sqlite3.c 4.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.7.6.3. 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 number of samples of an index that SQLite takes in order to
  293. ** construct a histogram of the table content when running ANALYZE
  294. ** and with SQLITE_ENABLE_STAT2
  295. */
  296. #define SQLITE_INDEX_SAMPLES 10
  297. /*
  298. ** The following macros are used to cast pointers to integers and
  299. ** integers to pointers. The way you do this varies from one compiler
  300. ** to the next, so we have developed the following set of #if statements
  301. ** to generate appropriate macros for a wide range of compilers.
  302. **
  303. ** The correct "ANSI" way to do this is to use the intptr_t type.
  304. ** Unfortunately, that typedef is not available on all compilers, or
  305. ** if it is available, it requires an #include of specific headers
  306. ** that vary from one machine to the next.
  307. **
  308. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  309. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  310. ** So we have to define the macros in different ways depending on the
  311. ** compiler.
  312. */
  313. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  314. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  315. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  316. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  317. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  318. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  319. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  320. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  321. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  322. #else /* Generates a warning - but it always works */
  323. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  324. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  325. #endif
  326. /*
  327. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  328. ** 0 means mutexes are permanently disable and the library is never
  329. ** threadsafe. 1 means the library is serialized which is the highest
  330. ** level of threadsafety. 2 means the libary is multithreaded - multiple
  331. ** threads can use SQLite as long as no two threads try to use the same
  332. ** database connection at the same time.
  333. **
  334. ** Older versions of SQLite used an optional THREADSAFE macro.
  335. ** We support that for legacy.
  336. */
  337. #if !defined(SQLITE_THREADSAFE)
  338. #if defined(THREADSAFE)
  339. # define SQLITE_THREADSAFE THREADSAFE
  340. #else
  341. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  342. #endif
  343. #endif
  344. /*
  345. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  346. ** It determines whether or not the features related to
  347. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  348. ** be overridden at runtime using the sqlite3_config() API.
  349. */
  350. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  351. # define SQLITE_DEFAULT_MEMSTATUS 1
  352. #endif
  353. /*
  354. ** Exactly one of the following macros must be defined in order to
  355. ** specify which memory allocation subsystem to use.
  356. **
  357. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  358. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  359. **
  360. ** (Historical note: There used to be several other options, but we've
  361. ** pared it down to just these two.)
  362. **
  363. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  364. ** the default.
  365. */
  366. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
  367. # error "At most one of the following compile-time configuration options\
  368. is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
  369. #endif
  370. #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
  371. # define SQLITE_SYSTEM_MALLOC 1
  372. #endif
  373. /*
  374. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  375. ** sizes of memory allocations below this value where possible.
  376. */
  377. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  378. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  379. #endif
  380. /*
  381. ** We need to define _XOPEN_SOURCE as follows in order to enable
  382. ** recursive mutexes on most Unix systems. But Mac OS X is different.
  383. ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
  384. ** so it is omitted there. See ticket #2673.
  385. **
  386. ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
  387. ** implemented on some systems. So we avoid defining it at all
  388. ** if it is already defined or if it is unneeded because we are
  389. ** not doing a threadsafe build. Ticket #2681.
  390. **
  391. ** See also ticket #2741.
  392. */
  393. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
  394. # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */
  395. #endif
  396. /*
  397. ** The TCL headers are only needed when compiling the TCL bindings.
  398. */
  399. #if defined(SQLITE_TCL) || defined(TCLSH)
  400. # include <tcl.h>
  401. #endif
  402. /*
  403. ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
  404. ** Setting NDEBUG makes the code smaller and run faster. So the following
  405. ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
  406. ** option is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  407. ** feature.
  408. */
  409. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  410. # define NDEBUG 1
  411. #endif
  412. /*
  413. ** The testcase() macro is used to aid in coverage testing. When
  414. ** doing coverage testing, the condition inside the argument to
  415. ** testcase() must be evaluated both true and false in order to
  416. ** get full branch coverage. The testcase() macro is inserted
  417. ** to help ensure adequate test coverage in places where simple
  418. ** condition/decision coverage is inadequate. For example, testcase()
  419. ** can be used to make sure boundary values are tested. For
  420. ** bitmask tests, testcase() can be used to make sure each bit
  421. ** is significant and used at least once. On switch statements
  422. ** where multiple cases go to the same block of code, testcase()
  423. ** can insure that all cases are evaluated.
  424. **
  425. */
  426. #ifdef SQLITE_COVERAGE_TEST
  427. SQLITE_PRIVATE void sqlite3Coverage(int);
  428. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  429. #else
  430. # define testcase(X)
  431. #endif
  432. /*
  433. ** The TESTONLY macro is used to enclose variable declarations or
  434. ** other bits of code that are needed to support the arguments
  435. ** within testcase() and assert() macros.
  436. */
  437. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  438. # define TESTONLY(X) X
  439. #else
  440. # define TESTONLY(X)
  441. #endif
  442. /*
  443. ** Sometimes we need a small amount of code such as a variable initialization
  444. ** to setup for a later assert() statement. We do not want this code to
  445. ** appear when assert() is disabled. The following macro is therefore
  446. ** used to contain that setup code. The "VVA" acronym stands for
  447. ** "Verification, Validation, and Accreditation". In other words, the
  448. ** code within VVA_ONLY() will only run during verification processes.
  449. */
  450. #ifndef NDEBUG
  451. # define VVA_ONLY(X) X
  452. #else
  453. # define VVA_ONLY(X)
  454. #endif
  455. /*
  456. ** The ALWAYS and NEVER macros surround boolean expressions which
  457. ** are intended to always be true or false, respectively. Such
  458. ** expressions could be omitted from the code completely. But they
  459. ** are included in a few cases in order to enhance the resilience
  460. ** of SQLite to unexpected behavior - to make the code "self-healing"
  461. ** or "ductile" rather than being "brittle" and crashing at the first
  462. ** hint of unplanned behavior.
  463. **
  464. ** In other words, ALWAYS and NEVER are added for defensive code.
  465. **
  466. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  467. ** be true and false so that the unreachable code then specify will
  468. ** not be counted as untested code.
  469. */
  470. #if defined(SQLITE_COVERAGE_TEST)
  471. # define ALWAYS(X) (1)
  472. # define NEVER(X) (0)
  473. #elif !defined(NDEBUG)
  474. # define ALWAYS(X) ((X)?1:(assert(0),0))
  475. # define NEVER(X) ((X)?(assert(0),1):0)
  476. #else
  477. # define ALWAYS(X) (X)
  478. # define NEVER(X) (X)
  479. #endif
  480. /*
  481. ** Return true (non-zero) if the input is a integer that is too large
  482. ** to fit in 32-bits. This macro is used inside of various testcase()
  483. ** macros to verify that we have tested SQLite for large-file support.
  484. */
  485. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  486. /*
  487. ** The macro unlikely() is a hint that surrounds a boolean
  488. ** expression that is usually false. Macro likely() surrounds
  489. ** a boolean expression that is usually true. GCC is able to
  490. ** use these hints to generate better code, sometimes.
  491. */
  492. #if defined(__GNUC__) && 0
  493. # define likely(X) __builtin_expect((X),1)
  494. # define unlikely(X) __builtin_expect((X),0)
  495. #else
  496. # define likely(X) !!(X)
  497. # define unlikely(X) !!(X)
  498. #endif
  499. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  500. /************** Begin file sqlite3.h *****************************************/
  501. /*
  502. ** 2001 September 15
  503. **
  504. ** The author disclaims copyright to this source code. In place of
  505. ** a legal notice, here is a blessing:
  506. **
  507. ** May you do good and not evil.
  508. ** May you find forgiveness for yourself and forgive others.
  509. ** May you share freely, never taking more than you give.
  510. **
  511. *************************************************************************
  512. ** This header file defines the interface that the SQLite library
  513. ** presents to client programs. If a C-function, structure, datatype,
  514. ** or constant definition does not appear in this file, then it is
  515. ** not a published API of SQLite, is subject to change without
  516. ** notice, and should not be referenced by programs that use SQLite.
  517. **
  518. ** Some of the definitions that are in this file are marked as
  519. ** "experimental". Experimental interfaces are normally new
  520. ** features recently added to SQLite. We do not anticipate changes
  521. ** to experimental interfaces but reserve the right to make minor changes
  522. ** if experience from use "in the wild" suggest such changes are prudent.
  523. **
  524. ** The official C-language API documentation for SQLite is derived
  525. ** from comments in this file. This file is the authoritative source
  526. ** on how SQLite interfaces are suppose to operate.
  527. **
  528. ** The name of this file under configuration management is "sqlite.h.in".
  529. ** The makefile makes some minor changes to this file (such as inserting
  530. ** the version number) and changes its name to "sqlite3.h" as
  531. ** part of the build process.
  532. */
  533. #ifndef _SQLITE3_H_
  534. #define _SQLITE3_H_
  535. #include <stdarg.h> /* Needed for the definition of va_list */
  536. /*
  537. ** Make sure we can call this stuff from C++.
  538. */
  539. #if 0
  540. extern "C" {
  541. #endif
  542. /*
  543. ** Add the ability to override 'extern'
  544. */
  545. #ifndef SQLITE_EXTERN
  546. # define SQLITE_EXTERN extern
  547. #endif
  548. #ifndef SQLITE_API
  549. # define SQLITE_API
  550. #endif
  551. /*
  552. ** These no-op macros are used in front of interfaces to mark those
  553. ** interfaces as either deprecated or experimental. New applications
  554. ** should not use deprecated interfaces - they are support for backwards
  555. ** compatibility only. Application writers should be aware that
  556. ** experimental interfaces are subject to change in point releases.
  557. **
  558. ** These macros used to resolve to various kinds of compiler magic that
  559. ** would generate warning messages when they were used. But that
  560. ** compiler magic ended up generating such a flurry of bug reports
  561. ** that we have taken it all out and gone back to using simple
  562. ** noop macros.
  563. */
  564. #define SQLITE_DEPRECATED
  565. #define SQLITE_EXPERIMENTAL
  566. /*
  567. ** Ensure these symbols were not defined by some previous header file.
  568. */
  569. #ifdef SQLITE_VERSION
  570. # undef SQLITE_VERSION
  571. #endif
  572. #ifdef SQLITE_VERSION_NUMBER
  573. # undef SQLITE_VERSION_NUMBER
  574. #endif
  575. /*
  576. ** CAPI3REF: Compile-Time Library Version Numbers
  577. **
  578. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  579. ** evaluates to a string literal that is the SQLite version in the
  580. ** format "X.Y.Z" where X is the major version number (always 3 for
  581. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  582. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  583. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  584. ** numbers used in [SQLITE_VERSION].)^
  585. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  586. ** be larger than the release from which it is derived. Either Y will
  587. ** be held constant and Z will be incremented or else Y will be incremented
  588. ** and Z will be reset to zero.
  589. **
  590. ** Since version 3.6.18, SQLite source code has been stored in the
  591. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  592. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  593. ** a string which identifies a particular check-in of SQLite
  594. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  595. ** string contains the date and time of the check-in (UTC) and an SHA1
  596. ** hash of the entire source tree.
  597. **
  598. ** See also: [sqlite3_libversion()],
  599. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  600. ** [sqlite_version()] and [sqlite_source_id()].
  601. */
  602. #define SQLITE_VERSION "3.7.6.3"
  603. #define SQLITE_VERSION_NUMBER 3007006
  604. #define SQLITE_SOURCE_ID "2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e"
  605. /*
  606. ** CAPI3REF: Run-Time Library Version Numbers
  607. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  608. **
  609. ** These interfaces provide the same information as the [SQLITE_VERSION],
  610. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  611. ** but are associated with the library instead of the header file. ^(Cautious
  612. ** programmers might include assert() statements in their application to
  613. ** verify that values returned by these interfaces match the macros in
  614. ** the header, and thus insure that the application is
  615. ** compiled with matching library and header files.
  616. **
  617. ** <blockquote><pre>
  618. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  619. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  620. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  621. ** </pre></blockquote>)^
  622. **
  623. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  624. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  625. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  626. ** function is provided for use in DLLs since DLL users usually do not have
  627. ** direct access to string constants within the DLL. ^The
  628. ** sqlite3_libversion_number() function returns an integer equal to
  629. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  630. ** a pointer to a string constant whose value is the same as the
  631. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  632. **
  633. ** See also: [sqlite_version()] and [sqlite_source_id()].
  634. */
  635. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  636. SQLITE_API const char *sqlite3_libversion(void);
  637. SQLITE_API const char *sqlite3_sourceid(void);
  638. SQLITE_API int sqlite3_libversion_number(void);
  639. /*
  640. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  641. **
  642. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  643. ** indicating whether the specified option was defined at
  644. ** compile time. ^The SQLITE_ prefix may be omitted from the
  645. ** option name passed to sqlite3_compileoption_used().
  646. **
  647. ** ^The sqlite3_compileoption_get() function allows iterating
  648. ** over the list of options that were defined at compile time by
  649. ** returning the N-th compile time option string. ^If N is out of range,
  650. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  651. ** prefix is omitted from any strings returned by
  652. ** sqlite3_compileoption_get().
  653. **
  654. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  655. ** and sqlite3_compileoption_get() may be omitted by specifying the
  656. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  657. **
  658. ** See also: SQL functions [sqlite_compileoption_used()] and
  659. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  660. */
  661. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  662. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  663. SQLITE_API const char *sqlite3_compileoption_get(int N);
  664. #endif
  665. /*
  666. ** CAPI3REF: Test To See If The Library Is Threadsafe
  667. **
  668. ** ^The sqlite3_threadsafe() function returns zero if and only if
  669. ** SQLite was compiled mutexing code omitted due to the
  670. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  671. **
  672. ** SQLite can be compiled with or without mutexes. When
  673. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  674. ** are enabled and SQLite is threadsafe. When the
  675. ** [SQLITE_THREADSAFE] macro is 0,
  676. ** the mutexes are omitted. Without the mutexes, it is not safe
  677. ** to use SQLite concurrently from more than one thread.
  678. **
  679. ** Enabling mutexes incurs a measurable performance penalty.
  680. ** So if speed is of utmost importance, it makes sense to disable
  681. ** the mutexes. But for maximum safety, mutexes should be enabled.
  682. ** ^The default behavior is for mutexes to be enabled.
  683. **
  684. ** This interface can be used by an application to make sure that the
  685. ** version of SQLite that it is linking against was compiled with
  686. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  687. **
  688. ** This interface only reports on the compile-time mutex setting
  689. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  690. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  691. ** can be fully or partially disabled using a call to [sqlite3_config()]
  692. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  693. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  694. ** sqlite3_threadsafe() function shows only the compile-time setting of
  695. ** thread safety, not any run-time changes to that setting made by
  696. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  697. ** is unchanged by calls to sqlite3_config().)^
  698. **
  699. ** See the [threading mode] documentation for additional information.
  700. */
  701. SQLITE_API int sqlite3_threadsafe(void);
  702. /*
  703. ** CAPI3REF: Database Connection Handle
  704. ** KEYWORDS: {database connection} {database connections}
  705. **
  706. ** Each open SQLite database is represented by a pointer to an instance of
  707. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  708. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  709. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  710. ** is its destructor. There are many other interfaces (such as
  711. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  712. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  713. ** sqlite3 object.
  714. */
  715. typedef struct sqlite3 sqlite3;
  716. /*
  717. ** CAPI3REF: 64-Bit Integer Types
  718. ** KEYWORDS: sqlite_int64 sqlite_uint64
  719. **
  720. ** Because there is no cross-platform way to specify 64-bit integer types
  721. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  722. **
  723. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  724. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  725. ** compatibility only.
  726. **
  727. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  728. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  729. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  730. ** between 0 and +18446744073709551615 inclusive.
  731. */
  732. #ifdef SQLITE_INT64_TYPE
  733. typedef SQLITE_INT64_TYPE sqlite_int64;
  734. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  735. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  736. typedef __int64 sqlite_int64;
  737. typedef unsigned __int64 sqlite_uint64;
  738. #else
  739. typedef long long int sqlite_int64;
  740. typedef unsigned long long int sqlite_uint64;
  741. #endif
  742. typedef sqlite_int64 sqlite3_int64;
  743. typedef sqlite_uint64 sqlite3_uint64;
  744. /*
  745. ** If compiling for a processor that lacks floating point support,
  746. ** substitute integer for floating-point.
  747. */
  748. #ifdef SQLITE_OMIT_FLOATING_POINT
  749. # define double sqlite3_int64
  750. #endif
  751. /*
  752. ** CAPI3REF: Closing A Database Connection
  753. **
  754. ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
  755. ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
  756. ** successfully destroyed and all associated resources are deallocated.
  757. **
  758. ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
  759. ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
  760. ** the [sqlite3] object prior to attempting to close the object. ^If
  761. ** sqlite3_close() is called on a [database connection] that still has
  762. ** outstanding [prepared statements] or [BLOB handles], then it returns
  763. ** SQLITE_BUSY.
  764. **
  765. ** ^If [sqlite3_close()] is invoked while a transaction is open,
  766. ** the transaction is automatically rolled back.
  767. **
  768. ** The C parameter to [sqlite3_close(C)] must be either a NULL
  769. ** pointer or an [sqlite3] object pointer obtained
  770. ** from [sqlite3_open()], [sqlite3_open16()], or
  771. ** [sqlite3_open_v2()], and not previously closed.
  772. ** ^Calling sqlite3_close() with a NULL pointer argument is a
  773. ** harmless no-op.
  774. */
  775. SQLITE_API int sqlite3_close(sqlite3 *);
  776. /*
  777. ** The type for a callback function.
  778. ** This is legacy and deprecated. It is included for historical
  779. ** compatibility and is not documented.
  780. */
  781. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  782. /*
  783. ** CAPI3REF: One-Step Query Execution Interface
  784. **
  785. ** The sqlite3_exec() interface is a convenience wrapper around
  786. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  787. ** that allows an application to run multiple statements of SQL
  788. ** without having to use a lot of C code.
  789. **
  790. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  791. ** semicolon-separate SQL statements passed into its 2nd argument,
  792. ** in the context of the [database connection] passed in as its 1st
  793. ** argument. ^If the callback function of the 3rd argument to
  794. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  795. ** coming out of the evaluated SQL statements. ^The 4th argument to
  796. ** to sqlite3_exec() is relayed through to the 1st argument of each
  797. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  798. ** is NULL, then no callback is ever invoked and result rows are
  799. ** ignored.
  800. **
  801. ** ^If an error occurs while evaluating the SQL statements passed into
  802. ** sqlite3_exec(), then execution of the current statement stops and
  803. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  804. ** is not NULL then any error message is written into memory obtained
  805. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  806. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  807. ** on error message strings returned through the 5th parameter of
  808. ** of sqlite3_exec() after the error message string is no longer needed.
  809. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  810. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  811. ** NULL before returning.
  812. **
  813. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  814. ** routine returns SQLITE_ABORT without invoking the callback again and
  815. ** without running any subsequent SQL statements.
  816. **
  817. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  818. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  819. ** callback is an array of pointers to strings obtained as if from
  820. ** [sqlite3_column_text()], one for each column. ^If an element of a
  821. ** result row is NULL then the corresponding string pointer for the
  822. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  823. ** sqlite3_exec() callback is an array of pointers to strings where each
  824. ** entry represents the name of corresponding result column as obtained
  825. ** from [sqlite3_column_name()].
  826. **
  827. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  828. ** to an empty string, or a pointer that contains only whitespace and/or
  829. ** SQL comments, then no SQL statements are evaluated and the database
  830. ** is not changed.
  831. **
  832. ** Restrictions:
  833. **
  834. ** <ul>
  835. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  836. ** is a valid and open [database connection].
  837. ** <li> The application must not close [database connection] specified by
  838. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  839. ** <li> The application must not modify the SQL statement text passed into
  840. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  841. ** </ul>
  842. */
  843. SQLITE_API int sqlite3_exec(
  844. sqlite3*, /* An open database */
  845. const char *sql, /* SQL to be evaluated */
  846. int (*callback)(void*,int,char**,char**), /* Callback function */
  847. void *, /* 1st argument to callback */
  848. char **errmsg /* Error msg written here */
  849. );
  850. /*
  851. ** CAPI3REF: Result Codes
  852. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  853. ** KEYWORDS: {result code} {result codes}
  854. **
  855. ** Many SQLite functions return an integer result code from the set shown
  856. ** here in order to indicates success or failure.
  857. **
  858. ** New error codes may be added in future versions of SQLite.
  859. **
  860. ** See also: [SQLITE_IOERR_READ | extended result codes]
  861. */
  862. #define SQLITE_OK 0 /* Successful result */
  863. /* beginning-of-error-codes */
  864. #define SQLITE_ERROR 1 /* SQL error or missing database */
  865. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  866. #define SQLITE_PERM 3 /* Access permission denied */
  867. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  868. #define SQLITE_BUSY 5 /* The database file is locked */
  869. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  870. #define SQLITE_NOMEM 7 /* A malloc() failed */
  871. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  872. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  873. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  874. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  875. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  876. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  877. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  878. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  879. #define SQLITE_EMPTY 16 /* Database is empty */
  880. #define SQLITE_SCHEMA 17 /* The database schema changed */
  881. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  882. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  883. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  884. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  885. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  886. #define SQLITE_AUTH 23 /* Authorization denied */
  887. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  888. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  889. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  890. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  891. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  892. /* end-of-error-codes */
  893. /*
  894. ** CAPI3REF: Extended Result Codes
  895. ** KEYWORDS: {extended error code} {extended error codes}
  896. ** KEYWORDS: {extended result code} {extended result codes}
  897. **
  898. ** In its default configuration, SQLite API routines return one of 26 integer
  899. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  900. ** these result codes are too coarse-grained. They do not provide as
  901. ** much information about problems as programmers might like. In an effort to
  902. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  903. ** support for additional result codes that provide more detailed information
  904. ** about errors. The extended result codes are enabled or disabled
  905. ** on a per database connection basis using the
  906. ** [sqlite3_extended_result_codes()] API.
  907. **
  908. ** Some of the available extended result codes are listed here.
  909. ** One may expect the number of extended result codes will be expand
  910. ** over time. Software that uses extended result codes should expect
  911. ** to see new result codes in future releases of SQLite.
  912. **
  913. ** The SQLITE_OK result code will never be extended. It will always
  914. ** be exactly zero.
  915. */
  916. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  917. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  918. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  919. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  920. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  921. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  922. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  923. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  924. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  925. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  926. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  927. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  928. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  929. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  930. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  931. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  932. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  933. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  934. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  935. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  936. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  937. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  938. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  939. /*
  940. ** CAPI3REF: Flags For File Open Operations
  941. **
  942. ** These bit values are intended for use in the
  943. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  944. ** in the 4th parameter to the xOpen method of the
  945. ** [sqlite3_vfs] object.
  946. */
  947. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  948. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  949. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  950. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  951. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  952. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  953. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  954. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  955. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  956. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  957. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  958. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  959. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  960. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  961. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  962. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  963. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  964. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  965. /* Reserved: 0x00F00000 */
  966. /*
  967. ** CAPI3REF: Device Characteristics
  968. **
  969. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  970. ** object returns an integer which is a vector of the these
  971. ** bit values expressing I/O characteristics of the mass storage
  972. ** device that holds the file that the [sqlite3_io_methods]
  973. ** refers to.
  974. **
  975. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  976. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  977. ** mean that writes of blocks that are nnn bytes in size and
  978. ** are aligned to an address which is an integer multiple of
  979. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  980. ** that when data is appended to a file, the data is appended
  981. ** first then the size of the file is extended, never the other
  982. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  983. ** information is written to disk in the same order as calls
  984. ** to xWrite().
  985. */
  986. #define SQLITE_IOCAP_ATOMIC 0x00000001
  987. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  988. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  989. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  990. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  991. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  992. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  993. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  994. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  995. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  996. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  997. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  998. /*
  999. ** CAPI3REF: File Locking Levels
  1000. **
  1001. ** SQLite uses one of these integer values as the second
  1002. ** argument to calls it makes to the xLock() and xUnlock() methods
  1003. ** of an [sqlite3_io_methods] object.
  1004. */
  1005. #define SQLITE_LOCK_NONE 0
  1006. #define SQLITE_LOCK_SHARED 1
  1007. #define SQLITE_LOCK_RESERVED 2
  1008. #define SQLITE_LOCK_PENDING 3
  1009. #define SQLITE_LOCK_EXCLUSIVE 4
  1010. /*
  1011. ** CAPI3REF: Synchronization Type Flags
  1012. **
  1013. ** When SQLite invokes the xSync() method of an
  1014. ** [sqlite3_io_methods] object it uses a combination of
  1015. ** these integer values as the second argument.
  1016. **
  1017. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1018. ** sync operation only needs to flush data to mass storage. Inode
  1019. ** information need not be flushed. If the lower four bits of the flag
  1020. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1021. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1022. ** to use Mac OS X style fullsync instead of fsync().
  1023. **
  1024. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1025. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1026. ** settings. The [synchronous pragma] determines when calls to the
  1027. ** xSync VFS method occur and applies uniformly across all platforms.
  1028. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1029. ** energetic or rigorous or forceful the sync operations are and
  1030. ** only make a difference on Mac OSX for the default SQLite code.
  1031. ** (Third-party VFS implementations might also make the distinction
  1032. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1033. ** operating systems natively supported by SQLite, only Mac OSX
  1034. ** cares about the difference.)
  1035. */
  1036. #define SQLITE_SYNC_NORMAL 0x00002
  1037. #define SQLITE_SYNC_FULL 0x00003
  1038. #define SQLITE_SYNC_DATAONLY 0x00010
  1039. /*
  1040. ** CAPI3REF: OS Interface Open File Handle
  1041. **
  1042. ** An [sqlite3_file] object represents an open file in the
  1043. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1044. ** implementations will
  1045. ** want to subclass this object by appending additional fields
  1046. ** for their own use. The pMethods entry is a pointer to an
  1047. ** [sqlite3_io_methods] object that defines methods for performing
  1048. ** I/O operations on the open file.
  1049. */
  1050. typedef struct sqlite3_file sqlite3_file;
  1051. struct sqlite3_file {
  1052. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1053. };
  1054. /*
  1055. ** CAPI3REF: OS Interface File Virtual Methods Object
  1056. **
  1057. ** Every file opened by the [sqlite3_vfs] xOpen method populates an
  1058. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1059. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1060. ** This object defines the methods used to perform various operations
  1061. ** against the open file represented by the [sqlite3_file] object.
  1062. **
  1063. ** If the xOpen method sets the sqlite3_file.pMethods element
  1064. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1065. ** may be invoked even if the xOpen reported that it failed. The
  1066. ** only way to prevent a call to xClose following a failed xOpen
  1067. ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
  1068. **
  1069. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1070. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1071. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1072. ** flag may be ORed in to indicate that only the data of the file
  1073. ** and not its inode needs to be synced.
  1074. **
  1075. ** The integer values to xLock() and xUnlock() are one of
  1076. ** <ul>
  1077. ** <li> [SQLITE_LOCK_NONE],
  1078. ** <li> [SQLITE_LOCK_SHARED],
  1079. ** <li> [SQLITE_LOCK_RESERVED],
  1080. ** <li> [SQLITE_LOCK_PENDING], or
  1081. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1082. ** </ul>
  1083. ** xLock() increases the lock. xUnlock() decreases the lock.
  1084. ** The xCheckReservedLock() method checks whether any database connection,
  1085. ** either in this process or in some other process, is holding a RESERVED,
  1086. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1087. ** if such a lock exists and false otherwise.
  1088. **
  1089. ** The xFileControl() method is a generic interface that allows custom
  1090. ** VFS implementations to directly control an open file using the
  1091. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1092. ** integer opcode. The third argument is a generic pointer intended to
  1093. ** point to a structure that may contain arguments or space in which to
  1094. ** write return values. Potential uses for xFileControl() might be
  1095. ** functions to enable blocking locks with timeouts, to change the
  1096. ** locking strategy (for example to use dot-file locks), to inquire
  1097. ** about the status of a lock, or to break stale locks. The SQLite
  1098. ** core reserves all opcodes less than 100 for its own use.
  1099. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  1100. ** Applications that define a custom xFileControl method should use opcodes
  1101. ** greater than 100 to avoid conflicts. VFS implementations should
  1102. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1103. ** recognize.
  1104. **
  1105. ** The xSectorSize() method returns the sector size of the
  1106. ** device that underlies the file. The sector size is the
  1107. ** minimum write that can be performed without disturbing
  1108. ** other bytes in the file. The xDeviceCharacteristics()
  1109. ** method returns a bit vector describing behaviors of the
  1110. ** underlying device:
  1111. **
  1112. ** <ul>
  1113. ** <li> [SQLITE_IOCAP_ATOMIC]
  1114. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1115. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1116. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1117. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1118. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1119. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1120. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1121. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1122. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1123. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1124. ** </ul>
  1125. **
  1126. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1127. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1128. ** mean that writes of blocks that are nnn bytes in size and
  1129. ** are aligned to an address which is an integer multiple of
  1130. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1131. ** that when data is appended to a file, the data is appended
  1132. ** first then the size of the file is extended, never the other
  1133. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1134. ** information is written to disk in the same order as calls
  1135. ** to xWrite().
  1136. **
  1137. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1138. ** in the unread portions of the buffer with zeros. A VFS that
  1139. ** fails to zero-fill short reads might seem to work. However,
  1140. ** failure to zero-fill short reads will eventually lead to
  1141. ** database corruption.
  1142. */
  1143. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1144. struct sqlite3_io_methods {
  1145. int iVersion;
  1146. int (*xClose)(sqlite3_file*);
  1147. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1148. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1149. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1150. int (*xSync)(sqlite3_file*, int flags);
  1151. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1152. int (*xLock)(sqlite3_file*, int);
  1153. int (*xUnlock)(sqlite3_file*, int);
  1154. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1155. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1156. int (*xSectorSize)(sqlite3_file*);
  1157. int (*xDeviceCharacteristics)(sqlite3_file*);
  1158. /* Methods above are valid for version 1 */
  1159. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1160. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1161. void (*xShmBarrier)(sqlite3_file*);
  1162. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1163. /* Methods above are valid for version 2 */
  1164. /* Additional methods may be added in future releases */
  1165. };
  1166. /*
  1167. ** CAPI3REF: Standard File Control Opcodes
  1168. **
  1169. ** These integer constants are opcodes for the xFileControl method
  1170. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1171. ** interface.
  1172. **
  1173. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1174. ** opcode causes the xFileControl method to write the current state of
  1175. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1176. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1177. ** into an integer that the pArg argument points to. This capability
  1178. ** is used during testing and only needs to be supported when SQLITE_TEST
  1179. ** is defined.
  1180. **
  1181. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1182. ** layer a hint of how large the database file will grow to be during the
  1183. ** current transaction. This hint is not guaranteed to be accurate but it
  1184. ** is often close. The underlying VFS might choose to preallocate database
  1185. ** file space based on this hint in order to help writes to the database
  1186. ** file run faster.
  1187. **
  1188. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1189. ** extends and truncates the database file in chunks of a size specified
  1190. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1191. ** point to an integer (type int) containing the new chunk-size to use
  1192. ** for the nominated database. Allocating database file space in large
  1193. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1194. ** improve performance on some systems.
  1195. **
  1196. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1197. ** to the [sqlite3_file] object associated with a particular database
  1198. ** connection. See the [sqlite3_file_control()] documentation for
  1199. ** additional information.
  1200. **
  1201. ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
  1202. ** SQLite and sent to all VFSes in place of a call to the xSync method
  1203. ** when the database connection has [PRAGMA synchronous] set to OFF.)^
  1204. ** Some specialized VFSes need this signal in order to operate correctly
  1205. ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
  1206. ** VFSes do not need this signal and should silently ignore this opcode.
  1207. ** Applications should not call [sqlite3_file_control()] with this
  1208. ** opcode as doing so may disrupt the operation of the specialized VFSes
  1209. ** that do require it.
  1210. */
  1211. #define SQLITE_FCNTL_LOCKSTATE 1
  1212. #define SQLITE_GET_LOCKPROXYFILE 2
  1213. #define SQLITE_SET_LOCKPROXYFILE 3
  1214. #define SQLITE_LAST_ERRNO 4
  1215. #define SQLITE_FCNTL_SIZE_HINT 5
  1216. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1217. #define SQLITE_FCNTL_FILE_POINTER 7
  1218. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1219. /*
  1220. ** CAPI3REF: Mutex Handle
  1221. **
  1222. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1223. ** abstract type for a mutex object. The SQLite core never looks
  1224. ** at the internal representation of an [sqlite3_mutex]. It only
  1225. ** deals with pointers to the [sqlite3_mutex] object.
  1226. **
  1227. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1228. */
  1229. typedef struct sqlite3_mutex sqlite3_mutex;
  1230. /*
  1231. ** CAPI3REF: OS Interface Object
  1232. **
  1233. ** An instance of the sqlite3_vfs object defines the interface between
  1234. ** the SQLite core and the underlying operating system. The "vfs"
  1235. ** in the name of the object stands for "virtual file system".
  1236. **
  1237. ** The value of the iVersion field is initially 1 but may be larger in
  1238. ** future versions of SQLite. Additional fields may be appended to this
  1239. ** object when the iVersion value is increased. Note that the structure
  1240. ** of the sqlite3_vfs object changes in the transaction between
  1241. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1242. ** modified.
  1243. **
  1244. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1245. ** structure used by this VFS. mxPathname is the maximum length of
  1246. ** a pathname in this VFS.
  1247. **
  1248. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1249. ** the pNext pointer. The [sqlite3_vfs_register()]
  1250. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1251. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1252. ** searches the list. Neither the application code nor the VFS
  1253. ** implementation should use the pNext pointer.
  1254. **
  1255. ** The pNext field is the only field in the sqlite3_vfs
  1256. ** structure that SQLite will ever modify. SQLite will only access
  1257. ** or modify this field while holding a particular static mutex.
  1258. ** The application should never modify anything within the sqlite3_vfs
  1259. ** object once the object has been registered.
  1260. **
  1261. ** The zName field holds the name of the VFS module. The name must
  1262. ** be unique across all VFS modules.
  1263. **
  1264. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1265. ** is either a NULL pointer or string obtained
  1266. ** from xFullPathname() with an optional suffix added.
  1267. ** ^If a suffix is added to the zFilename parameter, it will
  1268. ** consist of a single "-" character followed by no more than
  1269. ** 10 alphanumeric and/or "-" characters.
  1270. ** ^SQLite further guarantees that
  1271. ** the string will be valid and unchanged until xClose() is
  1272. ** called. Because of the previous sentence,
  1273. ** the [sqlite3_file] can safely store a pointer to the
  1274. ** filename if it needs to remember the filename for some reason.
  1275. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1276. ** must invent its own temporary name for the file. ^Whenever the
  1277. ** xFilename parameter is NULL it will also be the case that the
  1278. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1279. **
  1280. ** The flags argument to xOpen() includes all bits set in
  1281. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1282. ** or [sqlite3_open16()] is used, then flags includes at least
  1283. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1284. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1285. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1286. **
  1287. ** ^(SQLite will also add one of the following flags to the xOpen()
  1288. ** call, depending on the object being opened:
  1289. **
  1290. ** <ul>
  1291. ** <li> [SQLITE_OPEN_MAIN_DB]
  1292. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1293. ** <li> [SQLITE_OPEN_TEMP_DB]
  1294. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1295. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1296. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1297. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1298. ** <li> [SQLITE_OPEN_WAL]
  1299. ** </ul>)^
  1300. **
  1301. ** The file I/O implementation can use the object type flags to
  1302. ** change the way it deals with files. For example, an application
  1303. ** that does not care about crash recovery or rollback might make
  1304. ** the open of a journal file a no-op. Writes to this journal would
  1305. ** also be no-ops, and any attempt to read the journal would return
  1306. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1307. ** file will be doing page-aligned sector reads and writes in a random
  1308. ** order and set up its I/O subsystem accordingly.
  1309. **
  1310. ** SQLite might also add one of the following flags to the xOpen method:
  1311. **
  1312. ** <ul>
  1313. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1314. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1315. ** </ul>
  1316. **
  1317. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1318. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1319. ** will be set for TEMP databases and their journals, transient
  1320. ** databases, and subjournals.
  1321. **
  1322. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1323. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1324. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1325. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1326. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1327. ** be created, and that it is an error if it already exists.
  1328. ** It is <i>not</i> used to indicate the file should be opened
  1329. ** for exclusive access.
  1330. **
  1331. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1332. ** to hold the [sqlite3_file] structure passed as the third
  1333. ** argument to xOpen. The xOpen method does not have to
  1334. ** allocate the structure; it should just fill it in. Note that
  1335. ** the xOpen method must set the sqlite3_file.pMethods to either
  1336. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1337. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1338. ** element will be valid after xOpen returns regardless of the success
  1339. ** or failure of the xOpen call.
  1340. **
  1341. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1342. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1343. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1344. ** to test whether a file is at least readable. The file can be a
  1345. ** directory.
  1346. **
  1347. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1348. ** output buffer xFullPathname. The exact size of the output buffer
  1349. ** is also passed as a parameter to both methods. If the output buffer
  1350. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1351. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1352. ** to prevent this by setting mxPathname to a sufficiently large value.
  1353. **
  1354. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1355. ** interfaces are not strictly a part of the filesystem, but they are
  1356. ** included in the VFS structure for completeness.
  1357. ** The xRandomness() function attempts to return nBytes bytes
  1358. ** of good-quality randomness into zOut. The return value is
  1359. ** the actual number of bytes of randomness obtained.
  1360. ** The xSleep() method causes the calling thread to sleep for at
  1361. ** least the number of microseconds given. ^The xCurrentTime()
  1362. ** method returns a Julian Day Number for the current date and time as
  1363. ** a floating point value.
  1364. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1365. ** Day Number multipled by 86400000 (the number of milliseconds in
  1366. ** a 24-hour day).
  1367. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1368. ** date and time if that method is available (if iVersion is 2 or
  1369. ** greater and the function pointer is not NULL) and will fall back
  1370. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1371. **
  1372. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1373. ** are not used by the SQLite core. These optional interfaces are provided
  1374. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1375. ** system calls with functions under its control, a test program can
  1376. ** simulate faults and error conditions that would otherwise be difficult
  1377. ** or impossible to induce. The set of system calls that can be overridden
  1378. ** varies from one VFS to another, and from one version of the same VFS to the
  1379. ** next. Applications that use these interfaces must be prepared for any
  1380. ** or all of these interfaces to be NULL or for their behavior to change
  1381. ** from one release to the next. Applications must not attempt to access
  1382. ** any of these methods if the iVersion of the VFS is less than 3.
  1383. */
  1384. typedef struct sqlite3_vfs sqlite3_vfs;
  1385. typedef void (*sqlite3_syscall_ptr)(void);
  1386. struct sqlite3_vfs {
  1387. int iVersion; /* Structure version number (currently 3) */
  1388. int szOsFile; /* Size of subclassed sqlite3_file */
  1389. int mxPathname; /* Maximum file pathname length */
  1390. sqlite3_vfs *pNext; /* Next registered VFS */
  1391. const char *zName; /* Name of this virtual file system */
  1392. void *pAppData; /* Pointer to application-specific data */
  1393. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1394. int flags, int *pOutFlags);
  1395. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1396. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1397. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1398. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1399. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1400. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1401. void (*xDlClose)(sqlite3_vfs*, void*);
  1402. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1403. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1404. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1405. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1406. /*
  1407. ** The methods above are in version 1 of the sqlite_vfs object
  1408. ** definition. Those that follow are added in version 2 or later
  1409. */
  1410. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1411. /*
  1412. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1413. ** Those below are for version 3 and greater.
  1414. */
  1415. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1416. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1417. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1418. /*
  1419. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1420. ** New fields may be appended in figure versions. The iVersion
  1421. ** value will increment whenever this happens.
  1422. */
  1423. };
  1424. /*
  1425. ** CAPI3REF: Flags for the xAccess VFS method
  1426. **
  1427. ** These integer constants can be used as the third parameter to
  1428. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1429. ** what kind of permissions the xAccess method is looking for.
  1430. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1431. ** simply checks whether the file exists.
  1432. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1433. ** checks whether the named directory is both readable and writable
  1434. ** (in other words, if files can be added, removed, and renamed within
  1435. ** the directory).
  1436. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1437. ** [temp_store_directory pragma], though this could change in a future
  1438. ** release of SQLite.
  1439. ** With SQLITE_ACCESS_READ, the xAccess method
  1440. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1441. ** currently unused, though it might be used in a future release of
  1442. ** SQLite.
  1443. */
  1444. #define SQLITE_ACCESS_EXISTS 0
  1445. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1446. #define SQLITE_ACCESS_READ 2 /* Unused */
  1447. /*
  1448. ** CAPI3REF: Flags for the xShmLock VFS method
  1449. **
  1450. ** These integer constants define the various locking operations
  1451. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1452. ** following are the only legal combinations of flags to the
  1453. ** xShmLock method:
  1454. **
  1455. ** <ul>
  1456. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1457. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1458. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1459. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1460. ** </ul>
  1461. **
  1462. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1463. ** was given no the corresponding lock.
  1464. **
  1465. ** The xShmLock method can transition between unlocked and SHARED or
  1466. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1467. ** and EXCLUSIVE.
  1468. */
  1469. #define SQLITE_SHM_UNLOCK 1
  1470. #define SQLITE_SHM_LOCK 2
  1471. #define SQLITE_SHM_SHARED 4
  1472. #define SQLITE_SHM_EXCLUSIVE 8
  1473. /*
  1474. ** CAPI3REF: Maximum xShmLock index
  1475. **
  1476. ** The xShmLock method on [sqlite3_io_methods] may use values
  1477. ** between 0 and this upper bound as its "offset" argument.
  1478. ** The SQLite core will never attempt to acquire or release a
  1479. ** lock outside of this range
  1480. */
  1481. #define SQLITE_SHM_NLOCK 8
  1482. /*
  1483. ** CAPI3REF: Initialize The SQLite Library
  1484. **
  1485. ** ^The sqlite3_initialize() routine initializes the
  1486. ** SQLite library. ^The sqlite3_shutdown() routine
  1487. ** deallocates any resources that were allocated by sqlite3_initialize().
  1488. ** These routines are designed to aid in process initialization and
  1489. ** shutdown on embedded systems. Workstation applications using
  1490. ** SQLite normally do not need to invoke either of these routines.
  1491. **
  1492. ** A call to sqlite3_initialize() is an "effective" call if it is
  1493. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1494. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1495. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1496. ** of sqlite3_initialize() does any initialization. All other calls
  1497. ** are harmless no-ops.)^
  1498. **
  1499. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1500. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1501. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1502. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1503. **
  1504. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1505. ** is not. The sqlite3_shutdown() interface must only be called from a
  1506. ** single thread. All open [database connections] must be closed and all
  1507. ** other SQLite resources must be deallocated prior to invoking
  1508. ** sqlite3_shutdown().
  1509. **
  1510. ** Among other things, ^sqlite3_initialize() will invoke
  1511. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1512. ** will invoke sqlite3_os_end().
  1513. **
  1514. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1515. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1516. ** the library (perhaps it is unable to allocate a needed resource such
  1517. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1518. **
  1519. ** ^The sqlite3_initialize() routine is called internally by many other
  1520. ** SQLite interfaces so that an application usually does not need to
  1521. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1522. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1523. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1524. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1525. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1526. ** are omitted and the application must call sqlite3_initialize() directly
  1527. ** prior to using any other SQLite interface. For maximum portability,
  1528. ** it is recommended that applications always invoke sqlite3_initialize()
  1529. ** directly prior to using any other SQLite interface. Future releases
  1530. ** of SQLite may require this. In other words, the behavior exhibited
  1531. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1532. ** default behavior in some future release of SQLite.
  1533. **
  1534. ** The sqlite3_os_init() routine does operating-system specific
  1535. ** initialization of the SQLite library. The sqlite3_os_end()
  1536. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1537. ** performed by these routines include allocation or deallocation
  1538. ** of static resources, initialization of global variables,
  1539. ** setting up a default [sqlite3_vfs] module, or setting up
  1540. ** a default configuration using [sqlite3_config()].
  1541. **
  1542. ** The application should never invoke either sqlite3_os_init()
  1543. ** or sqlite3_os_end() directly. The application should only invoke
  1544. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1545. ** interface is called automatically by sqlite3_initialize() and
  1546. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1547. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1548. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1549. ** When [custom builds | built for other platforms]
  1550. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1551. ** option) the application must supply a suitable implementation for
  1552. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1553. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1554. ** must return [SQLITE_OK] on success and some other [error code] upon
  1555. ** failure.
  1556. */
  1557. SQLITE_API int sqlite3_initialize(void);
  1558. SQLITE_API int sqlite3_shutdown(void);
  1559. SQLITE_API int sqlite3_os_init(void);
  1560. SQLITE_API int sqlite3_os_end(void);
  1561. /*
  1562. ** CAPI3REF: Configuring The SQLite Library
  1563. **
  1564. ** The sqlite3_config() interface is used to make global configuration
  1565. ** changes to SQLite in order to tune SQLite to the specific needs of
  1566. ** the application. The default configuration is recommended for most
  1567. ** applications and so this routine is usually not necessary. It is
  1568. ** provided to support rare applications with unusual needs.
  1569. **
  1570. ** The sqlite3_config() interface is not threadsafe. The application
  1571. ** must insure that no other SQLite interfaces are invoked by other
  1572. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1573. ** may only be invoked prior to library initialization using
  1574. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1575. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1576. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1577. ** Note, however, that ^sqlite3_config() can be called as part of the
  1578. ** implementation of an application-defined [sqlite3_os_init()].
  1579. **
  1580. ** The first argument to sqlite3_config() is an integer
  1581. ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
  1582. ** what property of SQLite is to be configured. Subsequent arguments
  1583. ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
  1584. ** in the first argument.
  1585. **
  1586. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1587. ** ^If the option is unknown or SQLite is unable to set the option
  1588. ** then this routine returns a non-zero [error code].
  1589. */
  1590. SQLITE_API int sqlite3_config(int, ...);
  1591. /*
  1592. ** CAPI3REF: Configure database connections
  1593. **
  1594. ** The sqlite3_db_config() interface is used to make configuration
  1595. ** changes to a [database connection]. The interface is similar to
  1596. ** [sqlite3_config()] except that the changes apply to a single
  1597. ** [database connection] (specified in the first argument).
  1598. **
  1599. ** The second argument to sqlite3_db_config(D,V,...) is the
  1600. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1601. ** that indicates what aspect of the [database connection] is being configured.
  1602. ** Subsequent arguments vary depending on the configuration verb.
  1603. **
  1604. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1605. ** the call is considered successful.
  1606. */
  1607. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1608. /*
  1609. ** CAPI3REF: Memory Allocation Routines
  1610. **
  1611. ** An instance of this object defines the interface between SQLite
  1612. ** and low-level memory allocation routines.
  1613. **
  1614. ** This object is used in only one place in the SQLite interface.
  1615. ** A pointer to an instance of this object is the argument to
  1616. ** [sqlite3_config()] when the configuration option is
  1617. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1618. ** By creating an instance of this object
  1619. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1620. ** during configuration, an application can specify an alternative
  1621. ** memory allocation subsystem for SQLite to use for all of its
  1622. ** dynamic memory needs.
  1623. **
  1624. ** Note that SQLite comes with several [built-in memory allocators]
  1625. ** that are perfectly adequate for the overwhelming majority of applications
  1626. ** and that this object is only useful to a tiny minority of applications
  1627. ** with specialized memory allocation requirements. This object is
  1628. ** also used during testing of SQLite in order to specify an alternative
  1629. ** memory allocator that simulates memory out-of-memory conditions in
  1630. ** order to verify that SQLite recovers gracefully from such
  1631. ** conditions.
  1632. **
  1633. ** The xMalloc and xFree methods must work like the
  1634. ** malloc() and free() functions from the standard C library.
  1635. ** The xRealloc method must work like realloc() from the standard C library
  1636. ** with the exception that if the second argument to xRealloc is zero,
  1637. ** xRealloc must be a no-op - it must not perform any allocation or
  1638. ** deallocation. ^SQLite guarantees that the second argument to
  1639. ** xRealloc is always a value returned by a prior call to xRoundup.
  1640. ** And so in cases where xRoundup always returns a positive number,
  1641. ** xRealloc can perform exactly as the standard library realloc() and
  1642. ** still be in compliance with this specification.
  1643. **
  1644. ** xSize should return the allocated size of a memory allocation
  1645. ** previously obtained from xMalloc or xRealloc. The allocated size
  1646. ** is always at least as big as the requested size but may be larger.
  1647. **
  1648. ** The xRoundup method returns what would be the allocated size of
  1649. ** a memory allocation given a particular requested size. Most memory
  1650. ** allocators round up memory allocations at least to the next multiple
  1651. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1652. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1653. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1654. ** that causes the corresponding memory allocation to fail.
  1655. **
  1656. ** The xInit method initializes the memory allocator. (For example,
  1657. ** it might allocate any require mutexes or initialize internal data
  1658. ** structures. The xShutdown method is invoked (indirectly) by
  1659. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1660. ** by xInit. The pAppData pointer is used as the only parameter to
  1661. ** xInit and xShutdown.
  1662. **
  1663. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1664. ** the xInit method, so the xInit method need not be threadsafe. The
  1665. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1666. ** not need to be threadsafe either. For all other methods, SQLite
  1667. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1668. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1669. ** it is by default) and so the methods are automatically serialized.
  1670. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1671. ** methods must be threadsafe or else make their own arrangements for
  1672. ** serialization.
  1673. **
  1674. ** SQLite will never invoke xInit() more than once without an intervening
  1675. ** call to xShutdown().
  1676. */
  1677. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1678. struct sqlite3_mem_methods {
  1679. void *(*xMalloc)(int); /* Memory allocation function */
  1680. void (*xFree)(void*); /* Free a prior allocation */
  1681. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1682. int (*xSize)(void*); /* Return the size of an allocation */
  1683. int (*xRoundup)(int); /* Round up request size to allocation size */
  1684. int (*xInit)(void*); /* Initialize the memory allocator */
  1685. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1686. void *pAppData; /* Argument to xInit() and xShutdown() */
  1687. };
  1688. /*
  1689. ** CAPI3REF: Configuration Options
  1690. **
  1691. ** These constants are the available integer configuration options that
  1692. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1693. **
  1694. ** New configuration options may be added in future releases of SQLite.
  1695. ** Existing configuration options might be discontinued. Applications
  1696. ** should check the return code from [sqlite3_config()] to make sure that
  1697. ** the call worked. The [sqlite3_config()] interface will return a
  1698. ** non-zero [error code] if a discontinued or unsupported configuration option
  1699. ** is invoked.
  1700. **
  1701. ** <dl>
  1702. ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1703. ** <dd>There are no arguments to this option. ^This option sets the
  1704. ** [threading mode] to Single-thread. In other words, it disables
  1705. ** all mutexing and puts SQLite into a mode where it can only be used
  1706. ** by a single thread. ^If SQLite is compiled with
  1707. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1708. ** it is not possible to change the [threading mode] from its default
  1709. ** value of Single-thread and so [sqlite3_config()] will return
  1710. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1711. ** configuration option.</dd>
  1712. **
  1713. ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1714. ** <dd>There are no arguments to this option. ^This option sets the
  1715. ** [threading mode] to Multi-thread. In other words, it disables
  1716. ** mutexing on [database connection] and [prepared statement] objects.
  1717. ** The application is responsible for serializing access to
  1718. ** [database connections] and [prepared statements]. But other mutexes
  1719. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1720. ** environment as long as no two threads attempt to use the same
  1721. ** [database connection] at the same time. ^If SQLite is compiled with
  1722. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1723. ** it is not possible to set the Multi-thread [threading mode] and
  1724. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1725. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1726. **
  1727. ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1728. ** <dd>There are no arguments to this option. ^This option sets the
  1729. ** [threading mode] to Serialized. In other words, this option enables
  1730. ** all mutexes including the recursive
  1731. ** mutexes on [database connection] and [prepared statement] objects.
  1732. ** In this mode (which is the default when SQLite is compiled with
  1733. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1734. ** to [database connections] and [prepared statements] so that the
  1735. ** application is free to use the same [database connection] or the
  1736. ** same [prepared statement] in different threads at the same time.
  1737. ** ^If SQLite is compiled with
  1738. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1739. ** it is not possible to set the Serialized [threading mode] and
  1740. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1741. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1742. **
  1743. ** <dt>SQLITE_CONFIG_MALLOC</dt>
  1744. ** <dd> ^(This option takes a single argument which is a pointer to an
  1745. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1746. ** alternative low-level memory allocation routines to be used in place of
  1747. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1748. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1749. ** before the [sqlite3_config()] call returns.</dd>
  1750. **
  1751. ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1752. ** <dd> ^(This option takes a single argument which is a pointer to an
  1753. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1754. ** structure is filled with the currently defined memory allocation routines.)^
  1755. ** This option can be used to overload the default memory allocation
  1756. ** routines with a wrapper that simulations memory allocation failure or
  1757. ** tracks memory usage, for example. </dd>
  1758. **
  1759. ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1760. ** <dd> ^This option takes single argument of type int, interpreted as a
  1761. ** boolean, which enables or disables the collection of memory allocation
  1762. ** statistics. ^(When memory allocation statistics are disabled, the
  1763. ** following SQLite interfaces become non-operational:
  1764. ** <ul>
  1765. ** <li> [sqlite3_memory_used()]
  1766. ** <li> [sqlite3_memory_highwater()]
  1767. ** <li> [sqlite3_soft_heap_limit64()]
  1768. ** <li> [sqlite3_status()]
  1769. ** </ul>)^
  1770. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1771. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1772. ** allocation statistics are disabled by default.
  1773. ** </dd>
  1774. **
  1775. ** <dt>SQLITE_CONFIG_SCRATCH</dt>
  1776. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1777. ** scratch memory. There are three arguments: A pointer an 8-byte
  1778. ** aligned memory buffer from which the scratch allocations will be
  1779. ** drawn, the size of each scratch allocation (sz),
  1780. ** and the maximum number of scratch allocations (N). The sz
  1781. ** argument must be a multiple of 16.
  1782. ** The first argument must be a pointer to an 8-byte aligned buffer
  1783. ** of at least sz*N bytes of memory.
  1784. ** ^SQLite will use no more than two scratch buffers per thread. So
  1785. ** N should be set to twice the expected maximum number of threads.
  1786. ** ^SQLite will never require a scratch buffer that is more than 6
  1787. ** times the database page size. ^If SQLite needs needs additional
  1788. ** scratch memory beyond what is provided by this configuration option, then
  1789. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1790. **
  1791. ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1792. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1793. ** the database page cache with the default page cache implemenation.
  1794. ** This configuration should not be used if an application-define page
  1795. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
  1796. ** There are three arguments to this option: A pointer to 8-byte aligned
  1797. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1798. ** The sz argument should be the size of the largest database page
  1799. ** (a power of two between 512 and 32768) plus a little extra for each
  1800. ** page header. ^The page header size is 20 to 40 bytes depending on
  1801. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1802. ** to make sz a little too large. The first
  1803. ** argument should point to an allocation of at least sz*N bytes of memory.
  1804. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1805. ** memory needs for the first N pages that it adds to cache. ^If additional
  1806. ** page cache memory is needed beyond what is provided by this option, then
  1807. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1808. ** The pointer in the first argument must
  1809. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1810. ** will be undefined.</dd>
  1811. **
  1812. ** <dt>SQLITE_CONFIG_HEAP</dt>
  1813. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1814. ** for all of its dynamic memory allocation needs beyond those provided
  1815. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1816. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1817. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1818. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1819. ** to using its default memory allocator (the system malloc() implementation),
  1820. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1821. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1822. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1823. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1824. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1825. ** boundary or subsequent behavior of SQLite will be undefined.
  1826. ** The minimum allocation size is capped at 2^12. Reasonable values
  1827. ** for the minimum allocation size are 2^5 through 2^8.</dd>
  1828. **
  1829. ** <dt>SQLITE_CONFIG_MUTEX</dt>
  1830. ** <dd> ^(This option takes a single argument which is a pointer to an
  1831. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1832. ** alternative low-level mutex routines to be used in place
  1833. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  1834. ** content of the [sqlite3_mutex_methods] structure before the call to
  1835. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1836. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1837. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1838. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1839. ** return [SQLITE_ERROR].</dd>
  1840. **
  1841. ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1842. ** <dd> ^(This option takes a single argument which is a pointer to an
  1843. ** instance of the [sqlite3_mutex_methods] structure. The
  1844. ** [sqlite3_mutex_methods]
  1845. ** structure is filled with the currently defined mutex routines.)^
  1846. ** This option can be used to overload the default mutex allocation
  1847. ** routines with a wrapper used to track mutex usage for performance
  1848. ** profiling or testing, for example. ^If SQLite is compiled with
  1849. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1850. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1851. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1852. ** return [SQLITE_ERROR].</dd>
  1853. **
  1854. ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1855. ** <dd> ^(This option takes two arguments that determine the default
  1856. ** memory allocation for the lookaside memory allocator on each
  1857. ** [database connection]. The first argument is the
  1858. ** size of each lookaside buffer slot and the second is the number of
  1859. ** slots allocated to each database connection.)^ ^(This option sets the
  1860. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1861. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1862. ** configuration on individual connections.)^ </dd>
  1863. **
  1864. ** <dt>SQLITE_CONFIG_PCACHE</dt>
  1865. ** <dd> ^(This option takes a single argument which is a pointer to
  1866. ** an [sqlite3_pcache_methods] object. This object specifies the interface
  1867. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  1868. ** object and uses it for page cache memory allocations.</dd>
  1869. **
  1870. ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
  1871. ** <dd> ^(This option takes a single argument which is a pointer to an
  1872. ** [sqlite3_pcache_methods] object. SQLite copies of the current
  1873. ** page cache implementation into that object.)^ </dd>
  1874. **
  1875. ** <dt>SQLITE_CONFIG_LOG</dt>
  1876. ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1877. ** function with a call signature of void(*)(void*,int,const char*),
  1878. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1879. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1880. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1881. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1882. ** passed through as the first parameter to the application-defined logger
  1883. ** function whenever that function is invoked. ^The second parameter to
  1884. ** the logger function is a copy of the first parameter to the corresponding
  1885. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1886. ** [extended result code]. ^The third parameter passed to the logger is
  1887. ** log message after formatting via [sqlite3_snprintf()].
  1888. ** The SQLite logging interface is not reentrant; the logger function
  1889. ** supplied by the application must not invoke any SQLite interface.
  1890. ** In a multi-threaded application, the application-defined logger
  1891. ** function must be threadsafe. </dd>
  1892. **
  1893. ** </dl>
  1894. */
  1895. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1896. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1897. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1898. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1899. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1900. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1901. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1902. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1903. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1904. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1905. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1906. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1907. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1908. #define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */
  1909. #define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */
  1910. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1911. /*
  1912. ** CAPI3REF: Database Connection Configuration Options
  1913. **
  1914. ** These constants are the available integer configuration options that
  1915. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1916. **
  1917. ** New configuration options may be added in future releases of SQLite.
  1918. ** Existing configuration options might be discontinued. Applications
  1919. ** should check the return code from [sqlite3_db_config()] to make sure that
  1920. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1921. ** non-zero [error code] if a discontinued or unsupported configuration option
  1922. ** is invoked.
  1923. **
  1924. ** <dl>
  1925. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1926. ** <dd> ^This option takes three additional arguments that determine the
  1927. ** [lookaside memory allocator] configuration for the [database connection].
  1928. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1929. ** pointer to a memory buffer to use for lookaside memory.
  1930. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1931. ** may be NULL in which case SQLite will allocate the
  1932. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1933. ** size of each lookaside buffer slot. ^The third argument is the number of
  1934. ** slots. The size of the buffer in the first argument must be greater than
  1935. ** or equal to the product of the second and third arguments. The buffer
  1936. ** must be aligned to an 8-byte boundary. ^If the second argument to
  1937. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1938. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  1939. ** configuration for a database connection can only be changed when that
  1940. ** connection is not currently using lookaside memory, or in other words
  1941. ** when the "current value" returned by
  1942. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  1943. ** Any attempt to change the lookaside memory configuration when lookaside
  1944. ** memory is in use leaves the configuration unchanged and returns
  1945. ** [SQLITE_BUSY].)^</dd>
  1946. **
  1947. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  1948. ** <dd> ^This option is used to enable or disable the enforcement of
  1949. ** [foreign key constraints]. There should be two additional arguments.
  1950. ** The first argument is an integer which is 0 to disable FK enforcement,
  1951. ** positive to enable FK enforcement or negative to leave FK enforcement
  1952. ** unchanged. The second parameter is a pointer to an integer into which
  1953. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  1954. ** following this call. The second parameter may be a NULL pointer, in
  1955. ** which case the FK enforcement setting is not reported back. </dd>
  1956. **
  1957. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  1958. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  1959. ** There should be two additional arguments.
  1960. ** The first argument is an integer which is 0 to disable triggers,
  1961. ** positive to enable triggers or negative to leave the setting unchanged.
  1962. ** The second parameter is a pointer to an integer into which
  1963. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  1964. ** following this call. The second parameter may be a NULL pointer, in
  1965. ** which case the trigger setting is not reported back. </dd>
  1966. **
  1967. ** </dl>
  1968. */
  1969. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1970. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  1971. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  1972. /*
  1973. ** CAPI3REF: Enable Or Disable Extended Result Codes
  1974. **
  1975. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  1976. ** [extended result codes] feature of SQLite. ^The extended result
  1977. ** codes are disabled by default for historical compatibility.
  1978. */
  1979. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1980. /*
  1981. ** CAPI3REF: Last Insert Rowid
  1982. **
  1983. ** ^Each entry in an SQLite table has a unique 64-bit signed
  1984. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  1985. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1986. ** names are not also used by explicitly declared columns. ^If
  1987. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1988. ** is another alias for the rowid.
  1989. **
  1990. ** ^This routine returns the [rowid] of the most recent
  1991. ** successful [INSERT] into the database from the [database connection]
  1992. ** in the first argument. ^If no successful [INSERT]s
  1993. ** have ever occurred on that database connection, zero is returned.
  1994. **
  1995. ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
  1996. ** row is returned by this routine as long as the trigger is running.
  1997. ** But once the trigger terminates, the value returned by this routine
  1998. ** reverts to the last value inserted before the trigger fired.)^
  1999. **
  2000. ** ^An [INSERT] that fails due to a constraint violation is not a
  2001. ** successful [INSERT] and does not change the value returned by this
  2002. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2003. ** and INSERT OR ABORT make no changes to the return value of this
  2004. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2005. ** encounters a constraint violation, it does not fail. The
  2006. ** INSERT continues to completion after deleting rows that caused
  2007. ** the constraint problem so INSERT OR REPLACE will always change
  2008. ** the return value of this interface.)^
  2009. **
  2010. ** ^For the purposes of this routine, an [INSERT] is considered to
  2011. ** be successful even if it is subsequently rolled back.
  2012. **
  2013. ** This function is accessible to SQL statements via the
  2014. ** [last_insert_rowid() SQL function].
  2015. **
  2016. ** If a separate thread performs a new [INSERT] on the same
  2017. ** database connection while the [sqlite3_last_insert_rowid()]
  2018. ** function is running and thus changes the last insert [rowid],
  2019. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2020. ** unpredictable and might not equal either the old or the new
  2021. ** last insert [rowid].
  2022. */
  2023. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  2024. /*
  2025. ** CAPI3REF: Count The Number Of Rows Modified
  2026. **
  2027. ** ^This function returns the number of database rows that were changed
  2028. ** or inserted or deleted by the most recently completed SQL statement
  2029. ** on the [database connection] specified by the first parameter.
  2030. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  2031. ** or [DELETE] statement are counted. Auxiliary changes caused by
  2032. ** triggers or [foreign key actions] are not counted.)^ Use the
  2033. ** [sqlite3_total_changes()] function to find the total number of changes
  2034. ** including changes caused by triggers and foreign key actions.
  2035. **
  2036. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  2037. ** are not counted. Only real table changes are counted.
  2038. **
  2039. ** ^(A "row change" is a change to a single row of a single table
  2040. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  2041. ** are changed as side effects of [REPLACE] constraint resolution,
  2042. ** rollback, ABORT processing, [DROP TABLE], or by any other
  2043. ** mechanisms do not count as direct row changes.)^
  2044. **
  2045. ** A "trigger context" is a scope of execution that begins and
  2046. ** ends with the script of a [CREATE TRIGGER | trigger].
  2047. ** Most SQL statements are
  2048. ** evaluated outside of any trigger. This is the "top level"
  2049. ** trigger context. If a trigger fires from the top level, a
  2050. ** new trigger context is entered for the duration of that one
  2051. ** trigger. Subtriggers create subcontexts for their duration.
  2052. **
  2053. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  2054. ** not create a new trigger context.
  2055. **
  2056. ** ^This function returns the number of direct row changes in the
  2057. ** most recent INSERT, UPDATE, or DELETE statement within the same
  2058. ** trigger context.
  2059. **
  2060. ** ^Thus, when called from the top level, this function returns the
  2061. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  2062. ** that also occurred at the top level. ^(Within the body of a trigger,
  2063. ** the sqlite3_changes() interface can be called to find the number of
  2064. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  2065. ** statement within the body of the same trigger.
  2066. ** However, the number returned does not include changes
  2067. ** caused by subtriggers since those have their own context.)^
  2068. **
  2069. ** See also the [sqlite3_total_changes()] interface, the
  2070. ** [count_changes pragma], and the [changes() SQL function].
  2071. **
  2072. ** If a separate thread makes changes on the same database connection
  2073. ** while [sqlite3_changes()] is running then the value returned
  2074. ** is unpredictable and not meaningful.
  2075. */
  2076. SQLITE_API int sqlite3_changes(sqlite3*);
  2077. /*
  2078. ** CAPI3REF: Total Number Of Rows Modified
  2079. **
  2080. ** ^This function returns the number of row changes caused by [INSERT],
  2081. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  2082. ** ^(The count returned by sqlite3_total_changes() includes all changes
  2083. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  2084. ** [foreign key actions]. However,
  2085. ** the count does not include changes used to implement [REPLACE] constraints,
  2086. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  2087. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  2088. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  2089. ** are counted.)^
  2090. ** ^The sqlite3_total_changes() function counts the changes as soon as
  2091. ** the statement that makes them is completed (when the statement handle
  2092. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  2093. **
  2094. ** See also the [sqlite3_changes()] interface, the
  2095. ** [count_changes pragma], and the [total_changes() SQL function].
  2096. **
  2097. ** If a separate thread makes changes on the same database connection
  2098. ** while [sqlite3_total_changes()] is running then the value
  2099. ** returned is unpredictable and not meaningful.
  2100. */
  2101. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2102. /*
  2103. ** CAPI3REF: Interrupt A Long-Running Query
  2104. **
  2105. ** ^This function causes any pending database operation to abort and
  2106. ** return at its earliest opportunity. This routine is typically
  2107. ** called in response to a user action such as pressing "Cancel"
  2108. ** or Ctrl-C where the user wants a long query operation to halt
  2109. ** immediately.
  2110. **
  2111. ** ^It is safe to call this routine from a thread different from the
  2112. ** thread that is currently running the database operation. But it
  2113. ** is not safe to call this routine with a [database connection] that
  2114. ** is closed or might close before sqlite3_interrupt() returns.
  2115. **
  2116. ** ^If an SQL operation is very nearly finished at the time when
  2117. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2118. ** to be interrupted and might continue to completion.
  2119. **
  2120. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2121. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2122. ** that is inside an explicit transaction, then the entire transaction
  2123. ** will be rolled back automatically.
  2124. **
  2125. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2126. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2127. ** that are started after the sqlite3_interrupt() call and before the
  2128. ** running statements reaches zero are interrupted as if they had been
  2129. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2130. ** that are started after the running statement count reaches zero are
  2131. ** not effected by the sqlite3_interrupt().
  2132. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2133. ** SQL statements is a no-op and has no effect on SQL statements
  2134. ** that are started after the sqlite3_interrupt() call returns.
  2135. **
  2136. ** If the database connection closes while [sqlite3_interrupt()]
  2137. ** is running then bad things will likely happen.
  2138. */
  2139. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2140. /*
  2141. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2142. **
  2143. ** These routines are useful during command-line input to determine if the
  2144. ** currently entered text seems to form a complete SQL statement or
  2145. ** if additional input is needed before sending the text into
  2146. ** SQLite for parsing. ^These routines return 1 if the input string
  2147. ** appears to be a complete SQL statement. ^A statement is judged to be
  2148. ** complete if it ends with a semicolon token and is not a prefix of a
  2149. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2150. ** string literals or quoted identifier names or comments are not
  2151. ** independent tokens (they are part of the token in which they are
  2152. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2153. ** and comments that follow the final semicolon are ignored.
  2154. **
  2155. ** ^These routines return 0 if the statement is incomplete. ^If a
  2156. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2157. **
  2158. ** ^These routines do not parse the SQL statements thus
  2159. ** will not detect syntactically incorrect SQL.
  2160. **
  2161. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2162. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2163. ** automatically by sqlite3_complete16(). If that initialization fails,
  2164. ** then the return value from sqlite3_complete16() will be non-zero
  2165. ** regardless of whether or not the input SQL is complete.)^
  2166. **
  2167. ** The input to [sqlite3_complete()] must be a zero-terminated
  2168. ** UTF-8 string.
  2169. **
  2170. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2171. ** UTF-16 string in native byte order.
  2172. */
  2173. SQLITE_API int sqlite3_complete(const char *sql);
  2174. SQLITE_API int sqlite3_complete16(const void *sql);
  2175. /*
  2176. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2177. **
  2178. ** ^This routine sets a callback function that might be invoked whenever
  2179. ** an attempt is made to open a database table that another thread
  2180. ** or process has locked.
  2181. **
  2182. ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  2183. ** is returned immediately upon encountering the lock. ^If the busy callback
  2184. ** is not NULL, then the callback might be invoked with two arguments.
  2185. **
  2186. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2187. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2188. ** the busy handler callback is the number of times that the busy handler has
  2189. ** been invoked for this locking event. ^If the
  2190. ** busy callback returns 0, then no additional attempts are made to
  2191. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  2192. ** ^If the callback returns non-zero, then another attempt
  2193. ** is made to open the database for reading and the cycle repeats.
  2194. **
  2195. ** The presence of a busy handler does not guarantee that it will be invoked
  2196. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2197. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2198. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  2199. ** Consider a scenario where one process is holding a read lock that
  2200. ** it is trying to promote to a reserved lock and
  2201. ** a second process is holding a reserved lock that it is trying
  2202. ** to promote to an exclusive lock. The first process cannot proceed
  2203. ** because it is blocked by the second and the second process cannot
  2204. ** proceed because it is blocked by the first. If both processes
  2205. ** invoke the busy handlers, neither will make any progress. Therefore,
  2206. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2207. ** will induce the first process to release its read lock and allow
  2208. ** the second process to proceed.
  2209. **
  2210. ** ^The default busy callback is NULL.
  2211. **
  2212. ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2213. ** when SQLite is in the middle of a large transaction where all the
  2214. ** changes will not fit into the in-memory cache. SQLite will
  2215. ** already hold a RESERVED lock on the database file, but it needs
  2216. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2217. ** pages into the database file without harm to concurrent
  2218. ** readers. ^If it is unable to promote the lock, then the in-memory
  2219. ** cache will be left in an inconsistent state and so the error
  2220. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2221. ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
  2222. ** forces an automatic rollback of the changes. See the
  2223. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2224. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2225. ** this is important.
  2226. **
  2227. ** ^(There can only be a single busy handler defined for each
  2228. ** [database connection]. Setting a new busy handler clears any
  2229. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2230. ** will also set or clear the busy handler.
  2231. **
  2232. ** The busy callback should not take any actions which modify the
  2233. ** database connection that invoked the busy handler. Any such actions
  2234. ** result in undefined behavior.
  2235. **
  2236. ** A busy handler must not close the database connection
  2237. ** or [prepared statement] that invoked the busy handler.
  2238. */
  2239. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2240. /*
  2241. ** CAPI3REF: Set A Busy Timeout
  2242. **
  2243. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2244. ** for a specified amount of time when a table is locked. ^The handler
  2245. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2246. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2247. ** the handler returns 0 which causes [sqlite3_step()] to return
  2248. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2249. **
  2250. ** ^Calling this routine with an argument less than or equal to zero
  2251. ** turns off all busy handlers.
  2252. **
  2253. ** ^(There can only be a single busy handler for a particular
  2254. ** [database connection] any any given moment. If another busy handler
  2255. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2256. ** this routine, that other busy handler is cleared.)^
  2257. */
  2258. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2259. /*
  2260. ** CAPI3REF: Convenience Routines For Running Queries
  2261. **
  2262. ** This is a legacy interface that is preserved for backwards compatibility.
  2263. ** Use of this interface is not recommended.
  2264. **
  2265. ** Definition: A <b>result table</b> is memory data structure created by the
  2266. ** [sqlite3_get_table()] interface. A result table records the
  2267. ** complete query results from one or more queries.
  2268. **
  2269. ** The table conceptually has a number of rows and columns. But
  2270. ** these numbers are not part of the result table itself. These
  2271. ** numbers are obtained separately. Let N be the number of rows
  2272. ** and M be the number of columns.
  2273. **
  2274. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2275. ** There are (N+1)*M elements in the array. The first M pointers point
  2276. ** to zero-terminated strings that contain the names of the columns.
  2277. ** The remaining entries all point to query results. NULL values result
  2278. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2279. ** string representation as returned by [sqlite3_column_text()].
  2280. **
  2281. ** A result table might consist of one or more memory allocations.
  2282. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2283. ** A result table should be deallocated using [sqlite3_free_table()].
  2284. **
  2285. ** ^(As an example of the result table format, suppose a query result
  2286. ** is as follows:
  2287. **
  2288. ** <blockquote><pre>
  2289. ** Name | Age
  2290. ** -----------------------
  2291. ** Alice | 43
  2292. ** Bob | 28
  2293. ** Cindy | 21
  2294. ** </pre></blockquote>
  2295. **
  2296. ** There are two column (M==2) and three rows (N==3). Thus the
  2297. ** result table has 8 entries. Suppose the result table is stored
  2298. ** in an array names azResult. Then azResult holds this content:
  2299. **
  2300. ** <blockquote><pre>
  2301. ** azResult&#91;0] = "Name";
  2302. ** azResult&#91;1] = "Age";
  2303. ** azResult&#91;2] = "Alice";
  2304. ** azResult&#91;3] = "43";
  2305. ** azResult&#91;4] = "Bob";
  2306. ** azResult&#91;5] = "28";
  2307. ** azResult&#91;6] = "Cindy";
  2308. ** azResult&#91;7] = "21";
  2309. ** </pre></blockquote>)^
  2310. **
  2311. ** ^The sqlite3_get_table() function evaluates one or more
  2312. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2313. ** string of its 2nd parameter and returns a result table to the
  2314. ** pointer given in its 3rd parameter.
  2315. **
  2316. ** After the application has finished with the result from sqlite3_get_table(),
  2317. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2318. ** release the memory that was malloced. Because of the way the
  2319. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2320. ** function must not try to call [sqlite3_free()] directly. Only
  2321. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2322. **
  2323. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2324. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2325. ** to any internal data structures of SQLite. It uses only the public
  2326. ** interface defined here. As a consequence, errors that occur in the
  2327. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2328. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2329. ** [sqlite3_errmsg()].
  2330. */
  2331. SQLITE_API int sqlite3_get_table(
  2332. sqlite3 *db, /* An open database */
  2333. const char *zSql, /* SQL to be evaluated */
  2334. char ***pazResult, /* Results of the query */
  2335. int *pnRow, /* Number of result rows written here */
  2336. int *pnColumn, /* Number of result columns written here */
  2337. char **pzErrmsg /* Error msg written here */
  2338. );
  2339. SQLITE_API void sqlite3_free_table(char **result);
  2340. /*
  2341. ** CAPI3REF: Formatted String Printing Functions
  2342. **
  2343. ** These routines are work-alikes of the "printf()" family of functions
  2344. ** from the standard C library.
  2345. **
  2346. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2347. ** results into memory obtained from [sqlite3_malloc()].
  2348. ** The strings returned by these two routines should be
  2349. ** released by [sqlite3_free()]. ^Both routines return a
  2350. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2351. ** memory to hold the resulting string.
  2352. **
  2353. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2354. ** the standard C library. The result is written into the
  2355. ** buffer supplied as the second parameter whose size is given by
  2356. ** the first parameter. Note that the order of the
  2357. ** first two parameters is reversed from snprintf().)^ This is an
  2358. ** historical accident that cannot be fixed without breaking
  2359. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2360. ** returns a pointer to its buffer instead of the number of
  2361. ** characters actually written into the buffer.)^ We admit that
  2362. ** the number of characters written would be a more useful return
  2363. ** value but we cannot change the implementation of sqlite3_snprintf()
  2364. ** now without breaking compatibility.
  2365. **
  2366. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2367. ** guarantees that the buffer is always zero-terminated. ^The first
  2368. ** parameter "n" is the total size of the buffer, including space for
  2369. ** the zero terminator. So the longest string that can be completely
  2370. ** written will be n-1 characters.
  2371. **
  2372. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2373. **
  2374. ** These routines all implement some additional formatting
  2375. ** options that are useful for constructing SQL statements.
  2376. ** All of the usual printf() formatting options apply. In addition, there
  2377. ** is are "%q", "%Q", and "%z" options.
  2378. **
  2379. ** ^(The %q option works like %s in that it substitutes a null-terminated
  2380. ** string from the argument list. But %q also doubles every '\'' character.
  2381. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2382. ** character it escapes that character and allows it to be inserted into
  2383. ** the string.
  2384. **
  2385. ** For example, assume the string variable zText contains text as follows:
  2386. **
  2387. ** <blockquote><pre>
  2388. ** char *zText = "It's a happy day!";
  2389. ** </pre></blockquote>
  2390. **
  2391. ** One can use this text in an SQL statement as follows:
  2392. **
  2393. ** <blockquote><pre>
  2394. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2395. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2396. ** sqlite3_free(zSQL);
  2397. ** </pre></blockquote>
  2398. **
  2399. ** Because the %q format string is used, the '\'' character in zText
  2400. ** is escaped and the SQL generated is as follows:
  2401. **
  2402. ** <blockquote><pre>
  2403. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2404. ** </pre></blockquote>
  2405. **
  2406. ** This is correct. Had we used %s instead of %q, the generated SQL
  2407. ** would have looked like this:
  2408. **
  2409. ** <blockquote><pre>
  2410. ** INSERT INTO table1 VALUES('It's a happy day!');
  2411. ** </pre></blockquote>
  2412. **
  2413. ** This second example is an SQL syntax error. As a general rule you should
  2414. ** always use %q instead of %s when inserting text into a string literal.
  2415. **
  2416. ** ^(The %Q option works like %q except it also adds single quotes around
  2417. ** the outside of the total string. Additionally, if the parameter in the
  2418. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2419. ** single quotes).)^ So, for example, one could say:
  2420. **
  2421. ** <blockquote><pre>
  2422. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2423. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2424. ** sqlite3_free(zSQL);
  2425. ** </pre></blockquote>
  2426. **
  2427. ** The code above will render a correct SQL statement in the zSQL
  2428. ** variable even if the zText variable is a NULL pointer.
  2429. **
  2430. ** ^(The "%z" formatting option works like "%s" but with the
  2431. ** addition that after the string has been read and copied into
  2432. ** the result, [sqlite3_free()] is called on the input string.)^
  2433. */
  2434. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2435. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2436. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2437. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2438. /*
  2439. ** CAPI3REF: Memory Allocation Subsystem
  2440. **
  2441. ** The SQLite core uses these three routines for all of its own
  2442. ** internal memory allocation needs. "Core" in the previous sentence
  2443. ** does not include operating-system specific VFS implementation. The
  2444. ** Windows VFS uses native malloc() and free() for some operations.
  2445. **
  2446. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2447. ** of memory at least N bytes in length, where N is the parameter.
  2448. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2449. ** memory, it returns a NULL pointer. ^If the parameter N to
  2450. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2451. ** a NULL pointer.
  2452. **
  2453. ** ^Calling sqlite3_free() with a pointer previously returned
  2454. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2455. ** that it might be reused. ^The sqlite3_free() routine is
  2456. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2457. ** to sqlite3_free() is harmless. After being freed, memory
  2458. ** should neither be read nor written. Even reading previously freed
  2459. ** memory might result in a segmentation fault or other severe error.
  2460. ** Memory corruption, a segmentation fault, or other severe error
  2461. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2462. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2463. **
  2464. ** ^(The sqlite3_realloc() interface attempts to resize a
  2465. ** prior memory allocation to be at least N bytes, where N is the
  2466. ** second parameter. The memory allocation to be resized is the first
  2467. ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  2468. ** is a NULL pointer then its behavior is identical to calling
  2469. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2470. ** ^If the second parameter to sqlite3_realloc() is zero or
  2471. ** negative then the behavior is exactly the same as calling
  2472. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2473. ** ^sqlite3_realloc() returns a pointer to a memory allocation
  2474. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2475. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2476. ** of the prior allocation are copied into the beginning of buffer returned
  2477. ** by sqlite3_realloc() and the prior allocation is freed.
  2478. ** ^If sqlite3_realloc() returns NULL, then the prior allocation
  2479. ** is not freed.
  2480. **
  2481. ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2482. ** is always aligned to at least an 8 byte boundary, or to a
  2483. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2484. ** option is used.
  2485. **
  2486. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2487. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2488. ** implementation of these routines to be omitted. That capability
  2489. ** is no longer provided. Only built-in memory allocators can be used.
  2490. **
  2491. ** The Windows OS interface layer calls
  2492. ** the system malloc() and free() directly when converting
  2493. ** filenames between the UTF-8 encoding used by SQLite
  2494. ** and whatever filename encoding is used by the particular Windows
  2495. ** installation. Memory allocation errors are detected, but
  2496. ** they are reported back as [SQLITE_CANTOPEN] or
  2497. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2498. **
  2499. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2500. ** must be either NULL or else pointers obtained from a prior
  2501. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2502. ** not yet been released.
  2503. **
  2504. ** The application must not read or write any part of
  2505. ** a block of memory after it has been released using
  2506. ** [sqlite3_free()] or [sqlite3_realloc()].
  2507. */
  2508. SQLITE_API void *sqlite3_malloc(int);
  2509. SQLITE_API void *sqlite3_realloc(void*, int);
  2510. SQLITE_API void sqlite3_free(void*);
  2511. /*
  2512. ** CAPI3REF: Memory Allocator Statistics
  2513. **
  2514. ** SQLite provides these two interfaces for reporting on the status
  2515. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2516. ** routines, which form the built-in memory allocation subsystem.
  2517. **
  2518. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2519. ** of memory currently outstanding (malloced but not freed).
  2520. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2521. ** value of [sqlite3_memory_used()] since the high-water mark
  2522. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2523. ** [sqlite3_memory_highwater()] include any overhead
  2524. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2525. ** but not overhead added by the any underlying system library
  2526. ** routines that [sqlite3_malloc()] may call.
  2527. **
  2528. ** ^The memory high-water mark is reset to the current value of
  2529. ** [sqlite3_memory_used()] if and only if the parameter to
  2530. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2531. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2532. ** prior to the reset.
  2533. */
  2534. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2535. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2536. /*
  2537. ** CAPI3REF: Pseudo-Random Number Generator
  2538. **
  2539. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2540. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2541. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2542. ** the build-in random() and randomblob() SQL functions. This interface allows
  2543. ** applications to access the same PRNG for other purposes.
  2544. **
  2545. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2546. **
  2547. ** ^The first time this routine is invoked (either internally or by
  2548. ** the application) the PRNG is seeded using randomness obtained
  2549. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2550. ** ^On all subsequent invocations, the pseudo-randomness is generated
  2551. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2552. ** method.
  2553. */
  2554. SQLITE_API void sqlite3_randomness(int N, void *P);
  2555. /*
  2556. ** CAPI3REF: Compile-Time Authorization Callbacks
  2557. **
  2558. ** ^This routine registers an authorizer callback with a particular
  2559. ** [database connection], supplied in the first argument.
  2560. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2561. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2562. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2563. ** points during the compilation process, as logic is being created
  2564. ** to perform various actions, the authorizer callback is invoked to
  2565. ** see if those actions are allowed. ^The authorizer callback should
  2566. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2567. ** specific action but allow the SQL statement to continue to be
  2568. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2569. ** rejected with an error. ^If the authorizer callback returns
  2570. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2571. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2572. ** the authorizer will fail with an error message.
  2573. **
  2574. ** When the callback returns [SQLITE_OK], that means the operation
  2575. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2576. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2577. ** authorizer will fail with an error message explaining that
  2578. ** access is denied.
  2579. **
  2580. ** ^The first parameter to the authorizer callback is a copy of the third
  2581. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2582. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2583. ** the particular action to be authorized. ^The third through sixth parameters
  2584. ** to the callback are zero-terminated strings that contain additional
  2585. ** details about the action to be authorized.
  2586. **
  2587. ** ^If the action code is [SQLITE_READ]
  2588. ** and the callback returns [SQLITE_IGNORE] then the
  2589. ** [prepared statement] statement is constructed to substitute
  2590. ** a NULL value in place of the table column that would have
  2591. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2592. ** return can be used to deny an untrusted user access to individual
  2593. ** columns of a table.
  2594. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2595. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2596. ** [truncate optimization] is disabled and all rows are deleted individually.
  2597. **
  2598. ** An authorizer is used when [sqlite3_prepare | preparing]
  2599. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2600. ** do not try to access data they are not allowed to see, or that they do not
  2601. ** try to execute malicious statements that damage the database. For
  2602. ** example, an application may allow a user to enter arbitrary
  2603. ** SQL queries for evaluation by a database. But the application does
  2604. ** not want the user to be able to make arbitrary changes to the
  2605. ** database. An authorizer could then be put in place while the
  2606. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2607. ** disallows everything except [SELECT] statements.
  2608. **
  2609. ** Applications that need to process SQL from untrusted sources
  2610. ** might also consider lowering resource limits using [sqlite3_limit()]
  2611. ** and limiting database size using the [max_page_count] [PRAGMA]
  2612. ** in addition to using an authorizer.
  2613. **
  2614. ** ^(Only a single authorizer can be in place on a database connection
  2615. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2616. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2617. ** The authorizer is disabled by default.
  2618. **
  2619. ** The authorizer callback must not do anything that will modify
  2620. ** the database connection that invoked the authorizer callback.
  2621. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2622. ** database connections for the meaning of "modify" in this paragraph.
  2623. **
  2624. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2625. ** statement might be re-prepared during [sqlite3_step()] due to a
  2626. ** schema change. Hence, the application should ensure that the
  2627. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2628. **
  2629. ** ^Note that the authorizer callback is invoked only during
  2630. ** [sqlite3_prepare()] or its variants. Authorization is not
  2631. ** performed during statement evaluation in [sqlite3_step()], unless
  2632. ** as stated in the previous paragraph, sqlite3_step() invokes
  2633. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2634. */
  2635. SQLITE_API int sqlite3_set_authorizer(
  2636. sqlite3*,
  2637. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2638. void *pUserData
  2639. );
  2640. /*
  2641. ** CAPI3REF: Authorizer Return Codes
  2642. **
  2643. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2644. ** return either [SQLITE_OK] or one of these two constants in order
  2645. ** to signal SQLite whether or not the action is permitted. See the
  2646. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2647. ** information.
  2648. */
  2649. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2650. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2651. /*
  2652. ** CAPI3REF: Authorizer Action Codes
  2653. **
  2654. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2655. ** that is invoked to authorize certain SQL statement actions. The
  2656. ** second parameter to the callback is an integer code that specifies
  2657. ** what action is being authorized. These are the integer action codes that
  2658. ** the authorizer callback may be passed.
  2659. **
  2660. ** These action code values signify what kind of operation is to be
  2661. ** authorized. The 3rd and 4th parameters to the authorization
  2662. ** callback function will be parameters or NULL depending on which of these
  2663. ** codes is used as the second parameter. ^(The 5th parameter to the
  2664. ** authorizer callback is the name of the database ("main", "temp",
  2665. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2666. ** is the name of the inner-most trigger or view that is responsible for
  2667. ** the access attempt or NULL if this access attempt is directly from
  2668. ** top-level SQL code.
  2669. */
  2670. /******************************************* 3rd ************ 4th ***********/
  2671. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2672. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2673. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2674. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2675. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2676. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2677. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2678. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2679. #define SQLITE_DELETE 9 /* Table Name NULL */
  2680. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2681. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2682. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2683. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2684. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2685. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2686. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2687. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2688. #define SQLITE_INSERT 18 /* Table Name NULL */
  2689. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2690. #define SQLITE_READ 20 /* Table Name Column Name */
  2691. #define SQLITE_SELECT 21 /* NULL NULL */
  2692. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2693. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2694. #define SQLITE_ATTACH 24 /* Filename NULL */
  2695. #define SQLITE_DETACH 25 /* Database Name NULL */
  2696. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2697. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2698. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2699. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2700. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2701. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2702. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2703. #define SQLITE_COPY 0 /* No longer used */
  2704. /*
  2705. ** CAPI3REF: Tracing And Profiling Functions
  2706. **
  2707. ** These routines register callback functions that can be used for
  2708. ** tracing and profiling the execution of SQL statements.
  2709. **
  2710. ** ^The callback function registered by sqlite3_trace() is invoked at
  2711. ** various times when an SQL statement is being run by [sqlite3_step()].
  2712. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2713. ** SQL statement text as the statement first begins executing.
  2714. ** ^(Additional sqlite3_trace() callbacks might occur
  2715. ** as each triggered subprogram is entered. The callbacks for triggers
  2716. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2717. **
  2718. ** ^The callback function registered by sqlite3_profile() is invoked
  2719. ** as each SQL statement finishes. ^The profile callback contains
  2720. ** the original statement text and an estimate of wall-clock time
  2721. ** of how long that statement took to run. ^The profile callback
  2722. ** time is in units of nanoseconds, however the current implementation
  2723. ** is only capable of millisecond resolution so the six least significant
  2724. ** digits in the time are meaningless. Future versions of SQLite
  2725. ** might provide greater resolution on the profiler callback. The
  2726. ** sqlite3_profile() function is considered experimental and is
  2727. ** subject to change in future versions of SQLite.
  2728. */
  2729. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2730. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2731. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2732. /*
  2733. ** CAPI3REF: Query Progress Callbacks
  2734. **
  2735. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2736. ** function X to be invoked periodically during long running calls to
  2737. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2738. ** database connection D. An example use for this
  2739. ** interface is to keep a GUI updated during a large query.
  2740. **
  2741. ** ^The parameter P is passed through as the only parameter to the
  2742. ** callback function X. ^The parameter N is the number of
  2743. ** [virtual machine instructions] that are evaluated between successive
  2744. ** invocations of the callback X.
  2745. **
  2746. ** ^Only a single progress handler may be defined at one time per
  2747. ** [database connection]; setting a new progress handler cancels the
  2748. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2749. ** ^The progress handler is also disabled by setting N to a value less
  2750. ** than 1.
  2751. **
  2752. ** ^If the progress callback returns non-zero, the operation is
  2753. ** interrupted. This feature can be used to implement a
  2754. ** "Cancel" button on a GUI progress dialog box.
  2755. **
  2756. ** The progress handler callback must not do anything that will modify
  2757. ** the database connection that invoked the progress handler.
  2758. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2759. ** database connections for the meaning of "modify" in this paragraph.
  2760. **
  2761. */
  2762. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2763. /*
  2764. ** CAPI3REF: Opening A New Database Connection
  2765. **
  2766. ** ^These routines open an SQLite database file whose name is given by the
  2767. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2768. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2769. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2770. ** returned in *ppDb, even if an error occurs. The only exception is that
  2771. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2772. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2773. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2774. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2775. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2776. ** an English language description of the error following a failure of any
  2777. ** of the sqlite3_open() routines.
  2778. **
  2779. ** ^The default encoding for the database will be UTF-8 if
  2780. ** sqlite3_open() or sqlite3_open_v2() is called and
  2781. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  2782. **
  2783. ** Whether or not an error occurs when it is opened, resources
  2784. ** associated with the [database connection] handle should be released by
  2785. ** passing it to [sqlite3_close()] when it is no longer required.
  2786. **
  2787. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2788. ** except that it accepts two additional parameters for additional control
  2789. ** over the new database connection. ^(The flags parameter to
  2790. ** sqlite3_open_v2() can take one of
  2791. ** the following three values, optionally combined with the
  2792. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2793. ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
  2794. **
  2795. ** <dl>
  2796. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2797. ** <dd>The database is opened in read-only mode. If the database does not
  2798. ** already exist, an error is returned.</dd>)^
  2799. **
  2800. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2801. ** <dd>The database is opened for reading and writing if possible, or reading
  2802. ** only if the file is write protected by the operating system. In either
  2803. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2804. **
  2805. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2806. ** <dd>The database is opened for reading and writing, and is created if
  2807. ** it does not already exist. This is the behavior that is always used for
  2808. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2809. ** </dl>
  2810. **
  2811. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2812. ** combinations shown above or one of the combinations shown above combined
  2813. ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
  2814. ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
  2815. ** then the behavior is undefined.
  2816. **
  2817. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2818. ** opens in the multi-thread [threading mode] as long as the single-thread
  2819. ** mode has not been set at compile-time or start-time. ^If the
  2820. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2821. ** in the serialized [threading mode] unless single-thread was
  2822. ** previously selected at compile-time or start-time.
  2823. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2824. ** eligible to use [shared cache mode], regardless of whether or not shared
  2825. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2826. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2827. ** participate in [shared cache mode] even if it is enabled.
  2828. **
  2829. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2830. ** is created for the connection. ^This in-memory database will vanish when
  2831. ** the database connection is closed. Future versions of SQLite might
  2832. ** make use of additional special filenames that begin with the ":" character.
  2833. ** It is recommended that when a database filename actually does begin with
  2834. ** a ":" character you should prefix the filename with a pathname such as
  2835. ** "./" to avoid ambiguity.
  2836. **
  2837. ** ^If the filename is an empty string, then a private, temporary
  2838. ** on-disk database will be created. ^This private database will be
  2839. ** automatically deleted as soon as the database connection is closed.
  2840. **
  2841. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2842. ** [sqlite3_vfs] object that defines the operating system interface that
  2843. ** the new database connection should use. ^If the fourth parameter is
  2844. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2845. **
  2846. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  2847. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  2848. ** codepage is currently defined. Filenames containing international
  2849. ** characters must be converted to UTF-8 prior to passing them into
  2850. ** sqlite3_open() or sqlite3_open_v2().
  2851. */
  2852. SQLITE_API int sqlite3_open(
  2853. const char *filename, /* Database filename (UTF-8) */
  2854. sqlite3 **ppDb /* OUT: SQLite db handle */
  2855. );
  2856. SQLITE_API int sqlite3_open16(
  2857. const void *filename, /* Database filename (UTF-16) */
  2858. sqlite3 **ppDb /* OUT: SQLite db handle */
  2859. );
  2860. SQLITE_API int sqlite3_open_v2(
  2861. const char *filename, /* Database filename (UTF-8) */
  2862. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2863. int flags, /* Flags */
  2864. const char *zVfs /* Name of VFS module to use */
  2865. );
  2866. /*
  2867. ** CAPI3REF: Error Codes And Messages
  2868. **
  2869. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  2870. ** [extended result code] for the most recent failed sqlite3_* API call
  2871. ** associated with a [database connection]. If a prior API call failed
  2872. ** but the most recent API call succeeded, the return value from
  2873. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  2874. ** interface is the same except that it always returns the
  2875. ** [extended result code] even when extended result codes are
  2876. ** disabled.
  2877. **
  2878. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  2879. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  2880. ** ^(Memory to hold the error message string is managed internally.
  2881. ** The application does not need to worry about freeing the result.
  2882. ** However, the error string might be overwritten or deallocated by
  2883. ** subsequent calls to other SQLite interface functions.)^
  2884. **
  2885. ** When the serialized [threading mode] is in use, it might be the
  2886. ** case that a second error occurs on a separate thread in between
  2887. ** the time of the first error and the call to these interfaces.
  2888. ** When that happens, the second error will be reported since these
  2889. ** interfaces always report the most recent result. To avoid
  2890. ** this, each thread can obtain exclusive use of the [database connection] D
  2891. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  2892. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  2893. ** all calls to the interfaces listed here are completed.
  2894. **
  2895. ** If an interface fails with SQLITE_MISUSE, that means the interface
  2896. ** was invoked incorrectly by the application. In that case, the
  2897. ** error code and message may or may not be set.
  2898. */
  2899. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  2900. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  2901. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  2902. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  2903. /*
  2904. ** CAPI3REF: SQL Statement Object
  2905. ** KEYWORDS: {prepared statement} {prepared statements}
  2906. **
  2907. ** An instance of this object represents a single SQL statement.
  2908. ** This object is variously known as a "prepared statement" or a
  2909. ** "compiled SQL statement" or simply as a "statement".
  2910. **
  2911. ** The life of a statement object goes something like this:
  2912. **
  2913. ** <ol>
  2914. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  2915. ** function.
  2916. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  2917. ** interfaces.
  2918. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  2919. ** <li> Reset the statement using [sqlite3_reset()] then go back
  2920. ** to step 2. Do this zero or more times.
  2921. ** <li> Destroy the object using [sqlite3_finalize()].
  2922. ** </ol>
  2923. **
  2924. ** Refer to documentation on individual methods above for additional
  2925. ** information.
  2926. */
  2927. typedef struct sqlite3_stmt sqlite3_stmt;
  2928. /*
  2929. ** CAPI3REF: Run-time Limits
  2930. **
  2931. ** ^(This interface allows the size of various constructs to be limited
  2932. ** on a connection by connection basis. The first parameter is the
  2933. ** [database connection] whose limit is to be set or queried. The
  2934. ** second parameter is one of the [limit categories] that define a
  2935. ** class of constructs to be size limited. The third parameter is the
  2936. ** new limit for that construct.)^
  2937. **
  2938. ** ^If the new limit is a negative number, the limit is unchanged.
  2939. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  2940. ** [limits | hard upper bound]
  2941. ** set at compile-time by a C preprocessor macro called
  2942. ** [limits | SQLITE_MAX_<i>NAME</i>].
  2943. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  2944. ** ^Attempts to increase a limit above its hard upper bound are
  2945. ** silently truncated to the hard upper bound.
  2946. **
  2947. ** ^Regardless of whether or not the limit was changed, the
  2948. ** [sqlite3_limit()] interface returns the prior value of the limit.
  2949. ** ^Hence, to find the current value of a limit without changing it,
  2950. ** simply invoke this interface with the third parameter set to -1.
  2951. **
  2952. ** Run-time limits are intended for use in applications that manage
  2953. ** both their own internal database and also databases that are controlled
  2954. ** by untrusted external sources. An example application might be a
  2955. ** web browser that has its own databases for storing history and
  2956. ** separate databases controlled by JavaScript applications downloaded
  2957. ** off the Internet. The internal databases can be given the
  2958. ** large, default limits. Databases managed by external sources can
  2959. ** be given much smaller limits designed to prevent a denial of service
  2960. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  2961. ** interface to further control untrusted SQL. The size of the database
  2962. ** created by an untrusted script can be contained using the
  2963. ** [max_page_count] [PRAGMA].
  2964. **
  2965. ** New run-time limit categories may be added in future releases.
  2966. */
  2967. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  2968. /*
  2969. ** CAPI3REF: Run-Time Limit Categories
  2970. ** KEYWORDS: {limit category} {*limit categories}
  2971. **
  2972. ** These constants define various performance limits
  2973. ** that can be lowered at run-time using [sqlite3_limit()].
  2974. ** The synopsis of the meanings of the various limits is shown below.
  2975. ** Additional information is available at [limits | Limits in SQLite].
  2976. **
  2977. ** <dl>
  2978. ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  2979. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  2980. **
  2981. ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  2982. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  2983. **
  2984. ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  2985. ** <dd>The maximum number of columns in a table definition or in the
  2986. ** result set of a [SELECT] or the maximum number of columns in an index
  2987. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  2988. **
  2989. ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  2990. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  2991. **
  2992. ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  2993. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  2994. **
  2995. ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  2996. ** <dd>The maximum number of instructions in a virtual machine program
  2997. ** used to implement an SQL statement. This limit is not currently
  2998. ** enforced, though that might be added in some future release of
  2999. ** SQLite.</dd>)^
  3000. **
  3001. ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3002. ** <dd>The maximum number of arguments on a function.</dd>)^
  3003. **
  3004. ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3005. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3006. **
  3007. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3008. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3009. ** [GLOB] operators.</dd>)^
  3010. **
  3011. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3012. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3013. **
  3014. ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3015. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3016. ** </dl>
  3017. */
  3018. #define SQLITE_LIMIT_LENGTH 0
  3019. #define SQLITE_LIMIT_SQL_LENGTH 1
  3020. #define SQLITE_LIMIT_COLUMN 2
  3021. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3022. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3023. #define SQLITE_LIMIT_VDBE_OP 5
  3024. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3025. #define SQLITE_LIMIT_ATTACHED 7
  3026. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3027. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3028. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3029. /*
  3030. ** CAPI3REF: Compiling An SQL Statement
  3031. ** KEYWORDS: {SQL statement compiler}
  3032. **
  3033. ** To execute an SQL query, it must first be compiled into a byte-code
  3034. ** program using one of these routines.
  3035. **
  3036. ** The first argument, "db", is a [database connection] obtained from a
  3037. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3038. ** [sqlite3_open16()]. The database connection must not have been closed.
  3039. **
  3040. ** The second argument, "zSql", is the statement to be compiled, encoded
  3041. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3042. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3043. ** use UTF-16.
  3044. **
  3045. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3046. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3047. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3048. ** zSql string ends at either the first '\000' or '\u0000' character or
  3049. ** the nByte-th byte, whichever comes first. If the caller knows
  3050. ** that the supplied string is nul-terminated, then there is a small
  3051. ** performance advantage to be gained by passing an nByte parameter that
  3052. ** is equal to the number of bytes in the input string <i>including</i>
  3053. ** the nul-terminator bytes.
  3054. **
  3055. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3056. ** past the end of the first SQL statement in zSql. These routines only
  3057. ** compile the first statement in zSql, so *pzTail is left pointing to
  3058. ** what remains uncompiled.
  3059. **
  3060. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3061. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3062. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3063. ** string or a comment) then *ppStmt is set to NULL.
  3064. ** The calling procedure is responsible for deleting the compiled
  3065. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3066. ** ppStmt may not be NULL.
  3067. **
  3068. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3069. ** otherwise an [error code] is returned.
  3070. **
  3071. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3072. ** recommended for all new programs. The two older interfaces are retained
  3073. ** for backwards compatibility, but their use is discouraged.
  3074. ** ^In the "v2" interfaces, the prepared statement
  3075. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3076. ** original SQL text. This causes the [sqlite3_step()] interface to
  3077. ** behave differently in three ways:
  3078. **
  3079. ** <ol>
  3080. ** <li>
  3081. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3082. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3083. ** statement and try to run it again.
  3084. ** </li>
  3085. **
  3086. ** <li>
  3087. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3088. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3089. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3090. ** and the application would have to make a second call to [sqlite3_reset()]
  3091. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3092. ** interfaces, the underlying reason for the error is returned immediately.
  3093. ** </li>
  3094. **
  3095. ** <li>
  3096. ** ^If the specific value bound to [parameter | host parameter] in the
  3097. ** WHERE clause might influence the choice of query plan for a statement,
  3098. ** then the statement will be automatically recompiled, as if there had been
  3099. ** a schema change, on the first [sqlite3_step()] call following any change
  3100. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3101. ** ^The specific value of WHERE-clause [parameter] might influence the
  3102. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3103. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3104. ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
  3105. ** the
  3106. ** </li>
  3107. ** </ol>
  3108. */
  3109. SQLITE_API int sqlite3_prepare(
  3110. sqlite3 *db, /* Database handle */
  3111. const char *zSql, /* SQL statement, UTF-8 encoded */
  3112. int nByte, /* Maximum length of zSql in bytes. */
  3113. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3114. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3115. );
  3116. SQLITE_API int sqlite3_prepare_v2(
  3117. sqlite3 *db, /* Database handle */
  3118. const char *zSql, /* SQL statement, UTF-8 encoded */
  3119. int nByte, /* Maximum length of zSql in bytes. */
  3120. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3121. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3122. );
  3123. SQLITE_API int sqlite3_prepare16(
  3124. sqlite3 *db, /* Database handle */
  3125. const void *zSql, /* SQL statement, UTF-16 encoded */
  3126. int nByte, /* Maximum length of zSql in bytes. */
  3127. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3128. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3129. );
  3130. SQLITE_API int sqlite3_prepare16_v2(
  3131. sqlite3 *db, /* Database handle */
  3132. const void *zSql, /* SQL statement, UTF-16 encoded */
  3133. int nByte, /* Maximum length of zSql in bytes. */
  3134. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3135. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3136. );
  3137. /*
  3138. ** CAPI3REF: Retrieving Statement SQL
  3139. **
  3140. ** ^This interface can be used to retrieve a saved copy of the original
  3141. ** SQL text used to create a [prepared statement] if that statement was
  3142. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3143. */
  3144. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3145. /*
  3146. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3147. **
  3148. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3149. ** and only if the [prepared statement] X makes no direct changes to
  3150. ** the content of the database file.
  3151. **
  3152. ** Note that [application-defined SQL functions] or
  3153. ** [virtual tables] might change the database indirectly as a side effect.
  3154. ** ^(For example, if an application defines a function "eval()" that
  3155. ** calls [sqlite3_exec()], then the following SQL statement would
  3156. ** change the database file through side-effects:
  3157. **
  3158. ** <blockquote><pre>
  3159. ** SELECT eval('DELETE FROM t1') FROM t2;
  3160. ** </pre></blockquote>
  3161. **
  3162. ** But because the [SELECT] statement does not change the database file
  3163. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3164. **
  3165. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3166. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3167. ** since the statements themselves do not actually modify the database but
  3168. ** rather they control the timing of when other statements modify the
  3169. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3170. ** sqlite3_stmt_readonly() to return true since, while those statements
  3171. ** change the configuration of a database connection, they do not make
  3172. ** changes to the content of the database files on disk.
  3173. */
  3174. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3175. /*
  3176. ** CAPI3REF: Dynamically Typed Value Object
  3177. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3178. **
  3179. ** SQLite uses the sqlite3_value object to represent all values
  3180. ** that can be stored in a database table. SQLite uses dynamic typing
  3181. ** for the values it stores. ^Values stored in sqlite3_value objects
  3182. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3183. **
  3184. ** An sqlite3_value object may be either "protected" or "unprotected".
  3185. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3186. ** will accept either a protected or an unprotected sqlite3_value.
  3187. ** Every interface that accepts sqlite3_value arguments specifies
  3188. ** whether or not it requires a protected sqlite3_value.
  3189. **
  3190. ** The terms "protected" and "unprotected" refer to whether or not
  3191. ** a mutex is held. An internal mutex is held for a protected
  3192. ** sqlite3_value object but no mutex is held for an unprotected
  3193. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3194. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3195. ** or if SQLite is run in one of reduced mutex modes
  3196. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3197. ** then there is no distinction between protected and unprotected
  3198. ** sqlite3_value objects and they can be used interchangeably. However,
  3199. ** for maximum code portability it is recommended that applications
  3200. ** still make the distinction between protected and unprotected
  3201. ** sqlite3_value objects even when not strictly required.
  3202. **
  3203. ** ^The sqlite3_value objects that are passed as parameters into the
  3204. ** implementation of [application-defined SQL functions] are protected.
  3205. ** ^The sqlite3_value object returned by
  3206. ** [sqlite3_column_value()] is unprotected.
  3207. ** Unprotected sqlite3_value objects may only be used with
  3208. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3209. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3210. ** interfaces require protected sqlite3_value objects.
  3211. */
  3212. typedef struct Mem sqlite3_value;
  3213. /*
  3214. ** CAPI3REF: SQL Function Context Object
  3215. **
  3216. ** The context in which an SQL function executes is stored in an
  3217. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3218. ** is always first parameter to [application-defined SQL functions].
  3219. ** The application-defined SQL function implementation will pass this
  3220. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3221. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3222. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3223. ** and/or [sqlite3_set_auxdata()].
  3224. */
  3225. typedef struct sqlite3_context sqlite3_context;
  3226. /*
  3227. ** CAPI3REF: Binding Values To Prepared Statements
  3228. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3229. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3230. **
  3231. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3232. ** literals may be replaced by a [parameter] that matches one of following
  3233. ** templates:
  3234. **
  3235. ** <ul>
  3236. ** <li> ?
  3237. ** <li> ?NNN
  3238. ** <li> :VVV
  3239. ** <li> @VVV
  3240. ** <li> $VVV
  3241. ** </ul>
  3242. **
  3243. ** In the templates above, NNN represents an integer literal,
  3244. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3245. ** parameters (also called "host parameter names" or "SQL parameters")
  3246. ** can be set using the sqlite3_bind_*() routines defined here.
  3247. **
  3248. ** ^The first argument to the sqlite3_bind_*() routines is always
  3249. ** a pointer to the [sqlite3_stmt] object returned from
  3250. ** [sqlite3_prepare_v2()] or its variants.
  3251. **
  3252. ** ^The second argument is the index of the SQL parameter to be set.
  3253. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3254. ** SQL parameter is used more than once, second and subsequent
  3255. ** occurrences have the same index as the first occurrence.
  3256. ** ^The index for named parameters can be looked up using the
  3257. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3258. ** for "?NNN" parameters is the value of NNN.
  3259. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3260. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3261. **
  3262. ** ^The third argument is the value to bind to the parameter.
  3263. **
  3264. ** ^(In those routines that have a fourth argument, its value is the
  3265. ** number of bytes in the parameter. To be clear: the value is the
  3266. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3267. ** ^If the fourth parameter is negative, the length of the string is
  3268. ** the number of bytes up to the first zero terminator.
  3269. **
  3270. ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3271. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3272. ** string after SQLite has finished with it. ^The destructor is called
  3273. ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  3274. ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
  3275. ** ^If the fifth argument is
  3276. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3277. ** information is in static, unmanaged space and does not need to be freed.
  3278. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3279. ** SQLite makes its own private copy of the data immediately, before
  3280. ** the sqlite3_bind_*() routine returns.
  3281. **
  3282. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3283. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3284. ** (just an integer to hold its size) while it is being processed.
  3285. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3286. ** content is later written using
  3287. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3288. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3289. **
  3290. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3291. ** for the [prepared statement] or with a prepared statement for which
  3292. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3293. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3294. ** routine is passed a [prepared statement] that has been finalized, the
  3295. ** result is undefined and probably harmful.
  3296. **
  3297. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3298. ** ^Unbound parameters are interpreted as NULL.
  3299. **
  3300. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3301. ** [error code] if anything goes wrong.
  3302. ** ^[SQLITE_RANGE] is returned if the parameter
  3303. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3304. **
  3305. ** See also: [sqlite3_bind_parameter_count()],
  3306. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3307. */
  3308. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3309. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3310. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3311. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3312. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3313. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3314. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3315. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3316. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3317. /*
  3318. ** CAPI3REF: Number Of SQL Parameters
  3319. **
  3320. ** ^This routine can be used to find the number of [SQL parameters]
  3321. ** in a [prepared statement]. SQL parameters are tokens of the
  3322. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3323. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3324. ** to the parameters at a later time.
  3325. **
  3326. ** ^(This routine actually returns the index of the largest (rightmost)
  3327. ** parameter. For all forms except ?NNN, this will correspond to the
  3328. ** number of unique parameters. If parameters of the ?NNN form are used,
  3329. ** there may be gaps in the list.)^
  3330. **
  3331. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3332. ** [sqlite3_bind_parameter_name()], and
  3333. ** [sqlite3_bind_parameter_index()].
  3334. */
  3335. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3336. /*
  3337. ** CAPI3REF: Name Of A Host Parameter
  3338. **
  3339. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3340. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3341. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3342. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3343. ** respectively.
  3344. ** In other words, the initial ":" or "$" or "@" or "?"
  3345. ** is included as part of the name.)^
  3346. ** ^Parameters of the form "?" without a following integer have no name
  3347. ** and are referred to as "nameless" or "anonymous parameters".
  3348. **
  3349. ** ^The first host parameter has an index of 1, not 0.
  3350. **
  3351. ** ^If the value N is out of range or if the N-th parameter is
  3352. ** nameless, then NULL is returned. ^The returned string is
  3353. ** always in UTF-8 encoding even if the named parameter was
  3354. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3355. ** [sqlite3_prepare16_v2()].
  3356. **
  3357. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3358. ** [sqlite3_bind_parameter_count()], and
  3359. ** [sqlite3_bind_parameter_index()].
  3360. */
  3361. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3362. /*
  3363. ** CAPI3REF: Index Of A Parameter With A Given Name
  3364. **
  3365. ** ^Return the index of an SQL parameter given its name. ^The
  3366. ** index value returned is suitable for use as the second
  3367. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3368. ** is returned if no matching parameter is found. ^The parameter
  3369. ** name must be given in UTF-8 even if the original statement
  3370. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3371. **
  3372. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3373. ** [sqlite3_bind_parameter_count()], and
  3374. ** [sqlite3_bind_parameter_index()].
  3375. */
  3376. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3377. /*
  3378. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3379. **
  3380. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3381. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3382. ** ^Use this routine to reset all host parameters to NULL.
  3383. */
  3384. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3385. /*
  3386. ** CAPI3REF: Number Of Columns In A Result Set
  3387. **
  3388. ** ^Return the number of columns in the result set returned by the
  3389. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3390. ** statement that does not return data (for example an [UPDATE]).
  3391. **
  3392. ** See also: [sqlite3_data_count()]
  3393. */
  3394. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3395. /*
  3396. ** CAPI3REF: Column Names In A Result Set
  3397. **
  3398. ** ^These routines return the name assigned to a particular column
  3399. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3400. ** interface returns a pointer to a zero-terminated UTF-8 string
  3401. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3402. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3403. ** that implements the [SELECT] statement. ^The second parameter is the
  3404. ** column number. ^The leftmost column is number 0.
  3405. **
  3406. ** ^The returned string pointer is valid until either the [prepared statement]
  3407. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3408. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3409. ** or until the next call to
  3410. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3411. **
  3412. ** ^If sqlite3_malloc() fails during the processing of either routine
  3413. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3414. ** NULL pointer is returned.
  3415. **
  3416. ** ^The name of a result column is the value of the "AS" clause for
  3417. ** that column, if there is an AS clause. If there is no AS clause
  3418. ** then the name of the column is unspecified and may change from
  3419. ** one release of SQLite to the next.
  3420. */
  3421. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3422. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3423. /*
  3424. ** CAPI3REF: Source Of Data In A Query Result
  3425. **
  3426. ** ^These routines provide a means to determine the database, table, and
  3427. ** table column that is the origin of a particular result column in
  3428. ** [SELECT] statement.
  3429. ** ^The name of the database or table or column can be returned as
  3430. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3431. ** the database name, the _table_ routines return the table name, and
  3432. ** the origin_ routines return the column name.
  3433. ** ^The returned string is valid until the [prepared statement] is destroyed
  3434. ** using [sqlite3_finalize()] or until the statement is automatically
  3435. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3436. ** or until the same information is requested
  3437. ** again in a different encoding.
  3438. **
  3439. ** ^The names returned are the original un-aliased names of the
  3440. ** database, table, and column.
  3441. **
  3442. ** ^The first argument to these interfaces is a [prepared statement].
  3443. ** ^These functions return information about the Nth result column returned by
  3444. ** the statement, where N is the second function argument.
  3445. ** ^The left-most column is column 0 for these routines.
  3446. **
  3447. ** ^If the Nth column returned by the statement is an expression or
  3448. ** subquery and is not a column value, then all of these functions return
  3449. ** NULL. ^These routine might also return NULL if a memory allocation error
  3450. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3451. ** or column that query result column was extracted from.
  3452. **
  3453. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3454. ** UTF-16 encoded strings and the other functions return UTF-8.
  3455. **
  3456. ** ^These APIs are only available if the library was compiled with the
  3457. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3458. **
  3459. ** If two or more threads call one or more of these routines against the same
  3460. ** prepared statement and column at the same time then the results are
  3461. ** undefined.
  3462. **
  3463. ** If two or more threads call one or more
  3464. ** [sqlite3_column_database_name | column metadata interfaces]
  3465. ** for the same [prepared statement] and result column
  3466. ** at the same time then the results are undefined.
  3467. */
  3468. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3469. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3470. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3471. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3472. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3473. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3474. /*
  3475. ** CAPI3REF: Declared Datatype Of A Query Result
  3476. **
  3477. ** ^(The first parameter is a [prepared statement].
  3478. ** If this statement is a [SELECT] statement and the Nth column of the
  3479. ** returned result set of that [SELECT] is a table column (not an
  3480. ** expression or subquery) then the declared type of the table
  3481. ** column is returned.)^ ^If the Nth column of the result set is an
  3482. ** expression or subquery, then a NULL pointer is returned.
  3483. ** ^The returned string is always UTF-8 encoded.
  3484. **
  3485. ** ^(For example, given the database schema:
  3486. **
  3487. ** CREATE TABLE t1(c1 VARIANT);
  3488. **
  3489. ** and the following statement to be compiled:
  3490. **
  3491. ** SELECT c1 + 1, c1 FROM t1;
  3492. **
  3493. ** this routine would return the string "VARIANT" for the second result
  3494. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3495. **
  3496. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3497. ** is declared to contain a particular type does not mean that the
  3498. ** data stored in that column is of the declared type. SQLite is
  3499. ** strongly typed, but the typing is dynamic not static. ^Type
  3500. ** is associated with individual values, not with the containers
  3501. ** used to hold those values.
  3502. */
  3503. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3504. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3505. /*
  3506. ** CAPI3REF: Evaluate An SQL Statement
  3507. **
  3508. ** After a [prepared statement] has been prepared using either
  3509. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3510. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3511. ** must be called one or more times to evaluate the statement.
  3512. **
  3513. ** The details of the behavior of the sqlite3_step() interface depend
  3514. ** on whether the statement was prepared using the newer "v2" interface
  3515. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3516. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3517. ** new "v2" interface is recommended for new applications but the legacy
  3518. ** interface will continue to be supported.
  3519. **
  3520. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3521. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3522. ** ^With the "v2" interface, any of the other [result codes] or
  3523. ** [extended result codes] might be returned as well.
  3524. **
  3525. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3526. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3527. ** or occurs outside of an explicit transaction, then you can retry the
  3528. ** statement. If the statement is not a [COMMIT] and occurs within a
  3529. ** explicit transaction then you should rollback the transaction before
  3530. ** continuing.
  3531. **
  3532. ** ^[SQLITE_DONE] means that the statement has finished executing
  3533. ** successfully. sqlite3_step() should not be called again on this virtual
  3534. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3535. ** machine back to its initial state.
  3536. **
  3537. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3538. ** is returned each time a new row of data is ready for processing by the
  3539. ** caller. The values may be accessed using the [column access functions].
  3540. ** sqlite3_step() is called again to retrieve the next row of data.
  3541. **
  3542. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3543. ** violation) has occurred. sqlite3_step() should not be called again on
  3544. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3545. ** ^With the legacy interface, a more specific error code (for example,
  3546. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3547. ** can be obtained by calling [sqlite3_reset()] on the
  3548. ** [prepared statement]. ^In the "v2" interface,
  3549. ** the more specific error code is returned directly by sqlite3_step().
  3550. **
  3551. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3552. ** Perhaps it was called on a [prepared statement] that has
  3553. ** already been [sqlite3_finalize | finalized] or on one that had
  3554. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3555. ** be the case that the same database connection is being used by two or
  3556. ** more threads at the same moment in time.
  3557. **
  3558. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3559. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3560. ** other than [SQLITE_ROW] before any subsequent invocation of
  3561. ** sqlite3_step(). Failure to reset the prepared statement using
  3562. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3563. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3564. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3565. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3566. ** break because any application that ever receives an SQLITE_MISUSE error
  3567. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3568. ** can be used to restore the legacy behavior.
  3569. **
  3570. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3571. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3572. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3573. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3574. ** specific [error codes] that better describes the error.
  3575. ** We admit that this is a goofy design. The problem has been fixed
  3576. ** with the "v2" interface. If you prepare all of your SQL statements
  3577. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3578. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3579. ** then the more specific [error codes] are returned directly
  3580. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3581. */
  3582. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3583. /*
  3584. ** CAPI3REF: Number of columns in a result set
  3585. **
  3586. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3587. ** current row of the result set of [prepared statement] P.
  3588. ** ^If prepared statement P does not have results ready to return
  3589. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3590. ** interfaces) then sqlite3_data_count(P) returns 0.
  3591. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3592. **
  3593. ** See also: [sqlite3_column_count()]
  3594. */
  3595. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3596. /*
  3597. ** CAPI3REF: Fundamental Datatypes
  3598. ** KEYWORDS: SQLITE_TEXT
  3599. **
  3600. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3601. **
  3602. ** <ul>
  3603. ** <li> 64-bit signed integer
  3604. ** <li> 64-bit IEEE floating point number
  3605. ** <li> string
  3606. ** <li> BLOB
  3607. ** <li> NULL
  3608. ** </ul>)^
  3609. **
  3610. ** These constants are codes for each of those types.
  3611. **
  3612. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3613. ** for a completely different meaning. Software that links against both
  3614. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3615. ** SQLITE_TEXT.
  3616. */
  3617. #define SQLITE_INTEGER 1
  3618. #define SQLITE_FLOAT 2
  3619. #define SQLITE_BLOB 4
  3620. #define SQLITE_NULL 5
  3621. #ifdef SQLITE_TEXT
  3622. # undef SQLITE_TEXT
  3623. #else
  3624. # define SQLITE_TEXT 3
  3625. #endif
  3626. #define SQLITE3_TEXT 3
  3627. /*
  3628. ** CAPI3REF: Result Values From A Query
  3629. ** KEYWORDS: {column access functions}
  3630. **
  3631. ** These routines form the "result set" interface.
  3632. **
  3633. ** ^These routines return information about a single column of the current
  3634. ** result row of a query. ^In every case the first argument is a pointer
  3635. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3636. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3637. ** and the second argument is the index of the column for which information
  3638. ** should be returned. ^The leftmost column of the result set has the index 0.
  3639. ** ^The number of columns in the result can be determined using
  3640. ** [sqlite3_column_count()].
  3641. **
  3642. ** If the SQL statement does not currently point to a valid row, or if the
  3643. ** column index is out of range, the result is undefined.
  3644. ** These routines may only be called when the most recent call to
  3645. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3646. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3647. ** If any of these routines are called after [sqlite3_reset()] or
  3648. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3649. ** something other than [SQLITE_ROW], the results are undefined.
  3650. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3651. ** are called from a different thread while any of these routines
  3652. ** are pending, then the results are undefined.
  3653. **
  3654. ** ^The sqlite3_column_type() routine returns the
  3655. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3656. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  3657. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3658. ** returned by sqlite3_column_type() is only meaningful if no type
  3659. ** conversions have occurred as described below. After a type conversion,
  3660. ** the value returned by sqlite3_column_type() is undefined. Future
  3661. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3662. ** following a type conversion.
  3663. **
  3664. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3665. ** routine returns the number of bytes in that BLOB or string.
  3666. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3667. ** the string to UTF-8 and then returns the number of bytes.
  3668. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  3669. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3670. ** the number of bytes in that string.
  3671. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  3672. **
  3673. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  3674. ** routine returns the number of bytes in that BLOB or string.
  3675. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  3676. ** the string to UTF-16 and then returns the number of bytes.
  3677. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  3678. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  3679. ** the number of bytes in that string.
  3680. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  3681. **
  3682. ** ^The values returned by [sqlite3_column_bytes()] and
  3683. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3684. ** of the string. ^For clarity: the values returned by
  3685. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3686. ** bytes in the string, not the number of characters.
  3687. **
  3688. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3689. ** even empty strings, are always zero terminated. ^The return
  3690. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3691. **
  3692. ** ^The object returned by [sqlite3_column_value()] is an
  3693. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3694. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3695. ** If the [unprotected sqlite3_value] object returned by
  3696. ** [sqlite3_column_value()] is used in any other way, including calls
  3697. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3698. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3699. **
  3700. ** These routines attempt to convert the value where appropriate. ^For
  3701. ** example, if the internal representation is FLOAT and a text result
  3702. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3703. ** conversion automatically. ^(The following table details the conversions
  3704. ** that are applied:
  3705. **
  3706. ** <blockquote>
  3707. ** <table border="1">
  3708. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3709. **
  3710. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3711. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3712. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  3713. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  3714. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3715. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3716. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3717. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  3718. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3719. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  3720. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  3721. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  3722. ** <tr><td> TEXT <td> BLOB <td> No change
  3723. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  3724. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  3725. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  3726. ** </table>
  3727. ** </blockquote>)^
  3728. **
  3729. ** The table above makes reference to standard C library functions atoi()
  3730. ** and atof(). SQLite does not really use these functions. It has its
  3731. ** own equivalent internal routines. The atoi() and atof() names are
  3732. ** used in the table for brevity and because they are familiar to most
  3733. ** C programmers.
  3734. **
  3735. ** Note that when type conversions occur, pointers returned by prior
  3736. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  3737. ** sqlite3_column_text16() may be invalidated.
  3738. ** Type conversions and pointer invalidations might occur
  3739. ** in the following cases:
  3740. **
  3741. ** <ul>
  3742. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  3743. ** sqlite3_column_text16() is called. A zero-terminator might
  3744. ** need to be added to the string.</li>
  3745. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  3746. ** sqlite3_column_text16() is called. The content must be converted
  3747. ** to UTF-16.</li>
  3748. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  3749. ** sqlite3_column_text() is called. The content must be converted
  3750. ** to UTF-8.</li>
  3751. ** </ul>
  3752. **
  3753. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  3754. ** not invalidate a prior pointer, though of course the content of the buffer
  3755. ** that the prior pointer references will have been modified. Other kinds
  3756. ** of conversion are done in place when it is possible, but sometimes they
  3757. ** are not possible and in those cases prior pointers are invalidated.
  3758. **
  3759. ** The safest and easiest to remember policy is to invoke these routines
  3760. ** in one of the following ways:
  3761. **
  3762. ** <ul>
  3763. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  3764. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  3765. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  3766. ** </ul>
  3767. **
  3768. ** In other words, you should call sqlite3_column_text(),
  3769. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  3770. ** into the desired format, then invoke sqlite3_column_bytes() or
  3771. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  3772. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  3773. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  3774. ** with calls to sqlite3_column_bytes().
  3775. **
  3776. ** ^The pointers returned are valid until a type conversion occurs as
  3777. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  3778. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  3779. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  3780. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  3781. ** [sqlite3_free()].
  3782. **
  3783. ** ^(If a memory allocation error occurs during the evaluation of any
  3784. ** of these routines, a default value is returned. The default value
  3785. ** is either the integer 0, the floating point number 0.0, or a NULL
  3786. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  3787. ** [SQLITE_NOMEM].)^
  3788. */
  3789. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  3790. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  3791. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  3792. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  3793. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  3794. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  3795. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  3796. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  3797. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  3798. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  3799. /*
  3800. ** CAPI3REF: Destroy A Prepared Statement Object
  3801. **
  3802. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  3803. ** ^If the most recent evaluation of the statement encountered no errors or
  3804. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  3805. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  3806. ** sqlite3_finalize(S) returns the appropriate [error code] or
  3807. ** [extended error code].
  3808. **
  3809. ** ^The sqlite3_finalize(S) routine can be called at any point during
  3810. ** the life cycle of [prepared statement] S:
  3811. ** before statement S is ever evaluated, after
  3812. ** one or more calls to [sqlite3_reset()], or after any call
  3813. ** to [sqlite3_step()] regardless of whether or not the statement has
  3814. ** completed execution.
  3815. **
  3816. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  3817. **
  3818. ** The application must finalize every [prepared statement] in order to avoid
  3819. ** resource leaks. It is a grievous error for the application to try to use
  3820. ** a prepared statement after it has been finalized. Any use of a prepared
  3821. ** statement after it has been finalized can result in undefined and
  3822. ** undesirable behavior such as segfaults and heap corruption.
  3823. */
  3824. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  3825. /*
  3826. ** CAPI3REF: Reset A Prepared Statement Object
  3827. **
  3828. ** The sqlite3_reset() function is called to reset a [prepared statement]
  3829. ** object back to its initial state, ready to be re-executed.
  3830. ** ^Any SQL statement variables that had values bound to them using
  3831. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  3832. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  3833. **
  3834. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  3835. ** back to the beginning of its program.
  3836. **
  3837. ** ^If the most recent call to [sqlite3_step(S)] for the
  3838. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  3839. ** or if [sqlite3_step(S)] has never before been called on S,
  3840. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  3841. **
  3842. ** ^If the most recent call to [sqlite3_step(S)] for the
  3843. ** [prepared statement] S indicated an error, then
  3844. ** [sqlite3_reset(S)] returns an appropriate [error code].
  3845. **
  3846. ** ^The [sqlite3_reset(S)] interface does not change the values
  3847. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  3848. */
  3849. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  3850. /*
  3851. ** CAPI3REF: Create Or Redefine SQL Functions
  3852. ** KEYWORDS: {function creation routines}
  3853. ** KEYWORDS: {application-defined SQL function}
  3854. ** KEYWORDS: {application-defined SQL functions}
  3855. **
  3856. ** ^These functions (collectively known as "function creation routines")
  3857. ** are used to add SQL functions or aggregates or to redefine the behavior
  3858. ** of existing SQL functions or aggregates. The only differences between
  3859. ** these routines are the text encoding expected for
  3860. ** the second parameter (the name of the function being created)
  3861. ** and the presence or absence of a destructor callback for
  3862. ** the application data pointer.
  3863. **
  3864. ** ^The first parameter is the [database connection] to which the SQL
  3865. ** function is to be added. ^If an application uses more than one database
  3866. ** connection then application-defined SQL functions must be added
  3867. ** to each database connection separately.
  3868. **
  3869. ** ^The second parameter is the name of the SQL function to be created or
  3870. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  3871. ** representation, exclusive of the zero-terminator. ^Note that the name
  3872. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  3873. ** ^Any attempt to create a function with a longer name
  3874. ** will result in [SQLITE_MISUSE] being returned.
  3875. **
  3876. ** ^The third parameter (nArg)
  3877. ** is the number of arguments that the SQL function or
  3878. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  3879. ** aggregate may take any number of arguments between 0 and the limit
  3880. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  3881. ** parameter is less than -1 or greater than 127 then the behavior is
  3882. ** undefined.
  3883. **
  3884. ** ^The fourth parameter, eTextRep, specifies what
  3885. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  3886. ** its parameters. Every SQL function implementation must be able to work
  3887. ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  3888. ** more efficient with one encoding than another. ^An application may
  3889. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  3890. ** times with the same function but with different values of eTextRep.
  3891. ** ^When multiple implementations of the same function are available, SQLite
  3892. ** will pick the one that involves the least amount of data conversion.
  3893. ** If there is only a single implementation which does not care what text
  3894. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  3895. **
  3896. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  3897. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  3898. **
  3899. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  3900. ** pointers to C-language functions that implement the SQL function or
  3901. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  3902. ** callback only; NULL pointers must be passed as the xStep and xFinal
  3903. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  3904. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  3905. ** SQL function or aggregate, pass NULL pointers for all three function
  3906. ** callbacks.
  3907. **
  3908. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  3909. ** then it is destructor for the application data pointer.
  3910. ** The destructor is invoked when the function is deleted, either by being
  3911. ** overloaded or when the database connection closes.)^
  3912. ** ^The destructor is also invoked if the call to
  3913. ** sqlite3_create_function_v2() fails.
  3914. ** ^When the destructor callback of the tenth parameter is invoked, it
  3915. ** is passed a single argument which is a copy of the application data
  3916. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  3917. **
  3918. ** ^It is permitted to register multiple implementations of the same
  3919. ** functions with the same name but with either differing numbers of
  3920. ** arguments or differing preferred text encodings. ^SQLite will use
  3921. ** the implementation that most closely matches the way in which the
  3922. ** SQL function is used. ^A function implementation with a non-negative
  3923. ** nArg parameter is a better match than a function implementation with
  3924. ** a negative nArg. ^A function where the preferred text encoding
  3925. ** matches the database encoding is a better
  3926. ** match than a function where the encoding is different.
  3927. ** ^A function where the encoding difference is between UTF16le and UTF16be
  3928. ** is a closer match than a function where the encoding difference is
  3929. ** between UTF8 and UTF16.
  3930. **
  3931. ** ^Built-in functions may be overloaded by new application-defined functions.
  3932. **
  3933. ** ^An application-defined function is permitted to call other
  3934. ** SQLite interfaces. However, such calls must not
  3935. ** close the database connection nor finalize or reset the prepared
  3936. ** statement in which the function is running.
  3937. */
  3938. SQLITE_API int sqlite3_create_function(
  3939. sqlite3 *db,
  3940. const char *zFunctionName,
  3941. int nArg,
  3942. int eTextRep,
  3943. void *pApp,
  3944. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3945. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3946. void (*xFinal)(sqlite3_context*)
  3947. );
  3948. SQLITE_API int sqlite3_create_function16(
  3949. sqlite3 *db,
  3950. const void *zFunctionName,
  3951. int nArg,
  3952. int eTextRep,
  3953. void *pApp,
  3954. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3955. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3956. void (*xFinal)(sqlite3_context*)
  3957. );
  3958. SQLITE_API int sqlite3_create_function_v2(
  3959. sqlite3 *db,
  3960. const char *zFunctionName,
  3961. int nArg,
  3962. int eTextRep,
  3963. void *pApp,
  3964. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3965. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3966. void (*xFinal)(sqlite3_context*),
  3967. void(*xDestroy)(void*)
  3968. );
  3969. /*
  3970. ** CAPI3REF: Text Encodings
  3971. **
  3972. ** These constant define integer codes that represent the various
  3973. ** text encodings supported by SQLite.
  3974. */
  3975. #define SQLITE_UTF8 1
  3976. #define SQLITE_UTF16LE 2
  3977. #define SQLITE_UTF16BE 3
  3978. #define SQLITE_UTF16 4 /* Use native byte order */
  3979. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  3980. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  3981. /*
  3982. ** CAPI3REF: Deprecated Functions
  3983. ** DEPRECATED
  3984. **
  3985. ** These functions are [deprecated]. In order to maintain
  3986. ** backwards compatibility with older code, these functions continue
  3987. ** to be supported. However, new applications should avoid
  3988. ** the use of these functions. To help encourage people to avoid
  3989. ** using these functions, we are not going to tell you what they do.
  3990. */
  3991. #ifndef SQLITE_OMIT_DEPRECATED
  3992. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  3993. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  3994. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  3995. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  3996. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  3997. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
  3998. #endif
  3999. /*
  4000. ** CAPI3REF: Obtaining SQL Function Parameter Values
  4001. **
  4002. ** The C-language implementation of SQL functions and aggregates uses
  4003. ** this set of interface routines to access the parameter values on
  4004. ** the function or aggregate.
  4005. **
  4006. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4007. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4008. ** define callbacks that implement the SQL functions and aggregates.
  4009. ** The 3rd parameter to these callbacks is an array of pointers to
  4010. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4011. ** each parameter to the SQL function. These routines are used to
  4012. ** extract values from the [sqlite3_value] objects.
  4013. **
  4014. ** These routines work only with [protected sqlite3_value] objects.
  4015. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4016. ** object results in undefined behavior.
  4017. **
  4018. ** ^These routines work just like the corresponding [column access functions]
  4019. ** except that these routines take a single [protected sqlite3_value] object
  4020. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4021. **
  4022. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4023. ** in the native byte-order of the host machine. ^The
  4024. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4025. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4026. **
  4027. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4028. ** numeric affinity to the value. This means that an attempt is
  4029. ** made to convert the value to an integer or floating point. If
  4030. ** such a conversion is possible without loss of information (in other
  4031. ** words, if the value is a string that looks like a number)
  4032. ** then the conversion is performed. Otherwise no conversion occurs.
  4033. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4034. **
  4035. ** Please pay particular attention to the fact that the pointer returned
  4036. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4037. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4038. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4039. ** or [sqlite3_value_text16()].
  4040. **
  4041. ** These routines must be called from the same thread as
  4042. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4043. */
  4044. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4045. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4046. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4047. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4048. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4049. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4050. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4051. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4052. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4053. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4054. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4055. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4056. /*
  4057. ** CAPI3REF: Obtain Aggregate Function Context
  4058. **
  4059. ** Implementations of aggregate SQL functions use this
  4060. ** routine to allocate memory for storing their state.
  4061. **
  4062. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4063. ** for a particular aggregate function, SQLite
  4064. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4065. ** to the new memory. ^On second and subsequent calls to
  4066. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4067. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4068. ** called once for each invocation of the xStep callback and then one
  4069. ** last time when the xFinal callback is invoked. ^(When no rows match
  4070. ** an aggregate query, the xStep() callback of the aggregate function
  4071. ** implementation is never called and xFinal() is called exactly once.
  4072. ** In those cases, sqlite3_aggregate_context() might be called for the
  4073. ** first time from within xFinal().)^
  4074. **
  4075. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
  4076. ** less than or equal to zero or if a memory allocate error occurs.
  4077. **
  4078. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4079. ** determined by the N parameter on first successful call. Changing the
  4080. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4081. ** the same aggregate function instance will not resize the memory
  4082. ** allocation.)^
  4083. **
  4084. ** ^SQLite automatically frees the memory allocated by
  4085. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4086. **
  4087. ** The first parameter must be a copy of the
  4088. ** [sqlite3_context | SQL function context] that is the first parameter
  4089. ** to the xStep or xFinal callback routine that implements the aggregate
  4090. ** function.
  4091. **
  4092. ** This routine must be called from the same thread in which
  4093. ** the aggregate SQL function is running.
  4094. */
  4095. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4096. /*
  4097. ** CAPI3REF: User Data For Functions
  4098. **
  4099. ** ^The sqlite3_user_data() interface returns a copy of
  4100. ** the pointer that was the pUserData parameter (the 5th parameter)
  4101. ** of the [sqlite3_create_function()]
  4102. ** and [sqlite3_create_function16()] routines that originally
  4103. ** registered the application defined function.
  4104. **
  4105. ** This routine must be called from the same thread in which
  4106. ** the application-defined function is running.
  4107. */
  4108. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4109. /*
  4110. ** CAPI3REF: Database Connection For Functions
  4111. **
  4112. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4113. ** the pointer to the [database connection] (the 1st parameter)
  4114. ** of the [sqlite3_create_function()]
  4115. ** and [sqlite3_create_function16()] routines that originally
  4116. ** registered the application defined function.
  4117. */
  4118. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4119. /*
  4120. ** CAPI3REF: Function Auxiliary Data
  4121. **
  4122. ** The following two functions may be used by scalar SQL functions to
  4123. ** associate metadata with argument values. If the same value is passed to
  4124. ** multiple invocations of the same SQL function during query execution, under
  4125. ** some circumstances the associated metadata may be preserved. This may
  4126. ** be used, for example, to add a regular-expression matching scalar
  4127. ** function. The compiled version of the regular expression is stored as
  4128. ** metadata associated with the SQL value passed as the regular expression
  4129. ** pattern. The compiled regular expression can be reused on multiple
  4130. ** invocations of the same function so that the original pattern string
  4131. ** does not need to be recompiled on each invocation.
  4132. **
  4133. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4134. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4135. ** value to the application-defined function. ^If no metadata has been ever
  4136. ** been set for the Nth argument of the function, or if the corresponding
  4137. ** function parameter has changed since the meta-data was set,
  4138. ** then sqlite3_get_auxdata() returns a NULL pointer.
  4139. **
  4140. ** ^The sqlite3_set_auxdata() interface saves the metadata
  4141. ** pointed to by its 3rd parameter as the metadata for the N-th
  4142. ** argument of the application-defined function. Subsequent
  4143. ** calls to sqlite3_get_auxdata() might return this data, if it has
  4144. ** not been destroyed.
  4145. ** ^If it is not NULL, SQLite will invoke the destructor
  4146. ** function given by the 4th parameter to sqlite3_set_auxdata() on
  4147. ** the metadata when the corresponding function parameter changes
  4148. ** or when the SQL statement completes, whichever comes first.
  4149. **
  4150. ** SQLite is free to call the destructor and drop metadata on any
  4151. ** parameter of any function at any time. ^The only guarantee is that
  4152. ** the destructor will be called before the metadata is dropped.
  4153. **
  4154. ** ^(In practice, metadata is preserved between function calls for
  4155. ** expressions that are constant at compile time. This includes literal
  4156. ** values and [parameters].)^
  4157. **
  4158. ** These routines must be called from the same thread in which
  4159. ** the SQL function is running.
  4160. */
  4161. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4162. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4163. /*
  4164. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4165. **
  4166. ** These are special values for the destructor that is passed in as the
  4167. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4168. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4169. ** and will never change. It does not need to be destroyed. ^The
  4170. ** SQLITE_TRANSIENT value means that the content will likely change in
  4171. ** the near future and that SQLite should make its own private copy of
  4172. ** the content before returning.
  4173. **
  4174. ** The typedef is necessary to work around problems in certain
  4175. ** C++ compilers. See ticket #2191.
  4176. */
  4177. typedef void (*sqlite3_destructor_type)(void*);
  4178. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4179. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4180. /*
  4181. ** CAPI3REF: Setting The Result Of An SQL Function
  4182. **
  4183. ** These routines are used by the xFunc or xFinal callbacks that
  4184. ** implement SQL functions and aggregates. See
  4185. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4186. ** for additional information.
  4187. **
  4188. ** These functions work very much like the [parameter binding] family of
  4189. ** functions used to bind values to host parameters in prepared statements.
  4190. ** Refer to the [SQL parameter] documentation for additional information.
  4191. **
  4192. ** ^The sqlite3_result_blob() interface sets the result from
  4193. ** an application-defined function to be the BLOB whose content is pointed
  4194. ** to by the second parameter and which is N bytes long where N is the
  4195. ** third parameter.
  4196. **
  4197. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4198. ** the application-defined function to be a BLOB containing all zero
  4199. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4200. **
  4201. ** ^The sqlite3_result_double() interface sets the result from
  4202. ** an application-defined function to be a floating point value specified
  4203. ** by its 2nd argument.
  4204. **
  4205. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4206. ** cause the implemented SQL function to throw an exception.
  4207. ** ^SQLite uses the string pointed to by the
  4208. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4209. ** as the text of an error message. ^SQLite interprets the error
  4210. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4211. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4212. ** byte order. ^If the third parameter to sqlite3_result_error()
  4213. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4214. ** message all text up through the first zero character.
  4215. ** ^If the third parameter to sqlite3_result_error() or
  4216. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4217. ** bytes (not characters) from the 2nd parameter as the error message.
  4218. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4219. ** routines make a private copy of the error message text before
  4220. ** they return. Hence, the calling function can deallocate or
  4221. ** modify the text after they return without harm.
  4222. ** ^The sqlite3_result_error_code() function changes the error code
  4223. ** returned by SQLite as a result of an error in a function. ^By default,
  4224. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4225. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4226. **
  4227. ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
  4228. ** indicating that a string or BLOB is too long to represent.
  4229. **
  4230. ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
  4231. ** indicating that a memory allocation failed.
  4232. **
  4233. ** ^The sqlite3_result_int() interface sets the return value
  4234. ** of the application-defined function to be the 32-bit signed integer
  4235. ** value given in the 2nd argument.
  4236. ** ^The sqlite3_result_int64() interface sets the return value
  4237. ** of the application-defined function to be the 64-bit signed integer
  4238. ** value given in the 2nd argument.
  4239. **
  4240. ** ^The sqlite3_result_null() interface sets the return value
  4241. ** of the application-defined function to be NULL.
  4242. **
  4243. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4244. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4245. ** set the return value of the application-defined function to be
  4246. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4247. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4248. ** ^SQLite takes the text result from the application from
  4249. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4250. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4251. ** is negative, then SQLite takes result text from the 2nd parameter
  4252. ** through the first zero character.
  4253. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4254. ** is non-negative, then as many bytes (not characters) of the text
  4255. ** pointed to by the 2nd parameter are taken as the application-defined
  4256. ** function result.
  4257. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4258. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4259. ** function as the destructor on the text or BLOB result when it has
  4260. ** finished using that result.
  4261. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4262. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4263. ** assumes that the text or BLOB result is in constant space and does not
  4264. ** copy the content of the parameter nor call a destructor on the content
  4265. ** when it has finished using that result.
  4266. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4267. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4268. ** then SQLite makes a copy of the result into space obtained from
  4269. ** from [sqlite3_malloc()] before it returns.
  4270. **
  4271. ** ^The sqlite3_result_value() interface sets the result of
  4272. ** the application-defined function to be a copy the
  4273. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4274. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4275. ** so that the [sqlite3_value] specified in the parameter may change or
  4276. ** be deallocated after sqlite3_result_value() returns without harm.
  4277. ** ^A [protected sqlite3_value] object may always be used where an
  4278. ** [unprotected sqlite3_value] object is required, so either
  4279. ** kind of [sqlite3_value] object can be used with this interface.
  4280. **
  4281. ** If these routines are called from within the different thread
  4282. ** than the one containing the application-defined function that received
  4283. ** the [sqlite3_context] pointer, the results are undefined.
  4284. */
  4285. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4286. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4287. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4288. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4289. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4290. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4291. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4292. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4293. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4294. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4295. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4296. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4297. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4298. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4299. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4300. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4301. /*
  4302. ** CAPI3REF: Define New Collating Sequences
  4303. **
  4304. ** ^These functions add, remove, or modify a [collation] associated
  4305. ** with the [database connection] specified as the first argument.
  4306. **
  4307. ** ^The name of the collation is a UTF-8 string
  4308. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4309. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4310. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4311. ** considered to be the same name.
  4312. **
  4313. ** ^(The third argument (eTextRep) must be one of the constants:
  4314. ** <ul>
  4315. ** <li> [SQLITE_UTF8],
  4316. ** <li> [SQLITE_UTF16LE],
  4317. ** <li> [SQLITE_UTF16BE],
  4318. ** <li> [SQLITE_UTF16], or
  4319. ** <li> [SQLITE_UTF16_ALIGNED].
  4320. ** </ul>)^
  4321. ** ^The eTextRep argument determines the encoding of strings passed
  4322. ** to the collating function callback, xCallback.
  4323. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4324. ** force strings to be UTF16 with native byte order.
  4325. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4326. ** on an even byte address.
  4327. **
  4328. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4329. ** through as the first argument to the collating function callback.
  4330. **
  4331. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4332. ** ^Multiple collating functions can be registered using the same name but
  4333. ** with different eTextRep parameters and SQLite will use whichever
  4334. ** function requires the least amount of data transformation.
  4335. ** ^If the xCallback argument is NULL then the collating function is
  4336. ** deleted. ^When all collating functions having the same name are deleted,
  4337. ** that collation is no longer usable.
  4338. **
  4339. ** ^The collating function callback is invoked with a copy of the pArg
  4340. ** application data pointer and with two strings in the encoding specified
  4341. ** by the eTextRep argument. The collating function must return an
  4342. ** integer that is negative, zero, or positive
  4343. ** if the first string is less than, equal to, or greater than the second,
  4344. ** respectively. A collating function must always return the same answer
  4345. ** given the same inputs. If two or more collating functions are registered
  4346. ** to the same collation name (using different eTextRep values) then all
  4347. ** must give an equivalent answer when invoked with equivalent strings.
  4348. ** The collating function must obey the following properties for all
  4349. ** strings A, B, and C:
  4350. **
  4351. ** <ol>
  4352. ** <li> If A==B then B==A.
  4353. ** <li> If A==B and B==C then A==C.
  4354. ** <li> If A&lt;B THEN B&gt;A.
  4355. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4356. ** </ol>
  4357. **
  4358. ** If a collating function fails any of the above constraints and that
  4359. ** collating function is registered and used, then the behavior of SQLite
  4360. ** is undefined.
  4361. **
  4362. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4363. ** with the addition that the xDestroy callback is invoked on pArg when
  4364. ** the collating function is deleted.
  4365. ** ^Collating functions are deleted when they are overridden by later
  4366. ** calls to the collation creation functions or when the
  4367. ** [database connection] is closed using [sqlite3_close()].
  4368. **
  4369. ** ^The xDestroy callback is <u>not</u> called if the
  4370. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4371. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4372. ** check the return code and dispose of the application data pointer
  4373. ** themselves rather than expecting SQLite to deal with it for them.
  4374. ** This is different from every other SQLite interface. The inconsistency
  4375. ** is unfortunate but cannot be changed without breaking backwards
  4376. ** compatibility.
  4377. **
  4378. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4379. */
  4380. SQLITE_API int sqlite3_create_collation(
  4381. sqlite3*,
  4382. const char *zName,
  4383. int eTextRep,
  4384. void *pArg,
  4385. int(*xCompare)(void*,int,const void*,int,const void*)
  4386. );
  4387. SQLITE_API int sqlite3_create_collation_v2(
  4388. sqlite3*,
  4389. const char *zName,
  4390. int eTextRep,
  4391. void *pArg,
  4392. int(*xCompare)(void*,int,const void*,int,const void*),
  4393. void(*xDestroy)(void*)
  4394. );
  4395. SQLITE_API int sqlite3_create_collation16(
  4396. sqlite3*,
  4397. const void *zName,
  4398. int eTextRep,
  4399. void *pArg,
  4400. int(*xCompare)(void*,int,const void*,int,const void*)
  4401. );
  4402. /*
  4403. ** CAPI3REF: Collation Needed Callbacks
  4404. **
  4405. ** ^To avoid having to register all collation sequences before a database
  4406. ** can be used, a single callback function may be registered with the
  4407. ** [database connection] to be invoked whenever an undefined collation
  4408. ** sequence is required.
  4409. **
  4410. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4411. ** then it is passed the names of undefined collation sequences as strings
  4412. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4413. ** the names are passed as UTF-16 in machine native byte order.
  4414. ** ^A call to either function replaces the existing collation-needed callback.
  4415. **
  4416. ** ^(When the callback is invoked, the first argument passed is a copy
  4417. ** of the second argument to sqlite3_collation_needed() or
  4418. ** sqlite3_collation_needed16(). The second argument is the database
  4419. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4420. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4421. ** sequence function required. The fourth parameter is the name of the
  4422. ** required collation sequence.)^
  4423. **
  4424. ** The callback function should register the desired collation using
  4425. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4426. ** [sqlite3_create_collation_v2()].
  4427. */
  4428. SQLITE_API int sqlite3_collation_needed(
  4429. sqlite3*,
  4430. void*,
  4431. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4432. );
  4433. SQLITE_API int sqlite3_collation_needed16(
  4434. sqlite3*,
  4435. void*,
  4436. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4437. );
  4438. #ifdef SQLITE_HAS_CODEC
  4439. /*
  4440. ** Specify the key for an encrypted database. This routine should be
  4441. ** called right after sqlite3_open().
  4442. **
  4443. ** The code to implement this API is not available in the public release
  4444. ** of SQLite.
  4445. */
  4446. SQLITE_API int sqlite3_key(
  4447. sqlite3 *db, /* Database to be rekeyed */
  4448. const void *pKey, int nKey /* The key */
  4449. );
  4450. /*
  4451. ** Change the key on an open database. If the current database is not
  4452. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4453. ** database is decrypted.
  4454. **
  4455. ** The code to implement this API is not available in the public release
  4456. ** of SQLite.
  4457. */
  4458. SQLITE_API int sqlite3_rekey(
  4459. sqlite3 *db, /* Database to be rekeyed */
  4460. const void *pKey, int nKey /* The new key */
  4461. );
  4462. /*
  4463. ** Specify the activation key for a SEE database. Unless
  4464. ** activated, none of the SEE routines will work.
  4465. */
  4466. SQLITE_API void sqlite3_activate_see(
  4467. const char *zPassPhrase /* Activation phrase */
  4468. );
  4469. #endif
  4470. #ifdef SQLITE_ENABLE_CEROD
  4471. /*
  4472. ** Specify the activation key for a CEROD database. Unless
  4473. ** activated, none of the CEROD routines will work.
  4474. */
  4475. SQLITE_API void sqlite3_activate_cerod(
  4476. const char *zPassPhrase /* Activation phrase */
  4477. );
  4478. #endif
  4479. /*
  4480. ** CAPI3REF: Suspend Execution For A Short Time
  4481. **
  4482. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4483. ** for at least a number of milliseconds specified in its parameter.
  4484. **
  4485. ** If the operating system does not support sleep requests with
  4486. ** millisecond time resolution, then the time will be rounded up to
  4487. ** the nearest second. The number of milliseconds of sleep actually
  4488. ** requested from the operating system is returned.
  4489. **
  4490. ** ^SQLite implements this interface by calling the xSleep()
  4491. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4492. ** of the default VFS is not implemented correctly, or not implemented at
  4493. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4494. ** in the previous paragraphs.
  4495. */
  4496. SQLITE_API int sqlite3_sleep(int);
  4497. /*
  4498. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4499. **
  4500. ** ^(If this global variable is made to point to a string which is
  4501. ** the name of a folder (a.k.a. directory), then all temporary files
  4502. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4503. ** will be placed in that directory.)^ ^If this variable
  4504. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4505. ** temporary file directory.
  4506. **
  4507. ** It is not safe to read or modify this variable in more than one
  4508. ** thread at a time. It is not safe to read or modify this variable
  4509. ** if a [database connection] is being used at the same time in a separate
  4510. ** thread.
  4511. ** It is intended that this variable be set once
  4512. ** as part of process initialization and before any SQLite interface
  4513. ** routines have been called and that this variable remain unchanged
  4514. ** thereafter.
  4515. **
  4516. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4517. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4518. ** the [temp_store_directory pragma] always assumes that any string
  4519. ** that this variable points to is held in memory obtained from
  4520. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4521. ** using [sqlite3_free].
  4522. ** Hence, if this variable is modified directly, either it should be
  4523. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4524. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4525. */
  4526. SQLITE_API char *sqlite3_temp_directory;
  4527. /*
  4528. ** CAPI3REF: Test For Auto-Commit Mode
  4529. ** KEYWORDS: {autocommit mode}
  4530. **
  4531. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  4532. ** zero if the given database connection is or is not in autocommit mode,
  4533. ** respectively. ^Autocommit mode is on by default.
  4534. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  4535. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4536. **
  4537. ** If certain kinds of errors occur on a statement within a multi-statement
  4538. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4539. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4540. ** transaction might be rolled back automatically. The only way to
  4541. ** find out whether SQLite automatically rolled back the transaction after
  4542. ** an error is to use this function.
  4543. **
  4544. ** If another thread changes the autocommit status of the database
  4545. ** connection while this routine is running, then the return value
  4546. ** is undefined.
  4547. */
  4548. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4549. /*
  4550. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  4551. **
  4552. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  4553. ** to which a [prepared statement] belongs. ^The [database connection]
  4554. ** returned by sqlite3_db_handle is the same [database connection]
  4555. ** that was the first argument
  4556. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4557. ** create the statement in the first place.
  4558. */
  4559. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4560. /*
  4561. ** CAPI3REF: Find the next prepared statement
  4562. **
  4563. ** ^This interface returns a pointer to the next [prepared statement] after
  4564. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  4565. ** then this interface returns a pointer to the first prepared statement
  4566. ** associated with the database connection pDb. ^If no prepared statement
  4567. ** satisfies the conditions of this routine, it returns NULL.
  4568. **
  4569. ** The [database connection] pointer D in a call to
  4570. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4571. ** connection and in particular must not be a NULL pointer.
  4572. */
  4573. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4574. /*
  4575. ** CAPI3REF: Commit And Rollback Notification Callbacks
  4576. **
  4577. ** ^The sqlite3_commit_hook() interface registers a callback
  4578. ** function to be invoked whenever a transaction is [COMMIT | committed].
  4579. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  4580. ** for the same database connection is overridden.
  4581. ** ^The sqlite3_rollback_hook() interface registers a callback
  4582. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  4583. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  4584. ** for the same database connection is overridden.
  4585. ** ^The pArg argument is passed through to the callback.
  4586. ** ^If the callback on a commit hook function returns non-zero,
  4587. ** then the commit is converted into a rollback.
  4588. **
  4589. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4590. ** return the P argument from the previous call of the same function
  4591. ** on the same [database connection] D, or NULL for
  4592. ** the first call for each function on D.
  4593. **
  4594. ** The callback implementation must not do anything that will modify
  4595. ** the database connection that invoked the callback. Any actions
  4596. ** to modify the database connection must be deferred until after the
  4597. ** completion of the [sqlite3_step()] call that triggered the commit
  4598. ** or rollback hook in the first place.
  4599. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4600. ** database connections for the meaning of "modify" in this paragraph.
  4601. **
  4602. ** ^Registering a NULL function disables the callback.
  4603. **
  4604. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4605. ** operation is allowed to continue normally. ^If the commit hook
  4606. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4607. ** ^The rollback hook is invoked on a rollback that results from a commit
  4608. ** hook returning non-zero, just as it would be with any other rollback.
  4609. **
  4610. ** ^For the purposes of this API, a transaction is said to have been
  4611. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4612. ** an error or constraint causes an implicit rollback to occur.
  4613. ** ^The rollback callback is not invoked if a transaction is
  4614. ** automatically rolled back because the database connection is closed.
  4615. **
  4616. ** See also the [sqlite3_update_hook()] interface.
  4617. */
  4618. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4619. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4620. /*
  4621. ** CAPI3REF: Data Change Notification Callbacks
  4622. **
  4623. ** ^The sqlite3_update_hook() interface registers a callback function
  4624. ** with the [database connection] identified by the first argument
  4625. ** to be invoked whenever a row is updated, inserted or deleted.
  4626. ** ^Any callback set by a previous call to this function
  4627. ** for the same database connection is overridden.
  4628. **
  4629. ** ^The second argument is a pointer to the function to invoke when a
  4630. ** row is updated, inserted or deleted.
  4631. ** ^The first argument to the callback is a copy of the third argument
  4632. ** to sqlite3_update_hook().
  4633. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4634. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4635. ** to be invoked.
  4636. ** ^The third and fourth arguments to the callback contain pointers to the
  4637. ** database and table name containing the affected row.
  4638. ** ^The final callback parameter is the [rowid] of the row.
  4639. ** ^In the case of an update, this is the [rowid] after the update takes place.
  4640. **
  4641. ** ^(The update hook is not invoked when internal system tables are
  4642. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  4643. **
  4644. ** ^In the current implementation, the update hook
  4645. ** is not invoked when duplication rows are deleted because of an
  4646. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  4647. ** invoked when rows are deleted using the [truncate optimization].
  4648. ** The exceptions defined in this paragraph might change in a future
  4649. ** release of SQLite.
  4650. **
  4651. ** The update hook implementation must not do anything that will modify
  4652. ** the database connection that invoked the update hook. Any actions
  4653. ** to modify the database connection must be deferred until after the
  4654. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4655. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4656. ** database connections for the meaning of "modify" in this paragraph.
  4657. **
  4658. ** ^The sqlite3_update_hook(D,C,P) function
  4659. ** returns the P argument from the previous call
  4660. ** on the same [database connection] D, or NULL for
  4661. ** the first call on D.
  4662. **
  4663. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  4664. ** interfaces.
  4665. */
  4666. SQLITE_API void *sqlite3_update_hook(
  4667. sqlite3*,
  4668. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  4669. void*
  4670. );
  4671. /*
  4672. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  4673. ** KEYWORDS: {shared cache}
  4674. **
  4675. ** ^(This routine enables or disables the sharing of the database cache
  4676. ** and schema data structures between [database connection | connections]
  4677. ** to the same database. Sharing is enabled if the argument is true
  4678. ** and disabled if the argument is false.)^
  4679. **
  4680. ** ^Cache sharing is enabled and disabled for an entire process.
  4681. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  4682. ** sharing was enabled or disabled for each thread separately.
  4683. **
  4684. ** ^(The cache sharing mode set by this interface effects all subsequent
  4685. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  4686. ** Existing database connections continue use the sharing mode
  4687. ** that was in effect at the time they were opened.)^
  4688. **
  4689. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  4690. ** successfully. An [error code] is returned otherwise.)^
  4691. **
  4692. ** ^Shared cache is disabled by default. But this might change in
  4693. ** future releases of SQLite. Applications that care about shared
  4694. ** cache setting should set it explicitly.
  4695. **
  4696. ** See Also: [SQLite Shared-Cache Mode]
  4697. */
  4698. SQLITE_API int sqlite3_enable_shared_cache(int);
  4699. /*
  4700. ** CAPI3REF: Attempt To Free Heap Memory
  4701. **
  4702. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  4703. ** of heap memory by deallocating non-essential memory allocations
  4704. ** held by the database library. Memory used to cache database
  4705. ** pages to improve performance is an example of non-essential memory.
  4706. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  4707. ** which might be more or less than the amount requested.
  4708. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  4709. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4710. */
  4711. SQLITE_API int sqlite3_release_memory(int);
  4712. /*
  4713. ** CAPI3REF: Impose A Limit On Heap Size
  4714. **
  4715. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  4716. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  4717. ** ^SQLite strives to keep heap memory utilization below the soft heap
  4718. ** limit by reducing the number of pages held in the page cache
  4719. ** as heap memory usages approaches the limit.
  4720. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  4721. ** below the limit, it will exceed the limit rather than generate
  4722. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  4723. ** is advisory only.
  4724. **
  4725. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  4726. ** the soft heap limit prior to the call. ^If the argument N is negative
  4727. ** then no change is made to the soft heap limit. Hence, the current
  4728. ** size of the soft heap limit can be determined by invoking
  4729. ** sqlite3_soft_heap_limit64() with a negative argument.
  4730. **
  4731. ** ^If the argument N is zero then the soft heap limit is disabled.
  4732. **
  4733. ** ^(The soft heap limit is not enforced in the current implementation
  4734. ** if one or more of following conditions are true:
  4735. **
  4736. ** <ul>
  4737. ** <li> The soft heap limit is set to zero.
  4738. ** <li> Memory accounting is disabled using a combination of the
  4739. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  4740. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  4741. ** <li> An alternative page cache implementation is specified using
  4742. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
  4743. ** <li> The page cache allocates from its own memory pool supplied
  4744. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  4745. ** from the heap.
  4746. ** </ul>)^
  4747. **
  4748. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  4749. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  4750. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  4751. ** the soft heap limit is enforced on every memory allocation. Without
  4752. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  4753. ** when memory is allocated by the page cache. Testing suggests that because
  4754. ** the page cache is the predominate memory user in SQLite, most
  4755. ** applications will achieve adequate soft heap limit enforcement without
  4756. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4757. **
  4758. ** The circumstances under which SQLite will enforce the soft heap limit may
  4759. ** changes in future releases of SQLite.
  4760. */
  4761. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  4762. /*
  4763. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  4764. ** DEPRECATED
  4765. **
  4766. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  4767. ** interface. This routine is provided for historical compatibility
  4768. ** only. All new applications should use the
  4769. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  4770. */
  4771. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  4772. /*
  4773. ** CAPI3REF: Extract Metadata About A Column Of A Table
  4774. **
  4775. ** ^This routine returns metadata about a specific column of a specific
  4776. ** database table accessible using the [database connection] handle
  4777. ** passed as the first function argument.
  4778. **
  4779. ** ^The column is identified by the second, third and fourth parameters to
  4780. ** this function. ^The second parameter is either the name of the database
  4781. ** (i.e. "main", "temp", or an attached database) containing the specified
  4782. ** table or NULL. ^If it is NULL, then all attached databases are searched
  4783. ** for the table using the same algorithm used by the database engine to
  4784. ** resolve unqualified table references.
  4785. **
  4786. ** ^The third and fourth parameters to this function are the table and column
  4787. ** name of the desired column, respectively. Neither of these parameters
  4788. ** may be NULL.
  4789. **
  4790. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  4791. ** and subsequent parameters to this function. ^Any of these arguments may be
  4792. ** NULL, in which case the corresponding element of metadata is omitted.
  4793. **
  4794. ** ^(<blockquote>
  4795. ** <table border="1">
  4796. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  4797. **
  4798. ** <tr><td> 5th <td> const char* <td> Data type
  4799. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  4800. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  4801. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  4802. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  4803. ** </table>
  4804. ** </blockquote>)^
  4805. **
  4806. ** ^The memory pointed to by the character pointers returned for the
  4807. ** declaration type and collation sequence is valid only until the next
  4808. ** call to any SQLite API function.
  4809. **
  4810. ** ^If the specified table is actually a view, an [error code] is returned.
  4811. **
  4812. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  4813. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  4814. ** parameters are set for the explicitly declared column. ^(If there is no
  4815. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  4816. ** parameters are set as follows:
  4817. **
  4818. ** <pre>
  4819. ** data type: "INTEGER"
  4820. ** collation sequence: "BINARY"
  4821. ** not null: 0
  4822. ** primary key: 1
  4823. ** auto increment: 0
  4824. ** </pre>)^
  4825. **
  4826. ** ^(This function may load one or more schemas from database files. If an
  4827. ** error occurs during this process, or if the requested table or column
  4828. ** cannot be found, an [error code] is returned and an error message left
  4829. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  4830. **
  4831. ** ^This API is only available if the library was compiled with the
  4832. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  4833. */
  4834. SQLITE_API int sqlite3_table_column_metadata(
  4835. sqlite3 *db, /* Connection handle */
  4836. const char *zDbName, /* Database name or NULL */
  4837. const char *zTableName, /* Table name */
  4838. const char *zColumnName, /* Column name */
  4839. char const **pzDataType, /* OUTPUT: Declared data type */
  4840. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  4841. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  4842. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  4843. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  4844. );
  4845. /*
  4846. ** CAPI3REF: Load An Extension
  4847. **
  4848. ** ^This interface loads an SQLite extension library from the named file.
  4849. **
  4850. ** ^The sqlite3_load_extension() interface attempts to load an
  4851. ** SQLite extension library contained in the file zFile.
  4852. **
  4853. ** ^The entry point is zProc.
  4854. ** ^zProc may be 0, in which case the name of the entry point
  4855. ** defaults to "sqlite3_extension_init".
  4856. ** ^The sqlite3_load_extension() interface returns
  4857. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  4858. ** ^If an error occurs and pzErrMsg is not 0, then the
  4859. ** [sqlite3_load_extension()] interface shall attempt to
  4860. ** fill *pzErrMsg with error message text stored in memory
  4861. ** obtained from [sqlite3_malloc()]. The calling function
  4862. ** should free this memory by calling [sqlite3_free()].
  4863. **
  4864. ** ^Extension loading must be enabled using
  4865. ** [sqlite3_enable_load_extension()] prior to calling this API,
  4866. ** otherwise an error will be returned.
  4867. **
  4868. ** See also the [load_extension() SQL function].
  4869. */
  4870. SQLITE_API int sqlite3_load_extension(
  4871. sqlite3 *db, /* Load the extension into this database connection */
  4872. const char *zFile, /* Name of the shared library containing extension */
  4873. const char *zProc, /* Entry point. Derived from zFile if 0 */
  4874. char **pzErrMsg /* Put error message here if not 0 */
  4875. );
  4876. /*
  4877. ** CAPI3REF: Enable Or Disable Extension Loading
  4878. **
  4879. ** ^So as not to open security holes in older applications that are
  4880. ** unprepared to deal with extension loading, and as a means of disabling
  4881. ** extension loading while evaluating user-entered SQL, the following API
  4882. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  4883. **
  4884. ** ^Extension loading is off by default. See ticket #1863.
  4885. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  4886. ** to turn extension loading on and call it with onoff==0 to turn
  4887. ** it back off again.
  4888. */
  4889. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  4890. /*
  4891. ** CAPI3REF: Automatically Load Statically Linked Extensions
  4892. **
  4893. ** ^This interface causes the xEntryPoint() function to be invoked for
  4894. ** each new [database connection] that is created. The idea here is that
  4895. ** xEntryPoint() is the entry point for a statically linked SQLite extension
  4896. ** that is to be automatically loaded into all new database connections.
  4897. **
  4898. ** ^(Even though the function prototype shows that xEntryPoint() takes
  4899. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  4900. ** arguments and expects and integer result as if the signature of the
  4901. ** entry point where as follows:
  4902. **
  4903. ** <blockquote><pre>
  4904. ** &nbsp; int xEntryPoint(
  4905. ** &nbsp; sqlite3 *db,
  4906. ** &nbsp; const char **pzErrMsg,
  4907. ** &nbsp; const struct sqlite3_api_routines *pThunk
  4908. ** &nbsp; );
  4909. ** </pre></blockquote>)^
  4910. **
  4911. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  4912. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  4913. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  4914. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  4915. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  4916. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  4917. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  4918. **
  4919. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  4920. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  4921. ** will be called more than once for each database connection that is opened.
  4922. **
  4923. ** See also: [sqlite3_reset_auto_extension()].
  4924. */
  4925. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  4926. /*
  4927. ** CAPI3REF: Reset Automatic Extension Loading
  4928. **
  4929. ** ^This interface disables all automatic extensions previously
  4930. ** registered using [sqlite3_auto_extension()].
  4931. */
  4932. SQLITE_API void sqlite3_reset_auto_extension(void);
  4933. /*
  4934. ** The interface to the virtual-table mechanism is currently considered
  4935. ** to be experimental. The interface might change in incompatible ways.
  4936. ** If this is a problem for you, do not use the interface at this time.
  4937. **
  4938. ** When the virtual-table mechanism stabilizes, we will declare the
  4939. ** interface fixed, support it indefinitely, and remove this comment.
  4940. */
  4941. /*
  4942. ** Structures used by the virtual table interface
  4943. */
  4944. typedef struct sqlite3_vtab sqlite3_vtab;
  4945. typedef struct sqlite3_index_info sqlite3_index_info;
  4946. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  4947. typedef struct sqlite3_module sqlite3_module;
  4948. /*
  4949. ** CAPI3REF: Virtual Table Object
  4950. ** KEYWORDS: sqlite3_module {virtual table module}
  4951. **
  4952. ** This structure, sometimes called a "virtual table module",
  4953. ** defines the implementation of a [virtual tables].
  4954. ** This structure consists mostly of methods for the module.
  4955. **
  4956. ** ^A virtual table module is created by filling in a persistent
  4957. ** instance of this structure and passing a pointer to that instance
  4958. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  4959. ** ^The registration remains valid until it is replaced by a different
  4960. ** module or until the [database connection] closes. The content
  4961. ** of this structure must not change while it is registered with
  4962. ** any database connection.
  4963. */
  4964. struct sqlite3_module {
  4965. int iVersion;
  4966. int (*xCreate)(sqlite3*, void *pAux,
  4967. int argc, const char *const*argv,
  4968. sqlite3_vtab **ppVTab, char**);
  4969. int (*xConnect)(sqlite3*, void *pAux,
  4970. int argc, const char *const*argv,
  4971. sqlite3_vtab **ppVTab, char**);
  4972. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  4973. int (*xDisconnect)(sqlite3_vtab *pVTab);
  4974. int (*xDestroy)(sqlite3_vtab *pVTab);
  4975. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  4976. int (*xClose)(sqlite3_vtab_cursor*);
  4977. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  4978. int argc, sqlite3_value **argv);
  4979. int (*xNext)(sqlite3_vtab_cursor*);
  4980. int (*xEof)(sqlite3_vtab_cursor*);
  4981. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  4982. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  4983. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  4984. int (*xBegin)(sqlite3_vtab *pVTab);
  4985. int (*xSync)(sqlite3_vtab *pVTab);
  4986. int (*xCommit)(sqlite3_vtab *pVTab);
  4987. int (*xRollback)(sqlite3_vtab *pVTab);
  4988. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  4989. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  4990. void **ppArg);
  4991. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  4992. };
  4993. /*
  4994. ** CAPI3REF: Virtual Table Indexing Information
  4995. ** KEYWORDS: sqlite3_index_info
  4996. **
  4997. ** The sqlite3_index_info structure and its substructures is used as part
  4998. ** of the [virtual table] interface to
  4999. ** pass information into and receive the reply from the [xBestIndex]
  5000. ** method of a [virtual table module]. The fields under **Inputs** are the
  5001. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5002. ** results into the **Outputs** fields.
  5003. **
  5004. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5005. **
  5006. ** <blockquote>column OP expr</blockquote>
  5007. **
  5008. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5009. ** stored in aConstraint[].op using one of the
  5010. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5011. ** ^(The index of the column is stored in
  5012. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5013. ** expr on the right-hand side can be evaluated (and thus the constraint
  5014. ** is usable) and false if it cannot.)^
  5015. **
  5016. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5017. ** and makes other simplifications to the WHERE clause in an attempt to
  5018. ** get as many WHERE clause terms into the form shown above as possible.
  5019. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5020. ** relevant to the particular virtual table being queried.
  5021. **
  5022. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5023. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5024. **
  5025. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5026. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5027. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5028. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5029. ** is true, then the constraint is assumed to be fully handled by the
  5030. ** virtual table and is not checked again by SQLite.)^
  5031. **
  5032. ** ^The idxNum and idxPtr values are recorded and passed into the
  5033. ** [xFilter] method.
  5034. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5035. ** needToFreeIdxPtr is true.
  5036. **
  5037. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5038. ** the correct order to satisfy the ORDER BY clause so that no separate
  5039. ** sorting step is required.
  5040. **
  5041. ** ^The estimatedCost value is an estimate of the cost of doing the
  5042. ** particular lookup. A full scan of a table with N entries should have
  5043. ** a cost of N. A binary search of a table of N entries should have a
  5044. ** cost of approximately log(N).
  5045. */
  5046. struct sqlite3_index_info {
  5047. /* Inputs */
  5048. int nConstraint; /* Number of entries in aConstraint */
  5049. struct sqlite3_index_constraint {
  5050. int iColumn; /* Column on left-hand side of constraint */
  5051. unsigned char op; /* Constraint operator */
  5052. unsigned char usable; /* True if this constraint is usable */
  5053. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5054. } *aConstraint; /* Table of WHERE clause constraints */
  5055. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5056. struct sqlite3_index_orderby {
  5057. int iColumn; /* Column number */
  5058. unsigned char desc; /* True for DESC. False for ASC. */
  5059. } *aOrderBy; /* The ORDER BY clause */
  5060. /* Outputs */
  5061. struct sqlite3_index_constraint_usage {
  5062. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5063. unsigned char omit; /* Do not code a test for this constraint */
  5064. } *aConstraintUsage;
  5065. int idxNum; /* Number used to identify the index */
  5066. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5067. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5068. int orderByConsumed; /* True if output is already ordered */
  5069. double estimatedCost; /* Estimated cost of using this index */
  5070. };
  5071. /*
  5072. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5073. **
  5074. ** These macros defined the allowed values for the
  5075. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5076. ** an operator that is part of a constraint term in the wHERE clause of
  5077. ** a query that uses a [virtual table].
  5078. */
  5079. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5080. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5081. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5082. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5083. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5084. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5085. /*
  5086. ** CAPI3REF: Register A Virtual Table Implementation
  5087. **
  5088. ** ^These routines are used to register a new [virtual table module] name.
  5089. ** ^Module names must be registered before
  5090. ** creating a new [virtual table] using the module and before using a
  5091. ** preexisting [virtual table] for the module.
  5092. **
  5093. ** ^The module name is registered on the [database connection] specified
  5094. ** by the first parameter. ^The name of the module is given by the
  5095. ** second parameter. ^The third parameter is a pointer to
  5096. ** the implementation of the [virtual table module]. ^The fourth
  5097. ** parameter is an arbitrary client data pointer that is passed through
  5098. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5099. ** when a new virtual table is be being created or reinitialized.
  5100. **
  5101. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5102. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5103. ** invoke the destructor function (if it is not NULL) when SQLite
  5104. ** no longer needs the pClientData pointer. ^The destructor will also
  5105. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5106. ** ^The sqlite3_create_module()
  5107. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5108. ** destructor.
  5109. */
  5110. SQLITE_API int sqlite3_create_module(
  5111. sqlite3 *db, /* SQLite connection to register module with */
  5112. const char *zName, /* Name of the module */
  5113. const sqlite3_module *p, /* Methods for the module */
  5114. void *pClientData /* Client data for xCreate/xConnect */
  5115. );
  5116. SQLITE_API int sqlite3_create_module_v2(
  5117. sqlite3 *db, /* SQLite connection to register module with */
  5118. const char *zName, /* Name of the module */
  5119. const sqlite3_module *p, /* Methods for the module */
  5120. void *pClientData, /* Client data for xCreate/xConnect */
  5121. void(*xDestroy)(void*) /* Module destructor function */
  5122. );
  5123. /*
  5124. ** CAPI3REF: Virtual Table Instance Object
  5125. ** KEYWORDS: sqlite3_vtab
  5126. **
  5127. ** Every [virtual table module] implementation uses a subclass
  5128. ** of this object to describe a particular instance
  5129. ** of the [virtual table]. Each subclass will
  5130. ** be tailored to the specific needs of the module implementation.
  5131. ** The purpose of this superclass is to define certain fields that are
  5132. ** common to all module implementations.
  5133. **
  5134. ** ^Virtual tables methods can set an error message by assigning a
  5135. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5136. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5137. ** prior to assigning a new string to zErrMsg. ^After the error message
  5138. ** is delivered up to the client application, the string will be automatically
  5139. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5140. */
  5141. struct sqlite3_vtab {
  5142. const sqlite3_module *pModule; /* The module for this virtual table */
  5143. int nRef; /* NO LONGER USED */
  5144. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5145. /* Virtual table implementations will typically add additional fields */
  5146. };
  5147. /*
  5148. ** CAPI3REF: Virtual Table Cursor Object
  5149. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5150. **
  5151. ** Every [virtual table module] implementation uses a subclass of the
  5152. ** following structure to describe cursors that point into the
  5153. ** [virtual table] and are used
  5154. ** to loop through the virtual table. Cursors are created using the
  5155. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5156. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5157. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5158. ** of the module. Each module implementation will define
  5159. ** the content of a cursor structure to suit its own needs.
  5160. **
  5161. ** This superclass exists in order to define fields of the cursor that
  5162. ** are common to all implementations.
  5163. */
  5164. struct sqlite3_vtab_cursor {
  5165. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5166. /* Virtual table implementations will typically add additional fields */
  5167. };
  5168. /*
  5169. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5170. **
  5171. ** ^The [xCreate] and [xConnect] methods of a
  5172. ** [virtual table module] call this interface
  5173. ** to declare the format (the names and datatypes of the columns) of
  5174. ** the virtual tables they implement.
  5175. */
  5176. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5177. /*
  5178. ** CAPI3REF: Overload A Function For A Virtual Table
  5179. **
  5180. ** ^(Virtual tables can provide alternative implementations of functions
  5181. ** using the [xFindFunction] method of the [virtual table module].
  5182. ** But global versions of those functions
  5183. ** must exist in order to be overloaded.)^
  5184. **
  5185. ** ^(This API makes sure a global version of a function with a particular
  5186. ** name and number of parameters exists. If no such function exists
  5187. ** before this API is called, a new function is created.)^ ^The implementation
  5188. ** of the new function always causes an exception to be thrown. So
  5189. ** the new function is not good for anything by itself. Its only
  5190. ** purpose is to be a placeholder function that can be overloaded
  5191. ** by a [virtual table].
  5192. */
  5193. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5194. /*
  5195. ** The interface to the virtual-table mechanism defined above (back up
  5196. ** to a comment remarkably similar to this one) is currently considered
  5197. ** to be experimental. The interface might change in incompatible ways.
  5198. ** If this is a problem for you, do not use the interface at this time.
  5199. **
  5200. ** When the virtual-table mechanism stabilizes, we will declare the
  5201. ** interface fixed, support it indefinitely, and remove this comment.
  5202. */
  5203. /*
  5204. ** CAPI3REF: A Handle To An Open BLOB
  5205. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5206. **
  5207. ** An instance of this object represents an open BLOB on which
  5208. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5209. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5210. ** and destroyed by [sqlite3_blob_close()].
  5211. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5212. ** can be used to read or write small subsections of the BLOB.
  5213. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5214. */
  5215. typedef struct sqlite3_blob sqlite3_blob;
  5216. /*
  5217. ** CAPI3REF: Open A BLOB For Incremental I/O
  5218. **
  5219. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5220. ** in row iRow, column zColumn, table zTable in database zDb;
  5221. ** in other words, the same BLOB that would be selected by:
  5222. **
  5223. ** <pre>
  5224. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5225. ** </pre>)^
  5226. **
  5227. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5228. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5229. ** ^It is not possible to open a column that is part of an index or primary
  5230. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5231. ** not possible to open a column that is part of a [child key] for writing.
  5232. **
  5233. ** ^Note that the database name is not the filename that contains
  5234. ** the database but rather the symbolic name of the database that
  5235. ** appears after the AS keyword when the database is connected using [ATTACH].
  5236. ** ^For the main database file, the database name is "main".
  5237. ** ^For TEMP tables, the database name is "temp".
  5238. **
  5239. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5240. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5241. ** to be a null pointer.)^
  5242. ** ^This function sets the [database connection] error code and message
  5243. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5244. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5245. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5246. ** regardless of the success or failure of this routine.
  5247. **
  5248. ** ^(If the row that a BLOB handle points to is modified by an
  5249. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5250. ** then the BLOB handle is marked as "expired".
  5251. ** This is true if any column of the row is changed, even a column
  5252. ** other than the one the BLOB handle is open on.)^
  5253. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5254. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5255. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5256. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5257. ** commit if the transaction continues to completion.)^
  5258. **
  5259. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5260. ** the opened blob. ^The size of a blob may not be changed by this
  5261. ** interface. Use the [UPDATE] SQL command to change the size of a
  5262. ** blob.
  5263. **
  5264. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5265. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5266. ** to create an empty, zero-filled blob in which to read or write using
  5267. ** this interface.
  5268. **
  5269. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5270. ** be released by a call to [sqlite3_blob_close()].
  5271. */
  5272. SQLITE_API int sqlite3_blob_open(
  5273. sqlite3*,
  5274. const char *zDb,
  5275. const char *zTable,
  5276. const char *zColumn,
  5277. sqlite3_int64 iRow,
  5278. int flags,
  5279. sqlite3_blob **ppBlob
  5280. );
  5281. /*
  5282. ** CAPI3REF: Move a BLOB Handle to a New Row
  5283. **
  5284. ** ^This function is used to move an existing blob handle so that it points
  5285. ** to a different row of the same database table. ^The new row is identified
  5286. ** by the rowid value passed as the second argument. Only the row can be
  5287. ** changed. ^The database, table and column on which the blob handle is open
  5288. ** remain the same. Moving an existing blob handle to a new row can be
  5289. ** faster than closing the existing handle and opening a new one.
  5290. **
  5291. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5292. ** it must exist and there must be either a blob or text value stored in
  5293. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5294. ** it does not contain a blob or text value, or if another error occurs, an
  5295. ** SQLite error code is returned and the blob handle is considered aborted.
  5296. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5297. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5298. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5299. ** always returns zero.
  5300. **
  5301. ** ^This function sets the database handle error code and message.
  5302. */
  5303. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5304. /*
  5305. ** CAPI3REF: Close A BLOB Handle
  5306. **
  5307. ** ^Closes an open [BLOB handle].
  5308. **
  5309. ** ^Closing a BLOB shall cause the current transaction to commit
  5310. ** if there are no other BLOBs, no pending prepared statements, and the
  5311. ** database connection is in [autocommit mode].
  5312. ** ^If any writes were made to the BLOB, they might be held in cache
  5313. ** until the close operation if they will fit.
  5314. **
  5315. ** ^(Closing the BLOB often forces the changes
  5316. ** out to disk and so if any I/O errors occur, they will likely occur
  5317. ** at the time when the BLOB is closed. Any errors that occur during
  5318. ** closing are reported as a non-zero return value.)^
  5319. **
  5320. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5321. ** an error code, the BLOB is still closed.)^
  5322. **
  5323. ** ^Calling this routine with a null pointer (such as would be returned
  5324. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5325. */
  5326. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5327. /*
  5328. ** CAPI3REF: Return The Size Of An Open BLOB
  5329. **
  5330. ** ^Returns the size in bytes of the BLOB accessible via the
  5331. ** successfully opened [BLOB handle] in its only argument. ^The
  5332. ** incremental blob I/O routines can only read or overwriting existing
  5333. ** blob content; they cannot change the size of a blob.
  5334. **
  5335. ** This routine only works on a [BLOB handle] which has been created
  5336. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5337. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5338. ** to this routine results in undefined and probably undesirable behavior.
  5339. */
  5340. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5341. /*
  5342. ** CAPI3REF: Read Data From A BLOB Incrementally
  5343. **
  5344. ** ^(This function is used to read data from an open [BLOB handle] into a
  5345. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5346. ** from the open BLOB, starting at offset iOffset.)^
  5347. **
  5348. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5349. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5350. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5351. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5352. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5353. **
  5354. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5355. ** error code of [SQLITE_ABORT].
  5356. **
  5357. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5358. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5359. **
  5360. ** This routine only works on a [BLOB handle] which has been created
  5361. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5362. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5363. ** to this routine results in undefined and probably undesirable behavior.
  5364. **
  5365. ** See also: [sqlite3_blob_write()].
  5366. */
  5367. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5368. /*
  5369. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5370. **
  5371. ** ^This function is used to write data into an open [BLOB handle] from a
  5372. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5373. ** into the open BLOB, starting at offset iOffset.
  5374. **
  5375. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5376. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5377. ** this function returns [SQLITE_READONLY].
  5378. **
  5379. ** ^This function may only modify the contents of the BLOB; it is
  5380. ** not possible to increase the size of a BLOB using this API.
  5381. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5382. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5383. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5384. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5385. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5386. **
  5387. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5388. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5389. ** before the [BLOB handle] expired are not rolled back by the
  5390. ** expiration of the handle, though of course those changes might
  5391. ** have been overwritten by the statement that expired the BLOB handle
  5392. ** or by other independent statements.
  5393. **
  5394. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5395. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5396. **
  5397. ** This routine only works on a [BLOB handle] which has been created
  5398. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5399. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5400. ** to this routine results in undefined and probably undesirable behavior.
  5401. **
  5402. ** See also: [sqlite3_blob_read()].
  5403. */
  5404. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5405. /*
  5406. ** CAPI3REF: Virtual File System Objects
  5407. **
  5408. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5409. ** that SQLite uses to interact
  5410. ** with the underlying operating system. Most SQLite builds come with a
  5411. ** single default VFS that is appropriate for the host computer.
  5412. ** New VFSes can be registered and existing VFSes can be unregistered.
  5413. ** The following interfaces are provided.
  5414. **
  5415. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5416. ** ^Names are case sensitive.
  5417. ** ^Names are zero-terminated UTF-8 strings.
  5418. ** ^If there is no match, a NULL pointer is returned.
  5419. ** ^If zVfsName is NULL then the default VFS is returned.
  5420. **
  5421. ** ^New VFSes are registered with sqlite3_vfs_register().
  5422. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5423. ** ^The same VFS can be registered multiple times without injury.
  5424. ** ^To make an existing VFS into the default VFS, register it again
  5425. ** with the makeDflt flag set. If two different VFSes with the
  5426. ** same name are registered, the behavior is undefined. If a
  5427. ** VFS is registered with a name that is NULL or an empty string,
  5428. ** then the behavior is undefined.
  5429. **
  5430. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5431. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5432. ** the default. The choice for the new VFS is arbitrary.)^
  5433. */
  5434. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5435. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5436. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5437. /*
  5438. ** CAPI3REF: Mutexes
  5439. **
  5440. ** The SQLite core uses these routines for thread
  5441. ** synchronization. Though they are intended for internal
  5442. ** use by SQLite, code that links against SQLite is
  5443. ** permitted to use any of these routines.
  5444. **
  5445. ** The SQLite source code contains multiple implementations
  5446. ** of these mutex routines. An appropriate implementation
  5447. ** is selected automatically at compile-time. ^(The following
  5448. ** implementations are available in the SQLite core:
  5449. **
  5450. ** <ul>
  5451. ** <li> SQLITE_MUTEX_OS2
  5452. ** <li> SQLITE_MUTEX_PTHREAD
  5453. ** <li> SQLITE_MUTEX_W32
  5454. ** <li> SQLITE_MUTEX_NOOP
  5455. ** </ul>)^
  5456. **
  5457. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5458. ** that does no real locking and is appropriate for use in
  5459. ** a single-threaded application. ^The SQLITE_MUTEX_OS2,
  5460. ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
  5461. ** are appropriate for use on OS/2, Unix, and Windows.
  5462. **
  5463. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5464. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5465. ** implementation is included with the library. In this case the
  5466. ** application must supply a custom mutex implementation using the
  5467. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5468. ** before calling sqlite3_initialize() or any other public sqlite3_
  5469. ** function that calls sqlite3_initialize().)^
  5470. **
  5471. ** ^The sqlite3_mutex_alloc() routine allocates a new
  5472. ** mutex and returns a pointer to it. ^If it returns NULL
  5473. ** that means that a mutex could not be allocated. ^SQLite
  5474. ** will unwind its stack and return an error. ^(The argument
  5475. ** to sqlite3_mutex_alloc() is one of these integer constants:
  5476. **
  5477. ** <ul>
  5478. ** <li> SQLITE_MUTEX_FAST
  5479. ** <li> SQLITE_MUTEX_RECURSIVE
  5480. ** <li> SQLITE_MUTEX_STATIC_MASTER
  5481. ** <li> SQLITE_MUTEX_STATIC_MEM
  5482. ** <li> SQLITE_MUTEX_STATIC_MEM2
  5483. ** <li> SQLITE_MUTEX_STATIC_PRNG
  5484. ** <li> SQLITE_MUTEX_STATIC_LRU
  5485. ** <li> SQLITE_MUTEX_STATIC_LRU2
  5486. ** </ul>)^
  5487. **
  5488. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  5489. ** cause sqlite3_mutex_alloc() to create
  5490. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  5491. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  5492. ** The mutex implementation does not need to make a distinction
  5493. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  5494. ** not want to. ^SQLite will only request a recursive mutex in
  5495. ** cases where it really needs one. ^If a faster non-recursive mutex
  5496. ** implementation is available on the host platform, the mutex subsystem
  5497. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  5498. **
  5499. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  5500. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  5501. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  5502. ** used by the current version of SQLite. Future versions of SQLite
  5503. ** may add additional static mutexes. Static mutexes are for internal
  5504. ** use by SQLite only. Applications that use SQLite mutexes should
  5505. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  5506. ** SQLITE_MUTEX_RECURSIVE.
  5507. **
  5508. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  5509. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  5510. ** returns a different mutex on every call. ^But for the static
  5511. ** mutex types, the same mutex is returned on every call that has
  5512. ** the same type number.
  5513. **
  5514. ** ^The sqlite3_mutex_free() routine deallocates a previously
  5515. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  5516. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  5517. ** use when they are deallocated. Attempting to deallocate a static
  5518. ** mutex results in undefined behavior. ^SQLite never deallocates
  5519. ** a static mutex.
  5520. **
  5521. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  5522. ** to enter a mutex. ^If another thread is already within the mutex,
  5523. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  5524. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  5525. ** upon successful entry. ^(Mutexes created using
  5526. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  5527. ** In such cases the,
  5528. ** mutex must be exited an equal number of times before another thread
  5529. ** can enter.)^ ^(If the same thread tries to enter any other
  5530. ** kind of mutex more than once, the behavior is undefined.
  5531. ** SQLite will never exhibit
  5532. ** such behavior in its own use of mutexes.)^
  5533. **
  5534. ** ^(Some systems (for example, Windows 95) do not support the operation
  5535. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  5536. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  5537. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  5538. **
  5539. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  5540. ** previously entered by the same thread. ^(The behavior
  5541. ** is undefined if the mutex is not currently entered by the
  5542. ** calling thread or is not currently allocated. SQLite will
  5543. ** never do either.)^
  5544. **
  5545. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  5546. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  5547. ** behave as no-ops.
  5548. **
  5549. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  5550. */
  5551. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  5552. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  5553. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  5554. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  5555. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  5556. /*
  5557. ** CAPI3REF: Mutex Methods Object
  5558. **
  5559. ** An instance of this structure defines the low-level routines
  5560. ** used to allocate and use mutexes.
  5561. **
  5562. ** Usually, the default mutex implementations provided by SQLite are
  5563. ** sufficient, however the user has the option of substituting a custom
  5564. ** implementation for specialized deployments or systems for which SQLite
  5565. ** does not provide a suitable implementation. In this case, the user
  5566. ** creates and populates an instance of this structure to pass
  5567. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  5568. ** Additionally, an instance of this structure can be used as an
  5569. ** output variable when querying the system for the current mutex
  5570. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  5571. **
  5572. ** ^The xMutexInit method defined by this structure is invoked as
  5573. ** part of system initialization by the sqlite3_initialize() function.
  5574. ** ^The xMutexInit routine is called by SQLite exactly once for each
  5575. ** effective call to [sqlite3_initialize()].
  5576. **
  5577. ** ^The xMutexEnd method defined by this structure is invoked as
  5578. ** part of system shutdown by the sqlite3_shutdown() function. The
  5579. ** implementation of this method is expected to release all outstanding
  5580. ** resources obtained by the mutex methods implementation, especially
  5581. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  5582. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  5583. **
  5584. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  5585. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5586. ** xMutexNotheld) implement the following interfaces (respectively):
  5587. **
  5588. ** <ul>
  5589. ** <li> [sqlite3_mutex_alloc()] </li>
  5590. ** <li> [sqlite3_mutex_free()] </li>
  5591. ** <li> [sqlite3_mutex_enter()] </li>
  5592. ** <li> [sqlite3_mutex_try()] </li>
  5593. ** <li> [sqlite3_mutex_leave()] </li>
  5594. ** <li> [sqlite3_mutex_held()] </li>
  5595. ** <li> [sqlite3_mutex_notheld()] </li>
  5596. ** </ul>)^
  5597. **
  5598. ** The only difference is that the public sqlite3_XXX functions enumerated
  5599. ** above silently ignore any invocations that pass a NULL pointer instead
  5600. ** of a valid mutex handle. The implementations of the methods defined
  5601. ** by this structure are not required to handle this case, the results
  5602. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  5603. ** (i.e. it is acceptable to provide an implementation that segfaults if
  5604. ** it is passed a NULL pointer).
  5605. **
  5606. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  5607. ** invoke xMutexInit() multiple times within the same process and without
  5608. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  5609. ** xMutexInit() must be no-ops.
  5610. **
  5611. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  5612. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  5613. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  5614. ** memory allocation for a fast or recursive mutex.
  5615. **
  5616. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  5617. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  5618. ** If xMutexInit fails in any way, it is expected to clean up after itself
  5619. ** prior to returning.
  5620. */
  5621. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  5622. struct sqlite3_mutex_methods {
  5623. int (*xMutexInit)(void);
  5624. int (*xMutexEnd)(void);
  5625. sqlite3_mutex *(*xMutexAlloc)(int);
  5626. void (*xMutexFree)(sqlite3_mutex *);
  5627. void (*xMutexEnter)(sqlite3_mutex *);
  5628. int (*xMutexTry)(sqlite3_mutex *);
  5629. void (*xMutexLeave)(sqlite3_mutex *);
  5630. int (*xMutexHeld)(sqlite3_mutex *);
  5631. int (*xMutexNotheld)(sqlite3_mutex *);
  5632. };
  5633. /*
  5634. ** CAPI3REF: Mutex Verification Routines
  5635. **
  5636. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  5637. ** are intended for use inside assert() statements. ^The SQLite core
  5638. ** never uses these routines except inside an assert() and applications
  5639. ** are advised to follow the lead of the core. ^The SQLite core only
  5640. ** provides implementations for these routines when it is compiled
  5641. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  5642. ** are only required to provide these routines if SQLITE_DEBUG is
  5643. ** defined and if NDEBUG is not defined.
  5644. **
  5645. ** ^These routines should return true if the mutex in their argument
  5646. ** is held or not held, respectively, by the calling thread.
  5647. **
  5648. ** ^The implementation is not required to provided versions of these
  5649. ** routines that actually work. If the implementation does not provide working
  5650. ** versions of these routines, it should at least provide stubs that always
  5651. ** return true so that one does not get spurious assertion failures.
  5652. **
  5653. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  5654. ** the routine should return 1. This seems counter-intuitive since
  5655. ** clearly the mutex cannot be held if it does not exist. But the
  5656. ** the reason the mutex does not exist is because the build is not
  5657. ** using mutexes. And we do not want the assert() containing the
  5658. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  5659. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  5660. ** interface should also return 1 when given a NULL pointer.
  5661. */
  5662. #ifndef NDEBUG
  5663. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  5664. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  5665. #endif
  5666. /*
  5667. ** CAPI3REF: Mutex Types
  5668. **
  5669. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  5670. ** which is one of these integer constants.
  5671. **
  5672. ** The set of static mutexes may change from one SQLite release to the
  5673. ** next. Applications that override the built-in mutex logic must be
  5674. ** prepared to accommodate additional static mutexes.
  5675. */
  5676. #define SQLITE_MUTEX_FAST 0
  5677. #define SQLITE_MUTEX_RECURSIVE 1
  5678. #define SQLITE_MUTEX_STATIC_MASTER 2
  5679. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  5680. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  5681. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  5682. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  5683. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  5684. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  5685. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  5686. /*
  5687. ** CAPI3REF: Retrieve the mutex for a database connection
  5688. **
  5689. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  5690. ** serializes access to the [database connection] given in the argument
  5691. ** when the [threading mode] is Serialized.
  5692. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  5693. ** routine returns a NULL pointer.
  5694. */
  5695. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  5696. /*
  5697. ** CAPI3REF: Low-Level Control Of Database Files
  5698. **
  5699. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  5700. ** xFileControl method for the [sqlite3_io_methods] object associated
  5701. ** with a particular database identified by the second argument. ^The
  5702. ** name of the database is "main" for the main database or "temp" for the
  5703. ** TEMP database, or the name that appears after the AS keyword for
  5704. ** databases that are added using the [ATTACH] SQL command.
  5705. ** ^A NULL pointer can be used in place of "main" to refer to the
  5706. ** main database file.
  5707. ** ^The third and fourth parameters to this routine
  5708. ** are passed directly through to the second and third parameters of
  5709. ** the xFileControl method. ^The return value of the xFileControl
  5710. ** method becomes the return value of this routine.
  5711. **
  5712. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  5713. ** a pointer to the underlying [sqlite3_file] object to be written into
  5714. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  5715. ** case is a short-circuit path which does not actually invoke the
  5716. ** underlying sqlite3_io_methods.xFileControl method.
  5717. **
  5718. ** ^If the second parameter (zDbName) does not match the name of any
  5719. ** open database file, then SQLITE_ERROR is returned. ^This error
  5720. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  5721. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  5722. ** also return SQLITE_ERROR. There is no way to distinguish between
  5723. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  5724. ** xFileControl method.
  5725. **
  5726. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  5727. */
  5728. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  5729. /*
  5730. ** CAPI3REF: Testing Interface
  5731. **
  5732. ** ^The sqlite3_test_control() interface is used to read out internal
  5733. ** state of SQLite and to inject faults into SQLite for testing
  5734. ** purposes. ^The first parameter is an operation code that determines
  5735. ** the number, meaning, and operation of all subsequent parameters.
  5736. **
  5737. ** This interface is not for use by applications. It exists solely
  5738. ** for verifying the correct operation of the SQLite library. Depending
  5739. ** on how the SQLite library is compiled, this interface might not exist.
  5740. **
  5741. ** The details of the operation codes, their meanings, the parameters
  5742. ** they take, and what they do are all subject to change without notice.
  5743. ** Unlike most of the SQLite API, this function is not guaranteed to
  5744. ** operate consistently from one release to the next.
  5745. */
  5746. SQLITE_API int sqlite3_test_control(int op, ...);
  5747. /*
  5748. ** CAPI3REF: Testing Interface Operation Codes
  5749. **
  5750. ** These constants are the valid operation code parameters used
  5751. ** as the first argument to [sqlite3_test_control()].
  5752. **
  5753. ** These parameters and their meanings are subject to change
  5754. ** without notice. These values are for testing purposes only.
  5755. ** Applications should not use any of these parameters or the
  5756. ** [sqlite3_test_control()] interface.
  5757. */
  5758. #define SQLITE_TESTCTRL_FIRST 5
  5759. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  5760. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  5761. #define SQLITE_TESTCTRL_PRNG_RESET 7
  5762. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  5763. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  5764. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  5765. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  5766. #define SQLITE_TESTCTRL_ASSERT 12
  5767. #define SQLITE_TESTCTRL_ALWAYS 13
  5768. #define SQLITE_TESTCTRL_RESERVE 14
  5769. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  5770. #define SQLITE_TESTCTRL_ISKEYWORD 16
  5771. #define SQLITE_TESTCTRL_PGHDRSZ 17
  5772. #define SQLITE_TESTCTRL_SCRATCHMALLOC 18
  5773. #define SQLITE_TESTCTRL_LAST 18
  5774. /*
  5775. ** CAPI3REF: SQLite Runtime Status
  5776. **
  5777. ** ^This interface is used to retrieve runtime status information
  5778. ** about the performance of SQLite, and optionally to reset various
  5779. ** highwater marks. ^The first argument is an integer code for
  5780. ** the specific parameter to measure. ^(Recognized integer codes
  5781. ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
  5782. ** ^The current value of the parameter is returned into *pCurrent.
  5783. ** ^The highest recorded value is returned in *pHighwater. ^If the
  5784. ** resetFlag is true, then the highest record value is reset after
  5785. ** *pHighwater is written. ^(Some parameters do not record the highest
  5786. ** value. For those parameters
  5787. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  5788. ** ^(Other parameters record only the highwater mark and not the current
  5789. ** value. For these latter parameters nothing is written into *pCurrent.)^
  5790. **
  5791. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  5792. ** non-zero [error code] on failure.
  5793. **
  5794. ** This routine is threadsafe but is not atomic. This routine can be
  5795. ** called while other threads are running the same or different SQLite
  5796. ** interfaces. However the values returned in *pCurrent and
  5797. ** *pHighwater reflect the status of SQLite at different points in time
  5798. ** and it is possible that another thread might change the parameter
  5799. ** in between the times when *pCurrent and *pHighwater are written.
  5800. **
  5801. ** See also: [sqlite3_db_status()]
  5802. */
  5803. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  5804. /*
  5805. ** CAPI3REF: Status Parameters
  5806. **
  5807. ** These integer constants designate various run-time status parameters
  5808. ** that can be returned by [sqlite3_status()].
  5809. **
  5810. ** <dl>
  5811. ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  5812. ** <dd>This parameter is the current amount of memory checked out
  5813. ** using [sqlite3_malloc()], either directly or indirectly. The
  5814. ** figure includes calls made to [sqlite3_malloc()] by the application
  5815. ** and internal memory usage by the SQLite library. Scratch memory
  5816. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  5817. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  5818. ** this parameter. The amount returned is the sum of the allocation
  5819. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  5820. **
  5821. ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  5822. ** <dd>This parameter records the largest memory allocation request
  5823. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  5824. ** internal equivalents). Only the value returned in the
  5825. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5826. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5827. **
  5828. ** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  5829. ** <dd>This parameter records the number of separate memory allocations
  5830. ** currently checked out.</dd>)^
  5831. **
  5832. ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  5833. ** <dd>This parameter returns the number of pages used out of the
  5834. ** [pagecache memory allocator] that was configured using
  5835. ** [SQLITE_CONFIG_PAGECACHE]. The
  5836. ** value returned is in pages, not in bytes.</dd>)^
  5837. **
  5838. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  5839. ** <dd>This parameter returns the number of bytes of page cache
  5840. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  5841. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  5842. ** returned value includes allocations that overflowed because they
  5843. ** where too large (they were larger than the "sz" parameter to
  5844. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  5845. ** no space was left in the page cache.</dd>)^
  5846. **
  5847. ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  5848. ** <dd>This parameter records the largest memory allocation request
  5849. ** handed to [pagecache memory allocator]. Only the value returned in the
  5850. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5851. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5852. **
  5853. ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  5854. ** <dd>This parameter returns the number of allocations used out of the
  5855. ** [scratch memory allocator] configured using
  5856. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  5857. ** in bytes. Since a single thread may only have one scratch allocation
  5858. ** outstanding at time, this parameter also reports the number of threads
  5859. ** using scratch memory at the same time.</dd>)^
  5860. **
  5861. ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  5862. ** <dd>This parameter returns the number of bytes of scratch memory
  5863. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  5864. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  5865. ** returned include overflows because the requested allocation was too
  5866. ** larger (that is, because the requested allocation was larger than the
  5867. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  5868. ** slots were available.
  5869. ** </dd>)^
  5870. **
  5871. ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  5872. ** <dd>This parameter records the largest memory allocation request
  5873. ** handed to [scratch memory allocator]. Only the value returned in the
  5874. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5875. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5876. **
  5877. ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  5878. ** <dd>This parameter records the deepest parser stack. It is only
  5879. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  5880. ** </dl>
  5881. **
  5882. ** New status parameters may be added from time to time.
  5883. */
  5884. #define SQLITE_STATUS_MEMORY_USED 0
  5885. #define SQLITE_STATUS_PAGECACHE_USED 1
  5886. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  5887. #define SQLITE_STATUS_SCRATCH_USED 3
  5888. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  5889. #define SQLITE_STATUS_MALLOC_SIZE 5
  5890. #define SQLITE_STATUS_PARSER_STACK 6
  5891. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  5892. #define SQLITE_STATUS_SCRATCH_SIZE 8
  5893. #define SQLITE_STATUS_MALLOC_COUNT 9
  5894. /*
  5895. ** CAPI3REF: Database Connection Status
  5896. **
  5897. ** ^This interface is used to retrieve runtime status information
  5898. ** about a single [database connection]. ^The first argument is the
  5899. ** database connection object to be interrogated. ^The second argument
  5900. ** is an integer constant, taken from the set of
  5901. ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
  5902. ** determines the parameter to interrogate. The set of
  5903. ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
  5904. ** to grow in future releases of SQLite.
  5905. **
  5906. ** ^The current value of the requested parameter is written into *pCur
  5907. ** and the highest instantaneous value is written into *pHiwtr. ^If
  5908. ** the resetFlg is true, then the highest instantaneous value is
  5909. ** reset back down to the current value.
  5910. **
  5911. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  5912. ** non-zero [error code] on failure.
  5913. **
  5914. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  5915. */
  5916. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  5917. /*
  5918. ** CAPI3REF: Status Parameters for database connections
  5919. **
  5920. ** These constants are the available integer "verbs" that can be passed as
  5921. ** the second argument to the [sqlite3_db_status()] interface.
  5922. **
  5923. ** New verbs may be added in future releases of SQLite. Existing verbs
  5924. ** might be discontinued. Applications should check the return code from
  5925. ** [sqlite3_db_status()] to make sure that the call worked.
  5926. ** The [sqlite3_db_status()] interface will return a non-zero error code
  5927. ** if a discontinued or unsupported verb is invoked.
  5928. **
  5929. ** <dl>
  5930. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  5931. ** <dd>This parameter returns the number of lookaside memory slots currently
  5932. ** checked out.</dd>)^
  5933. **
  5934. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  5935. ** <dd>This parameter returns the number malloc attempts that were
  5936. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  5937. ** the current value is always zero.)^
  5938. **
  5939. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  5940. ** <dd>This parameter returns the number malloc attempts that might have
  5941. ** been satisfied using lookaside memory but failed due to the amount of
  5942. ** memory requested being larger than the lookaside slot size.
  5943. ** Only the high-water value is meaningful;
  5944. ** the current value is always zero.)^
  5945. **
  5946. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  5947. ** <dd>This parameter returns the number malloc attempts that might have
  5948. ** been satisfied using lookaside memory but failed due to all lookaside
  5949. ** memory already being in use.
  5950. ** Only the high-water value is meaningful;
  5951. ** the current value is always zero.)^
  5952. **
  5953. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  5954. ** <dd>This parameter returns the approximate number of of bytes of heap
  5955. ** memory used by all pager caches associated with the database connection.)^
  5956. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  5957. **
  5958. ** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  5959. ** <dd>This parameter returns the approximate number of of bytes of heap
  5960. ** memory used to store the schema for all databases associated
  5961. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  5962. ** ^The full amount of memory used by the schemas is reported, even if the
  5963. ** schema memory is shared with other database connections due to
  5964. ** [shared cache mode] being enabled.
  5965. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  5966. **
  5967. ** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  5968. ** <dd>This parameter returns the approximate number of of bytes of heap
  5969. ** and lookaside memory used by all prepared statements associated with
  5970. ** the database connection.)^
  5971. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  5972. ** </dd>
  5973. ** </dl>
  5974. */
  5975. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  5976. #define SQLITE_DBSTATUS_CACHE_USED 1
  5977. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  5978. #define SQLITE_DBSTATUS_STMT_USED 3
  5979. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  5980. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  5981. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  5982. #define SQLITE_DBSTATUS_MAX 6 /* Largest defined DBSTATUS */
  5983. /*
  5984. ** CAPI3REF: Prepared Statement Status
  5985. **
  5986. ** ^(Each prepared statement maintains various
  5987. ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
  5988. ** of times it has performed specific operations.)^ These counters can
  5989. ** be used to monitor the performance characteristics of the prepared
  5990. ** statements. For example, if the number of table steps greatly exceeds
  5991. ** the number of table searches or result rows, that would tend to indicate
  5992. ** that the prepared statement is using a full table scan rather than
  5993. ** an index.
  5994. **
  5995. ** ^(This interface is used to retrieve and reset counter values from
  5996. ** a [prepared statement]. The first argument is the prepared statement
  5997. ** object to be interrogated. The second argument
  5998. ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
  5999. ** to be interrogated.)^
  6000. ** ^The current value of the requested counter is returned.
  6001. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6002. ** interface call returns.
  6003. **
  6004. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6005. */
  6006. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6007. /*
  6008. ** CAPI3REF: Status Parameters for prepared statements
  6009. **
  6010. ** These preprocessor macros define integer codes that name counter
  6011. ** values associated with the [sqlite3_stmt_status()] interface.
  6012. ** The meanings of the various counters are as follows:
  6013. **
  6014. ** <dl>
  6015. ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6016. ** <dd>^This is the number of times that SQLite has stepped forward in
  6017. ** a table as part of a full table scan. Large numbers for this counter
  6018. ** may indicate opportunities for performance improvement through
  6019. ** careful use of indices.</dd>
  6020. **
  6021. ** <dt>SQLITE_STMTSTATUS_SORT</dt>
  6022. ** <dd>^This is the number of sort operations that have occurred.
  6023. ** A non-zero value in this counter may indicate an opportunity to
  6024. ** improvement performance through careful use of indices.</dd>
  6025. **
  6026. ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6027. ** <dd>^This is the number of rows inserted into transient indices that
  6028. ** were created automatically in order to help joins run faster.
  6029. ** A non-zero value in this counter may indicate an opportunity to
  6030. ** improvement performance by adding permanent indices that do not
  6031. ** need to be reinitialized each time the statement is run.</dd>
  6032. **
  6033. ** </dl>
  6034. */
  6035. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6036. #define SQLITE_STMTSTATUS_SORT 2
  6037. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6038. /*
  6039. ** CAPI3REF: Custom Page Cache Object
  6040. **
  6041. ** The sqlite3_pcache type is opaque. It is implemented by
  6042. ** the pluggable module. The SQLite core has no knowledge of
  6043. ** its size or internal structure and never deals with the
  6044. ** sqlite3_pcache object except by holding and passing pointers
  6045. ** to the object.
  6046. **
  6047. ** See [sqlite3_pcache_methods] for additional information.
  6048. */
  6049. typedef struct sqlite3_pcache sqlite3_pcache;
  6050. /*
  6051. ** CAPI3REF: Application Defined Page Cache.
  6052. ** KEYWORDS: {page cache}
  6053. **
  6054. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
  6055. ** register an alternative page cache implementation by passing in an
  6056. ** instance of the sqlite3_pcache_methods structure.)^
  6057. ** In many applications, most of the heap memory allocated by
  6058. ** SQLite is used for the page cache.
  6059. ** By implementing a
  6060. ** custom page cache using this API, an application can better control
  6061. ** the amount of memory consumed by SQLite, the way in which
  6062. ** that memory is allocated and released, and the policies used to
  6063. ** determine exactly which parts of a database file are cached and for
  6064. ** how long.
  6065. **
  6066. ** The alternative page cache mechanism is an
  6067. ** extreme measure that is only needed by the most demanding applications.
  6068. ** The built-in page cache is recommended for most uses.
  6069. **
  6070. ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
  6071. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6072. ** the application may discard the parameter after the call to
  6073. ** [sqlite3_config()] returns.)^
  6074. **
  6075. ** ^(The xInit() method is called once for each effective
  6076. ** call to [sqlite3_initialize()])^
  6077. ** (usually only once during the lifetime of the process). ^(The xInit()
  6078. ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
  6079. ** The intent of the xInit() method is to set up global data structures
  6080. ** required by the custom page cache implementation.
  6081. ** ^(If the xInit() method is NULL, then the
  6082. ** built-in default page cache is used instead of the application defined
  6083. ** page cache.)^
  6084. **
  6085. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6086. ** It can be used to clean up
  6087. ** any outstanding resources before process shutdown, if required.
  6088. ** ^The xShutdown() method may be NULL.
  6089. **
  6090. ** ^SQLite automatically serializes calls to the xInit method,
  6091. ** so the xInit method need not be threadsafe. ^The
  6092. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6093. ** not need to be threadsafe either. All other methods must be threadsafe
  6094. ** in multithreaded applications.
  6095. **
  6096. ** ^SQLite will never invoke xInit() more than once without an intervening
  6097. ** call to xShutdown().
  6098. **
  6099. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6100. ** SQLite will typically create one cache instance for each open database file,
  6101. ** though this is not guaranteed. ^The
  6102. ** first parameter, szPage, is the size in bytes of the pages that must
  6103. ** be allocated by the cache. ^szPage will not be a power of two. ^szPage
  6104. ** will the page size of the database file that is to be cached plus an
  6105. ** increment (here called "R") of less than 250. SQLite will use the
  6106. ** extra R bytes on each page to store metadata about the underlying
  6107. ** database page on disk. The value of R depends
  6108. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6109. ** ^(R is constant for a particular build of SQLite. Except, there are two
  6110. ** distinct values of R when SQLite is compiled with the proprietary
  6111. ** ZIPVFS extension.)^ ^The second argument to
  6112. ** xCreate(), bPurgeable, is true if the cache being created will
  6113. ** be used to cache database pages of a file stored on disk, or
  6114. ** false if it is used for an in-memory database. The cache implementation
  6115. ** does not have to do anything special based with the value of bPurgeable;
  6116. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6117. ** never invoke xUnpin() except to deliberately delete a page.
  6118. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6119. ** false will always have the "discard" flag set to true.
  6120. ** ^Hence, a cache created with bPurgeable false will
  6121. ** never contain any unpinned pages.
  6122. **
  6123. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6124. ** suggested maximum cache-size (number of pages stored by) the cache
  6125. ** instance passed as the first argument. This is the value configured using
  6126. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6127. ** parameter, the implementation is not required to do anything with this
  6128. ** value; it is advisory only.
  6129. **
  6130. ** The xPagecount() method must return the number of pages currently
  6131. ** stored in the cache, both pinned and unpinned.
  6132. **
  6133. ** The xFetch() method locates a page in the cache and returns a pointer to
  6134. ** the page, or a NULL pointer.
  6135. ** A "page", in this context, means a buffer of szPage bytes aligned at an
  6136. ** 8-byte boundary. The page to be fetched is determined by the key. ^The
  6137. ** mimimum key value is 1. After it has been retrieved using xFetch, the page
  6138. ** is considered to be "pinned".
  6139. **
  6140. ** If the requested page is already in the page cache, then the page cache
  6141. ** implementation must return a pointer to the page buffer with its content
  6142. ** intact. If the requested page is not already in the cache, then the
  6143. ** cache implementation should use the value of the createFlag
  6144. ** parameter to help it determined what action to take:
  6145. **
  6146. ** <table border=1 width=85% align=center>
  6147. ** <tr><th> createFlag <th> Behaviour when page is not already in cache
  6148. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6149. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6150. ** Otherwise return NULL.
  6151. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6152. ** NULL if allocating a new page is effectively impossible.
  6153. ** </table>
  6154. **
  6155. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6156. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6157. ** failed.)^ In between the to xFetch() calls, SQLite may
  6158. ** attempt to unpin one or more cache pages by spilling the content of
  6159. ** pinned pages to disk and synching the operating system disk cache.
  6160. **
  6161. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6162. ** as its second argument. If the third parameter, discard, is non-zero,
  6163. ** then the page must be evicted from the cache.
  6164. ** ^If the discard parameter is
  6165. ** zero, then the page may be discarded or retained at the discretion of
  6166. ** page cache implementation. ^The page cache implementation
  6167. ** may choose to evict unpinned pages at any time.
  6168. **
  6169. ** The cache must not perform any reference counting. A single
  6170. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6171. ** to xFetch().
  6172. **
  6173. ** The xRekey() method is used to change the key value associated with the
  6174. ** page passed as the second argument. If the cache
  6175. ** previously contains an entry associated with newKey, it must be
  6176. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6177. ** to be pinned.
  6178. **
  6179. ** When SQLite calls the xTruncate() method, the cache must discard all
  6180. ** existing cache entries with page numbers (keys) greater than or equal
  6181. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6182. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6183. ** they can be safely discarded.
  6184. **
  6185. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6186. ** All resources associated with the specified cache should be freed. ^After
  6187. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6188. ** handle invalid, and will not use it with any other sqlite3_pcache_methods
  6189. ** functions.
  6190. */
  6191. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6192. struct sqlite3_pcache_methods {
  6193. void *pArg;
  6194. int (*xInit)(void*);
  6195. void (*xShutdown)(void*);
  6196. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6197. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6198. int (*xPagecount)(sqlite3_pcache*);
  6199. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6200. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6201. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6202. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6203. void (*xDestroy)(sqlite3_pcache*);
  6204. };
  6205. /*
  6206. ** CAPI3REF: Online Backup Object
  6207. **
  6208. ** The sqlite3_backup object records state information about an ongoing
  6209. ** online backup operation. ^The sqlite3_backup object is created by
  6210. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6211. ** [sqlite3_backup_finish()].
  6212. **
  6213. ** See Also: [Using the SQLite Online Backup API]
  6214. */
  6215. typedef struct sqlite3_backup sqlite3_backup;
  6216. /*
  6217. ** CAPI3REF: Online Backup API.
  6218. **
  6219. ** The backup API copies the content of one database into another.
  6220. ** It is useful either for creating backups of databases or
  6221. ** for copying in-memory databases to or from persistent files.
  6222. **
  6223. ** See Also: [Using the SQLite Online Backup API]
  6224. **
  6225. ** ^SQLite holds a write transaction open on the destination database file
  6226. ** for the duration of the backup operation.
  6227. ** ^The source database is read-locked only while it is being read;
  6228. ** it is not locked continuously for the entire backup operation.
  6229. ** ^Thus, the backup may be performed on a live source database without
  6230. ** preventing other database connections from
  6231. ** reading or writing to the source database while the backup is underway.
  6232. **
  6233. ** ^(To perform a backup operation:
  6234. ** <ol>
  6235. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6236. ** backup,
  6237. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6238. ** the data between the two databases, and finally
  6239. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6240. ** associated with the backup operation.
  6241. ** </ol>)^
  6242. ** There should be exactly one call to sqlite3_backup_finish() for each
  6243. ** successful call to sqlite3_backup_init().
  6244. **
  6245. ** <b>sqlite3_backup_init()</b>
  6246. **
  6247. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6248. ** [database connection] associated with the destination database
  6249. ** and the database name, respectively.
  6250. ** ^The database name is "main" for the main database, "temp" for the
  6251. ** temporary database, or the name specified after the AS keyword in
  6252. ** an [ATTACH] statement for an attached database.
  6253. ** ^The S and M arguments passed to
  6254. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6255. ** and database name of the source database, respectively.
  6256. ** ^The source and destination [database connections] (parameters S and D)
  6257. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6258. ** an error.
  6259. **
  6260. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6261. ** returned and an error code and error message are stored in the
  6262. ** destination [database connection] D.
  6263. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6264. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6265. ** [sqlite3_errmsg16()] functions.
  6266. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6267. ** [sqlite3_backup] object.
  6268. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6269. ** sqlite3_backup_finish() functions to perform the specified backup
  6270. ** operation.
  6271. **
  6272. ** <b>sqlite3_backup_step()</b>
  6273. **
  6274. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6275. ** the source and destination databases specified by [sqlite3_backup] object B.
  6276. ** ^If N is negative, all remaining source pages are copied.
  6277. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6278. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6279. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6280. ** from source to destination, then it returns [SQLITE_DONE].
  6281. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6282. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6283. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6284. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6285. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6286. **
  6287. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6288. ** <ol>
  6289. ** <li> the destination database was opened read-only, or
  6290. ** <li> the destination database is using write-ahead-log journaling
  6291. ** and the destination and source page sizes differ, or
  6292. ** <li> the destination database is an in-memory database and the
  6293. ** destination and source page sizes differ.
  6294. ** </ol>)^
  6295. **
  6296. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6297. ** the [sqlite3_busy_handler | busy-handler function]
  6298. ** is invoked (if one is specified). ^If the
  6299. ** busy-handler returns non-zero before the lock is available, then
  6300. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6301. ** sqlite3_backup_step() can be retried later. ^If the source
  6302. ** [database connection]
  6303. ** is being used to write to the source database when sqlite3_backup_step()
  6304. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6305. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6306. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6307. ** [SQLITE_READONLY] is returned, then
  6308. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6309. ** errors are considered fatal.)^ The application must accept
  6310. ** that the backup operation has failed and pass the backup operation handle
  6311. ** to the sqlite3_backup_finish() to release associated resources.
  6312. **
  6313. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6314. ** on the destination file. ^The exclusive lock is not released until either
  6315. ** sqlite3_backup_finish() is called or the backup operation is complete
  6316. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6317. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6318. ** lasts for the duration of the sqlite3_backup_step() call.
  6319. ** ^Because the source database is not locked between calls to
  6320. ** sqlite3_backup_step(), the source database may be modified mid-way
  6321. ** through the backup process. ^If the source database is modified by an
  6322. ** external process or via a database connection other than the one being
  6323. ** used by the backup operation, then the backup will be automatically
  6324. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6325. ** database is modified by the using the same database connection as is used
  6326. ** by the backup operation, then the backup database is automatically
  6327. ** updated at the same time.
  6328. **
  6329. ** <b>sqlite3_backup_finish()</b>
  6330. **
  6331. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6332. ** application wishes to abandon the backup operation, the application
  6333. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6334. ** ^The sqlite3_backup_finish() interfaces releases all
  6335. ** resources associated with the [sqlite3_backup] object.
  6336. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6337. ** active write-transaction on the destination database is rolled back.
  6338. ** The [sqlite3_backup] object is invalid
  6339. ** and may not be used following a call to sqlite3_backup_finish().
  6340. **
  6341. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6342. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6343. ** sqlite3_backup_step() completed.
  6344. ** ^If an out-of-memory condition or IO error occurred during any prior
  6345. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6346. ** sqlite3_backup_finish() returns the corresponding [error code].
  6347. **
  6348. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6349. ** is not a permanent error and does not affect the return value of
  6350. ** sqlite3_backup_finish().
  6351. **
  6352. ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
  6353. **
  6354. ** ^Each call to sqlite3_backup_step() sets two values inside
  6355. ** the [sqlite3_backup] object: the number of pages still to be backed
  6356. ** up and the total number of pages in the source database file.
  6357. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6358. ** retrieve these two values, respectively.
  6359. **
  6360. ** ^The values returned by these functions are only updated by
  6361. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6362. ** operation, then the values are not updated to account for any extra
  6363. ** pages that need to be updated or the size of the source database file
  6364. ** changing.
  6365. **
  6366. ** <b>Concurrent Usage of Database Handles</b>
  6367. **
  6368. ** ^The source [database connection] may be used by the application for other
  6369. ** purposes while a backup operation is underway or being initialized.
  6370. ** ^If SQLite is compiled and configured to support threadsafe database
  6371. ** connections, then the source database connection may be used concurrently
  6372. ** from within other threads.
  6373. **
  6374. ** However, the application must guarantee that the destination
  6375. ** [database connection] is not passed to any other API (by any thread) after
  6376. ** sqlite3_backup_init() is called and before the corresponding call to
  6377. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6378. ** if the application incorrectly accesses the destination [database connection]
  6379. ** and so no error code is reported, but the operations may malfunction
  6380. ** nevertheless. Use of the destination database connection while a
  6381. ** backup is in progress might also also cause a mutex deadlock.
  6382. **
  6383. ** If running in [shared cache mode], the application must
  6384. ** guarantee that the shared cache used by the destination database
  6385. ** is not accessed while the backup is running. In practice this means
  6386. ** that the application must guarantee that the disk file being
  6387. ** backed up to is not accessed by any connection within the process,
  6388. ** not just the specific connection that was passed to sqlite3_backup_init().
  6389. **
  6390. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  6391. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  6392. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  6393. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  6394. ** same time as another thread is invoking sqlite3_backup_step() it is
  6395. ** possible that they return invalid values.
  6396. */
  6397. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  6398. sqlite3 *pDest, /* Destination database handle */
  6399. const char *zDestName, /* Destination database name */
  6400. sqlite3 *pSource, /* Source database handle */
  6401. const char *zSourceName /* Source database name */
  6402. );
  6403. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  6404. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  6405. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  6406. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  6407. /*
  6408. ** CAPI3REF: Unlock Notification
  6409. **
  6410. ** ^When running in shared-cache mode, a database operation may fail with
  6411. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  6412. ** individual tables within the shared-cache cannot be obtained. See
  6413. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  6414. ** ^This API may be used to register a callback that SQLite will invoke
  6415. ** when the connection currently holding the required lock relinquishes it.
  6416. ** ^This API is only available if the library was compiled with the
  6417. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  6418. **
  6419. ** See Also: [Using the SQLite Unlock Notification Feature].
  6420. **
  6421. ** ^Shared-cache locks are released when a database connection concludes
  6422. ** its current transaction, either by committing it or rolling it back.
  6423. **
  6424. ** ^When a connection (known as the blocked connection) fails to obtain a
  6425. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  6426. ** identity of the database connection (the blocking connection) that
  6427. ** has locked the required resource is stored internally. ^After an
  6428. ** application receives an SQLITE_LOCKED error, it may call the
  6429. ** sqlite3_unlock_notify() method with the blocked connection handle as
  6430. ** the first argument to register for a callback that will be invoked
  6431. ** when the blocking connections current transaction is concluded. ^The
  6432. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  6433. ** call that concludes the blocking connections transaction.
  6434. **
  6435. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  6436. ** there is a chance that the blocking connection will have already
  6437. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  6438. ** If this happens, then the specified callback is invoked immediately,
  6439. ** from within the call to sqlite3_unlock_notify().)^
  6440. **
  6441. ** ^If the blocked connection is attempting to obtain a write-lock on a
  6442. ** shared-cache table, and more than one other connection currently holds
  6443. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  6444. ** the other connections to use as the blocking connection.
  6445. **
  6446. ** ^(There may be at most one unlock-notify callback registered by a
  6447. ** blocked connection. If sqlite3_unlock_notify() is called when the
  6448. ** blocked connection already has a registered unlock-notify callback,
  6449. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  6450. ** called with a NULL pointer as its second argument, then any existing
  6451. ** unlock-notify callback is canceled. ^The blocked connections
  6452. ** unlock-notify callback may also be canceled by closing the blocked
  6453. ** connection using [sqlite3_close()].
  6454. **
  6455. ** The unlock-notify callback is not reentrant. If an application invokes
  6456. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  6457. ** crash or deadlock may be the result.
  6458. **
  6459. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  6460. ** returns SQLITE_OK.
  6461. **
  6462. ** <b>Callback Invocation Details</b>
  6463. **
  6464. ** When an unlock-notify callback is registered, the application provides a
  6465. ** single void* pointer that is passed to the callback when it is invoked.
  6466. ** However, the signature of the callback function allows SQLite to pass
  6467. ** it an array of void* context pointers. The first argument passed to
  6468. ** an unlock-notify callback is a pointer to an array of void* pointers,
  6469. ** and the second is the number of entries in the array.
  6470. **
  6471. ** When a blocking connections transaction is concluded, there may be
  6472. ** more than one blocked connection that has registered for an unlock-notify
  6473. ** callback. ^If two or more such blocked connections have specified the
  6474. ** same callback function, then instead of invoking the callback function
  6475. ** multiple times, it is invoked once with the set of void* context pointers
  6476. ** specified by the blocked connections bundled together into an array.
  6477. ** This gives the application an opportunity to prioritize any actions
  6478. ** related to the set of unblocked database connections.
  6479. **
  6480. ** <b>Deadlock Detection</b>
  6481. **
  6482. ** Assuming that after registering for an unlock-notify callback a
  6483. ** database waits for the callback to be issued before taking any further
  6484. ** action (a reasonable assumption), then using this API may cause the
  6485. ** application to deadlock. For example, if connection X is waiting for
  6486. ** connection Y's transaction to be concluded, and similarly connection
  6487. ** Y is waiting on connection X's transaction, then neither connection
  6488. ** will proceed and the system may remain deadlocked indefinitely.
  6489. **
  6490. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  6491. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  6492. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  6493. ** unlock-notify callback is registered. The system is said to be in
  6494. ** a deadlocked state if connection A has registered for an unlock-notify
  6495. ** callback on the conclusion of connection B's transaction, and connection
  6496. ** B has itself registered for an unlock-notify callback when connection
  6497. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  6498. ** the system is also considered to be deadlocked if connection B has
  6499. ** registered for an unlock-notify callback on the conclusion of connection
  6500. ** C's transaction, where connection C is waiting on connection A. ^Any
  6501. ** number of levels of indirection are allowed.
  6502. **
  6503. ** <b>The "DROP TABLE" Exception</b>
  6504. **
  6505. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  6506. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  6507. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  6508. ** SQLite checks if there are any currently executing SELECT statements
  6509. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  6510. ** returned. In this case there is no "blocking connection", so invoking
  6511. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  6512. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  6513. ** or "DROP INDEX" query, an infinite loop might be the result.
  6514. **
  6515. ** One way around this problem is to check the extended error code returned
  6516. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  6517. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  6518. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  6519. ** SQLITE_LOCKED.)^
  6520. */
  6521. SQLITE_API int sqlite3_unlock_notify(
  6522. sqlite3 *pBlocked, /* Waiting connection */
  6523. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  6524. void *pNotifyArg /* Argument to pass to xNotify */
  6525. );
  6526. /*
  6527. ** CAPI3REF: String Comparison
  6528. **
  6529. ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
  6530. ** compare the contents of two buffers containing UTF-8 strings in a
  6531. ** case-independent fashion, using the same definition of case independence
  6532. ** that SQLite uses internally when comparing identifiers.
  6533. */
  6534. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  6535. /*
  6536. ** CAPI3REF: Error Logging Interface
  6537. **
  6538. ** ^The [sqlite3_log()] interface writes a message into the error log
  6539. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  6540. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  6541. ** used with [sqlite3_snprintf()] to generate the final output string.
  6542. **
  6543. ** The sqlite3_log() interface is intended for use by extensions such as
  6544. ** virtual tables, collating functions, and SQL functions. While there is
  6545. ** nothing to prevent an application from calling sqlite3_log(), doing so
  6546. ** is considered bad form.
  6547. **
  6548. ** The zFormat string must not be NULL.
  6549. **
  6550. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  6551. ** will not use dynamically allocated memory. The log message is stored in
  6552. ** a fixed-length buffer on the stack. If the log message is longer than
  6553. ** a few hundred characters, it will be truncated to the length of the
  6554. ** buffer.
  6555. */
  6556. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  6557. /*
  6558. ** CAPI3REF: Write-Ahead Log Commit Hook
  6559. **
  6560. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  6561. ** will be invoked each time a database connection commits data to a
  6562. ** [write-ahead log] (i.e. whenever a transaction is committed in
  6563. ** [journal_mode | journal_mode=WAL mode]).
  6564. **
  6565. ** ^The callback is invoked by SQLite after the commit has taken place and
  6566. ** the associated write-lock on the database released, so the implementation
  6567. ** may read, write or [checkpoint] the database as required.
  6568. **
  6569. ** ^The first parameter passed to the callback function when it is invoked
  6570. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  6571. ** registering the callback. ^The second is a copy of the database handle.
  6572. ** ^The third parameter is the name of the database that was written to -
  6573. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  6574. ** is the number of pages currently in the write-ahead log file,
  6575. ** including those that were just committed.
  6576. **
  6577. ** The callback function should normally return [SQLITE_OK]. ^If an error
  6578. ** code is returned, that error will propagate back up through the
  6579. ** SQLite code base to cause the statement that provoked the callback
  6580. ** to report an error, though the commit will have still occurred. If the
  6581. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  6582. ** that does not correspond to any valid SQLite error code, the results
  6583. ** are undefined.
  6584. **
  6585. ** A single database handle may have at most a single write-ahead log callback
  6586. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  6587. ** previously registered write-ahead log callback. ^Note that the
  6588. ** [sqlite3_wal_autocheckpoint()] interface and the
  6589. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  6590. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  6591. */
  6592. SQLITE_API void *sqlite3_wal_hook(
  6593. sqlite3*,
  6594. int(*)(void *,sqlite3*,const char*,int),
  6595. void*
  6596. );
  6597. /*
  6598. ** CAPI3REF: Configure an auto-checkpoint
  6599. **
  6600. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  6601. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  6602. ** to automatically [checkpoint]
  6603. ** after committing a transaction if there are N or
  6604. ** more frames in the [write-ahead log] file. ^Passing zero or
  6605. ** a negative value as the nFrame parameter disables automatic
  6606. ** checkpoints entirely.
  6607. **
  6608. ** ^The callback registered by this function replaces any existing callback
  6609. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  6610. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  6611. ** configured by this function.
  6612. **
  6613. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  6614. ** from SQL.
  6615. **
  6616. ** ^Every new [database connection] defaults to having the auto-checkpoint
  6617. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  6618. ** pages. The use of this interface
  6619. ** is only necessary if the default setting is found to be suboptimal
  6620. ** for a particular application.
  6621. */
  6622. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  6623. /*
  6624. ** CAPI3REF: Checkpoint a database
  6625. **
  6626. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  6627. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  6628. ** empty string, then a checkpoint is run on all databases of
  6629. ** connection D. ^If the database connection D is not in
  6630. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  6631. **
  6632. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  6633. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  6634. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  6635. ** run whenever the WAL reaches a certain size threshold.
  6636. **
  6637. ** See also: [sqlite3_wal_checkpoint_v2()]
  6638. */
  6639. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  6640. /*
  6641. ** CAPI3REF: Checkpoint a database
  6642. **
  6643. ** Run a checkpoint operation on WAL database zDb attached to database
  6644. ** handle db. The specific operation is determined by the value of the
  6645. ** eMode parameter:
  6646. **
  6647. ** <dl>
  6648. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  6649. ** Checkpoint as many frames as possible without waiting for any database
  6650. ** readers or writers to finish. Sync the db file if all frames in the log
  6651. ** are checkpointed. This mode is the same as calling
  6652. ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  6653. **
  6654. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  6655. ** This mode blocks (calls the busy-handler callback) until there is no
  6656. ** database writer and all readers are reading from the most recent database
  6657. ** snapshot. It then checkpoints all frames in the log file and syncs the
  6658. ** database file. This call blocks database writers while it is running,
  6659. ** but not database readers.
  6660. **
  6661. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  6662. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  6663. ** checkpointing the log file it blocks (calls the busy-handler callback)
  6664. ** until all readers are reading from the database file only. This ensures
  6665. ** that the next client to write to the database file restarts the log file
  6666. ** from the beginning. This call blocks database writers while it is running,
  6667. ** but not database readers.
  6668. ** </dl>
  6669. **
  6670. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  6671. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  6672. ** the total number of checkpointed frames (including any that were already
  6673. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  6674. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  6675. ** If no values are available because of an error, they are both set to -1
  6676. ** before returning to communicate this to the caller.
  6677. **
  6678. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  6679. ** any other process is running a checkpoint operation at the same time, the
  6680. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  6681. ** busy-handler configured, it will not be invoked in this case.
  6682. **
  6683. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  6684. ** "writer" lock on the database file. If the writer lock cannot be obtained
  6685. ** immediately, and a busy-handler is configured, it is invoked and the writer
  6686. ** lock retried until either the busy-handler returns 0 or the lock is
  6687. ** successfully obtained. The busy-handler is also invoked while waiting for
  6688. ** database readers as described above. If the busy-handler returns 0 before
  6689. ** the writer lock is obtained or while waiting for database readers, the
  6690. ** checkpoint operation proceeds from that point in the same way as
  6691. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  6692. ** without blocking any further. SQLITE_BUSY is returned in this case.
  6693. **
  6694. ** If parameter zDb is NULL or points to a zero length string, then the
  6695. ** specified operation is attempted on all WAL databases. In this case the
  6696. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  6697. ** an SQLITE_BUSY error is encountered when processing one or more of the
  6698. ** attached WAL databases, the operation is still attempted on any remaining
  6699. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  6700. ** error occurs while processing an attached database, processing is abandoned
  6701. ** and the error code returned to the caller immediately. If no error
  6702. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  6703. ** databases, SQLITE_OK is returned.
  6704. **
  6705. ** If database zDb is the name of an attached database that is not in WAL
  6706. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  6707. ** zDb is not NULL (or a zero length string) and is not the name of any
  6708. ** attached database, SQLITE_ERROR is returned to the caller.
  6709. */
  6710. SQLITE_API int sqlite3_wal_checkpoint_v2(
  6711. sqlite3 *db, /* Database handle */
  6712. const char *zDb, /* Name of attached database (or NULL) */
  6713. int eMode, /* SQLITE_CHECKPOINT_* value */
  6714. int *pnLog, /* OUT: Size of WAL log in frames */
  6715. int *pnCkpt /* OUT: Total number of frames checkpointed */
  6716. );
  6717. /*
  6718. ** CAPI3REF: Checkpoint operation parameters
  6719. **
  6720. ** These constants can be used as the 3rd parameter to
  6721. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  6722. ** documentation for additional information about the meaning and use of
  6723. ** each of these values.
  6724. */
  6725. #define SQLITE_CHECKPOINT_PASSIVE 0
  6726. #define SQLITE_CHECKPOINT_FULL 1
  6727. #define SQLITE_CHECKPOINT_RESTART 2
  6728. /*
  6729. ** Undo the hack that converts floating point types to integer for
  6730. ** builds on processors without floating point support.
  6731. */
  6732. #ifdef SQLITE_OMIT_FLOATING_POINT
  6733. # undef double
  6734. #endif
  6735. #if 0
  6736. } /* End of the 'extern "C"' block */
  6737. #endif
  6738. #endif
  6739. /*
  6740. ** 2010 August 30
  6741. **
  6742. ** The author disclaims copyright to this source code. In place of
  6743. ** a legal notice, here is a blessing:
  6744. **
  6745. ** May you do good and not evil.
  6746. ** May you find forgiveness for yourself and forgive others.
  6747. ** May you share freely, never taking more than you give.
  6748. **
  6749. *************************************************************************
  6750. */
  6751. #ifndef _SQLITE3RTREE_H_
  6752. #define _SQLITE3RTREE_H_
  6753. #if 0
  6754. extern "C" {
  6755. #endif
  6756. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  6757. /*
  6758. ** Register a geometry callback named zGeom that can be used as part of an
  6759. ** R-Tree geometry query as follows:
  6760. **
  6761. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  6762. */
  6763. SQLITE_API int sqlite3_rtree_geometry_callback(
  6764. sqlite3 *db,
  6765. const char *zGeom,
  6766. int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
  6767. void *pContext
  6768. );
  6769. /*
  6770. ** A pointer to a structure of the following type is passed as the first
  6771. ** argument to callbacks registered using rtree_geometry_callback().
  6772. */
  6773. struct sqlite3_rtree_geometry {
  6774. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  6775. int nParam; /* Size of array aParam[] */
  6776. double *aParam; /* Parameters passed to SQL geom function */
  6777. void *pUser; /* Callback implementation user data */
  6778. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  6779. };
  6780. #if 0
  6781. } /* end of the 'extern "C"' block */
  6782. #endif
  6783. #endif /* ifndef _SQLITE3RTREE_H_ */
  6784. /************** End of sqlite3.h *********************************************/
  6785. /************** Continuing where we left off in sqliteInt.h ******************/
  6786. /************** Include hash.h in the middle of sqliteInt.h ******************/
  6787. /************** Begin file hash.h ********************************************/
  6788. /*
  6789. ** 2001 September 22
  6790. **
  6791. ** The author disclaims copyright to this source code. In place of
  6792. ** a legal notice, here is a blessing:
  6793. **
  6794. ** May you do good and not evil.
  6795. ** May you find forgiveness for yourself and forgive others.
  6796. ** May you share freely, never taking more than you give.
  6797. **
  6798. *************************************************************************
  6799. ** This is the header file for the generic hash-table implemenation
  6800. ** used in SQLite.
  6801. */
  6802. #ifndef _SQLITE_HASH_H_
  6803. #define _SQLITE_HASH_H_
  6804. /* Forward declarations of structures. */
  6805. typedef struct Hash Hash;
  6806. typedef struct HashElem HashElem;
  6807. /* A complete hash table is an instance of the following structure.
  6808. ** The internals of this structure are intended to be opaque -- client
  6809. ** code should not attempt to access or modify the fields of this structure
  6810. ** directly. Change this structure only by using the routines below.
  6811. ** However, some of the "procedures" and "functions" for modifying and
  6812. ** accessing this structure are really macros, so we can't really make
  6813. ** this structure opaque.
  6814. **
  6815. ** All elements of the hash table are on a single doubly-linked list.
  6816. ** Hash.first points to the head of this list.
  6817. **
  6818. ** There are Hash.htsize buckets. Each bucket points to a spot in
  6819. ** the global doubly-linked list. The contents of the bucket are the
  6820. ** element pointed to plus the next _ht.count-1 elements in the list.
  6821. **
  6822. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  6823. ** by a linear search of the global list. For small tables, the
  6824. ** Hash.ht table is never allocated because if there are few elements
  6825. ** in the table, it is faster to do a linear search than to manage
  6826. ** the hash table.
  6827. */
  6828. struct Hash {
  6829. unsigned int htsize; /* Number of buckets in the hash table */
  6830. unsigned int count; /* Number of entries in this table */
  6831. HashElem *first; /* The first element of the array */
  6832. struct _ht { /* the hash table */
  6833. int count; /* Number of entries with this hash */
  6834. HashElem *chain; /* Pointer to first entry with this hash */
  6835. } *ht;
  6836. };
  6837. /* Each element in the hash table is an instance of the following
  6838. ** structure. All elements are stored on a single doubly-linked list.
  6839. **
  6840. ** Again, this structure is intended to be opaque, but it can't really
  6841. ** be opaque because it is used by macros.
  6842. */
  6843. struct HashElem {
  6844. HashElem *next, *prev; /* Next and previous elements in the table */
  6845. void *data; /* Data associated with this element */
  6846. const char *pKey; int nKey; /* Key associated with this element */
  6847. };
  6848. /*
  6849. ** Access routines. To delete, insert a NULL pointer.
  6850. */
  6851. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  6852. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  6853. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  6854. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  6855. /*
  6856. ** Macros for looping over all elements of a hash table. The idiom is
  6857. ** like this:
  6858. **
  6859. ** Hash h;
  6860. ** HashElem *p;
  6861. ** ...
  6862. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  6863. ** SomeStructure *pData = sqliteHashData(p);
  6864. ** // do something with pData
  6865. ** }
  6866. */
  6867. #define sqliteHashFirst(H) ((H)->first)
  6868. #define sqliteHashNext(E) ((E)->next)
  6869. #define sqliteHashData(E) ((E)->data)
  6870. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  6871. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  6872. /*
  6873. ** Number of entries in a hash table
  6874. */
  6875. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  6876. #endif /* _SQLITE_HASH_H_ */
  6877. /************** End of hash.h ************************************************/
  6878. /************** Continuing where we left off in sqliteInt.h ******************/
  6879. /************** Include parse.h in the middle of sqliteInt.h *****************/
  6880. /************** Begin file parse.h *******************************************/
  6881. #define TK_SEMI 1
  6882. #define TK_EXPLAIN 2
  6883. #define TK_QUERY 3
  6884. #define TK_PLAN 4
  6885. #define TK_BEGIN 5
  6886. #define TK_TRANSACTION 6
  6887. #define TK_DEFERRED 7
  6888. #define TK_IMMEDIATE 8
  6889. #define TK_EXCLUSIVE 9
  6890. #define TK_COMMIT 10
  6891. #define TK_END 11
  6892. #define TK_ROLLBACK 12
  6893. #define TK_SAVEPOINT 13
  6894. #define TK_RELEASE 14
  6895. #define TK_TO 15
  6896. #define TK_TABLE 16
  6897. #define TK_CREATE 17
  6898. #define TK_IF 18
  6899. #define TK_NOT 19
  6900. #define TK_EXISTS 20
  6901. #define TK_TEMP 21
  6902. #define TK_LP 22
  6903. #define TK_RP 23
  6904. #define TK_AS 24
  6905. #define TK_COMMA 25
  6906. #define TK_ID 26
  6907. #define TK_INDEXED 27
  6908. #define TK_ABORT 28
  6909. #define TK_ACTION 29
  6910. #define TK_AFTER 30
  6911. #define TK_ANALYZE 31
  6912. #define TK_ASC 32
  6913. #define TK_ATTACH 33
  6914. #define TK_BEFORE 34
  6915. #define TK_BY 35
  6916. #define TK_CASCADE 36
  6917. #define TK_CAST 37
  6918. #define TK_COLUMNKW 38
  6919. #define TK_CONFLICT 39
  6920. #define TK_DATABASE 40
  6921. #define TK_DESC 41
  6922. #define TK_DETACH 42
  6923. #define TK_EACH 43
  6924. #define TK_FAIL 44
  6925. #define TK_FOR 45
  6926. #define TK_IGNORE 46
  6927. #define TK_INITIALLY 47
  6928. #define TK_INSTEAD 48
  6929. #define TK_LIKE_KW 49
  6930. #define TK_MATCH 50
  6931. #define TK_NO 51
  6932. #define TK_KEY 52
  6933. #define TK_OF 53
  6934. #define TK_OFFSET 54
  6935. #define TK_PRAGMA 55
  6936. #define TK_RAISE 56
  6937. #define TK_REPLACE 57
  6938. #define TK_RESTRICT 58
  6939. #define TK_ROW 59
  6940. #define TK_TRIGGER 60
  6941. #define TK_VACUUM 61
  6942. #define TK_VIEW 62
  6943. #define TK_VIRTUAL 63
  6944. #define TK_REINDEX 64
  6945. #define TK_RENAME 65
  6946. #define TK_CTIME_KW 66
  6947. #define TK_ANY 67
  6948. #define TK_OR 68
  6949. #define TK_AND 69
  6950. #define TK_IS 70
  6951. #define TK_BETWEEN 71
  6952. #define TK_IN 72
  6953. #define TK_ISNULL 73
  6954. #define TK_NOTNULL 74
  6955. #define TK_NE 75
  6956. #define TK_EQ 76
  6957. #define TK_GT 77
  6958. #define TK_LE 78
  6959. #define TK_LT 79
  6960. #define TK_GE 80
  6961. #define TK_ESCAPE 81
  6962. #define TK_BITAND 82
  6963. #define TK_BITOR 83
  6964. #define TK_LSHIFT 84
  6965. #define TK_RSHIFT 85
  6966. #define TK_PLUS 86
  6967. #define TK_MINUS 87
  6968. #define TK_STAR 88
  6969. #define TK_SLASH 89
  6970. #define TK_REM 90
  6971. #define TK_CONCAT 91
  6972. #define TK_COLLATE 92
  6973. #define TK_BITNOT 93
  6974. #define TK_STRING 94
  6975. #define TK_JOIN_KW 95
  6976. #define TK_CONSTRAINT 96
  6977. #define TK_DEFAULT 97
  6978. #define TK_NULL 98
  6979. #define TK_PRIMARY 99
  6980. #define TK_UNIQUE 100
  6981. #define TK_CHECK 101
  6982. #define TK_REFERENCES 102
  6983. #define TK_AUTOINCR 103
  6984. #define TK_ON 104
  6985. #define TK_INSERT 105
  6986. #define TK_DELETE 106
  6987. #define TK_UPDATE 107
  6988. #define TK_SET 108
  6989. #define TK_DEFERRABLE 109
  6990. #define TK_FOREIGN 110
  6991. #define TK_DROP 111
  6992. #define TK_UNION 112
  6993. #define TK_ALL 113
  6994. #define TK_EXCEPT 114
  6995. #define TK_INTERSECT 115
  6996. #define TK_SELECT 116
  6997. #define TK_DISTINCT 117
  6998. #define TK_DOT 118
  6999. #define TK_FROM 119
  7000. #define TK_JOIN 120
  7001. #define TK_USING 121
  7002. #define TK_ORDER 122
  7003. #define TK_GROUP 123
  7004. #define TK_HAVING 124
  7005. #define TK_LIMIT 125
  7006. #define TK_WHERE 126
  7007. #define TK_INTO 127
  7008. #define TK_VALUES 128
  7009. #define TK_INTEGER 129
  7010. #define TK_FLOAT 130
  7011. #define TK_BLOB 131
  7012. #define TK_REGISTER 132
  7013. #define TK_VARIABLE 133
  7014. #define TK_CASE 134
  7015. #define TK_WHEN 135
  7016. #define TK_THEN 136
  7017. #define TK_ELSE 137
  7018. #define TK_INDEX 138
  7019. #define TK_ALTER 139
  7020. #define TK_ADD 140
  7021. #define TK_TO_TEXT 141
  7022. #define TK_TO_BLOB 142
  7023. #define TK_TO_NUMERIC 143
  7024. #define TK_TO_INT 144
  7025. #define TK_TO_REAL 145
  7026. #define TK_ISNOT 146
  7027. #define TK_END_OF_FILE 147
  7028. #define TK_ILLEGAL 148
  7029. #define TK_SPACE 149
  7030. #define TK_UNCLOSED_STRING 150
  7031. #define TK_FUNCTION 151
  7032. #define TK_COLUMN 152
  7033. #define TK_AGG_FUNCTION 153
  7034. #define TK_AGG_COLUMN 154
  7035. #define TK_CONST_FUNC 155
  7036. #define TK_UMINUS 156
  7037. #define TK_UPLUS 157
  7038. /************** End of parse.h ***********************************************/
  7039. /************** Continuing where we left off in sqliteInt.h ******************/
  7040. #include <stdio.h>
  7041. #include <stdlib.h>
  7042. #include <string.h>
  7043. #include <assert.h>
  7044. #include <stddef.h>
  7045. /*
  7046. ** If compiling for a processor that lacks floating point support,
  7047. ** substitute integer for floating-point
  7048. */
  7049. #ifdef SQLITE_OMIT_FLOATING_POINT
  7050. # define double sqlite_int64
  7051. # define float sqlite_int64
  7052. # define LONGDOUBLE_TYPE sqlite_int64
  7053. # ifndef SQLITE_BIG_DBL
  7054. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  7055. # endif
  7056. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7057. # define SQLITE_OMIT_TRACE 1
  7058. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7059. # undef SQLITE_HAVE_ISNAN
  7060. #endif
  7061. #ifndef SQLITE_BIG_DBL
  7062. # define SQLITE_BIG_DBL (1e99)
  7063. #endif
  7064. /*
  7065. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7066. ** afterward. Having this macro allows us to cause the C compiler
  7067. ** to omit code used by TEMP tables without messy #ifndef statements.
  7068. */
  7069. #ifdef SQLITE_OMIT_TEMPDB
  7070. #define OMIT_TEMPDB 1
  7071. #else
  7072. #define OMIT_TEMPDB 0
  7073. #endif
  7074. /*
  7075. ** The "file format" number is an integer that is incremented whenever
  7076. ** the VDBE-level file format changes. The following macros define the
  7077. ** the default file format for new databases and the maximum file format
  7078. ** that the library can read.
  7079. */
  7080. #define SQLITE_MAX_FILE_FORMAT 4
  7081. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7082. # define SQLITE_DEFAULT_FILE_FORMAT 1
  7083. #endif
  7084. /*
  7085. ** Determine whether triggers are recursive by default. This can be
  7086. ** changed at run-time using a pragma.
  7087. */
  7088. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  7089. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  7090. #endif
  7091. /*
  7092. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7093. ** on the command-line
  7094. */
  7095. #ifndef SQLITE_TEMP_STORE
  7096. # define SQLITE_TEMP_STORE 1
  7097. #endif
  7098. /*
  7099. ** GCC does not define the offsetof() macro so we'll have to do it
  7100. ** ourselves.
  7101. */
  7102. #ifndef offsetof
  7103. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7104. #endif
  7105. /*
  7106. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7107. ** not, there are still machines out there that use EBCDIC.)
  7108. */
  7109. #if 'A' == '\301'
  7110. # define SQLITE_EBCDIC 1
  7111. #else
  7112. # define SQLITE_ASCII 1
  7113. #endif
  7114. /*
  7115. ** Integers of known sizes. These typedefs might change for architectures
  7116. ** where the sizes very. Preprocessor macros are available so that the
  7117. ** types can be conveniently redefined at compile-type. Like this:
  7118. **
  7119. ** cc '-DUINTPTR_TYPE=long long int' ...
  7120. */
  7121. #ifndef UINT32_TYPE
  7122. # ifdef HAVE_UINT32_T
  7123. # define UINT32_TYPE uint32_t
  7124. # else
  7125. # define UINT32_TYPE unsigned int
  7126. # endif
  7127. #endif
  7128. #ifndef UINT16_TYPE
  7129. # ifdef HAVE_UINT16_T
  7130. # define UINT16_TYPE uint16_t
  7131. # else
  7132. # define UINT16_TYPE unsigned short int
  7133. # endif
  7134. #endif
  7135. #ifndef INT16_TYPE
  7136. # ifdef HAVE_INT16_T
  7137. # define INT16_TYPE int16_t
  7138. # else
  7139. # define INT16_TYPE short int
  7140. # endif
  7141. #endif
  7142. #ifndef UINT8_TYPE
  7143. # ifdef HAVE_UINT8_T
  7144. # define UINT8_TYPE uint8_t
  7145. # else
  7146. # define UINT8_TYPE unsigned char
  7147. # endif
  7148. #endif
  7149. #ifndef INT8_TYPE
  7150. # ifdef HAVE_INT8_T
  7151. # define INT8_TYPE int8_t
  7152. # else
  7153. # define INT8_TYPE signed char
  7154. # endif
  7155. #endif
  7156. #ifndef LONGDOUBLE_TYPE
  7157. # define LONGDOUBLE_TYPE long double
  7158. #endif
  7159. typedef sqlite_int64 i64; /* 8-byte signed integer */
  7160. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  7161. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  7162. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  7163. typedef INT16_TYPE i16; /* 2-byte signed integer */
  7164. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  7165. typedef INT8_TYPE i8; /* 1-byte signed integer */
  7166. /*
  7167. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  7168. ** that can be stored in a u32 without loss of data. The value
  7169. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  7170. ** have to specify the value in the less intuitive manner shown:
  7171. */
  7172. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  7173. /*
  7174. ** Macros to determine whether the machine is big or little endian,
  7175. ** evaluated at runtime.
  7176. */
  7177. #ifdef SQLITE_AMALGAMATION
  7178. SQLITE_PRIVATE const int sqlite3one = 1;
  7179. #else
  7180. SQLITE_PRIVATE const int sqlite3one;
  7181. #endif
  7182. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  7183. || defined(__x86_64) || defined(__x86_64__)
  7184. # define SQLITE_BIGENDIAN 0
  7185. # define SQLITE_LITTLEENDIAN 1
  7186. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  7187. #else
  7188. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  7189. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  7190. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  7191. #endif
  7192. /*
  7193. ** Constants for the largest and smallest possible 64-bit signed integers.
  7194. ** These macros are designed to work correctly on both 32-bit and 64-bit
  7195. ** compilers.
  7196. */
  7197. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  7198. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  7199. /*
  7200. ** Round up a number to the next larger multiple of 8. This is used
  7201. ** to force 8-byte alignment on 64-bit architectures.
  7202. */
  7203. #define ROUND8(x) (((x)+7)&~7)
  7204. /*
  7205. ** Round down to the nearest multiple of 8
  7206. */
  7207. #define ROUNDDOWN8(x) ((x)&~7)
  7208. /*
  7209. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  7210. ** macro is used only within assert() to verify that the code gets
  7211. ** all alignment restrictions correct.
  7212. **
  7213. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  7214. ** underlying malloc() implemention might return us 4-byte aligned
  7215. ** pointers. In that case, only verify 4-byte alignment.
  7216. */
  7217. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  7218. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  7219. #else
  7220. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  7221. #endif
  7222. /*
  7223. ** An instance of the following structure is used to store the busy-handler
  7224. ** callback for a given sqlite handle.
  7225. **
  7226. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  7227. ** callback for the database handle. Each pager opened via the sqlite
  7228. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  7229. ** callback is currently invoked only from within pager.c.
  7230. */
  7231. typedef struct BusyHandler BusyHandler;
  7232. struct BusyHandler {
  7233. int (*xFunc)(void *,int); /* The busy callback */
  7234. void *pArg; /* First arg to busy callback */
  7235. int nBusy; /* Incremented with each busy call */
  7236. };
  7237. /*
  7238. ** Name of the master database table. The master database table
  7239. ** is a special table that holds the names and attributes of all
  7240. ** user tables and indices.
  7241. */
  7242. #define MASTER_NAME "sqlite_master"
  7243. #define TEMP_MASTER_NAME "sqlite_temp_master"
  7244. /*
  7245. ** The root-page of the master database table.
  7246. */
  7247. #define MASTER_ROOT 1
  7248. /*
  7249. ** The name of the schema table.
  7250. */
  7251. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  7252. /*
  7253. ** A convenience macro that returns the number of elements in
  7254. ** an array.
  7255. */
  7256. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  7257. /*
  7258. ** The following value as a destructor means to use sqlite3DbFree().
  7259. ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
  7260. */
  7261. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3DbFree)
  7262. /*
  7263. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  7264. ** not support Writable Static Data (WSD) such as global and static variables.
  7265. ** All variables must either be on the stack or dynamically allocated from
  7266. ** the heap. When WSD is unsupported, the variable declarations scattered
  7267. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  7268. ** macro is used for this purpose. And instead of referencing the variable
  7269. ** directly, we use its constant as a key to lookup the run-time allocated
  7270. ** buffer that holds real variable. The constant is also the initializer
  7271. ** for the run-time allocated buffer.
  7272. **
  7273. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  7274. ** macros become no-ops and have zero performance impact.
  7275. */
  7276. #ifdef SQLITE_OMIT_WSD
  7277. #define SQLITE_WSD const
  7278. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  7279. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  7280. SQLITE_API int sqlite3_wsd_init(int N, int J);
  7281. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  7282. #else
  7283. #define SQLITE_WSD
  7284. #define GLOBAL(t,v) v
  7285. #define sqlite3GlobalConfig sqlite3Config
  7286. #endif
  7287. /*
  7288. ** The following macros are used to suppress compiler warnings and to
  7289. ** make it clear to human readers when a function parameter is deliberately
  7290. ** left unused within the body of a function. This usually happens when
  7291. ** a function is called via a function pointer. For example the
  7292. ** implementation of an SQL aggregate step callback may not use the
  7293. ** parameter indicating the number of arguments passed to the aggregate,
  7294. ** if it knows that this is enforced elsewhere.
  7295. **
  7296. ** When a function parameter is not used at all within the body of a function,
  7297. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  7298. ** However, these macros may also be used to suppress warnings related to
  7299. ** parameters that may or may not be used depending on compilation options.
  7300. ** For example those parameters only used in assert() statements. In these
  7301. ** cases the parameters are named as per the usual conventions.
  7302. */
  7303. #define UNUSED_PARAMETER(x) (void)(x)
  7304. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  7305. /*
  7306. ** Forward references to structures
  7307. */
  7308. typedef struct AggInfo AggInfo;
  7309. typedef struct AuthContext AuthContext;
  7310. typedef struct AutoincInfo AutoincInfo;
  7311. typedef struct Bitvec Bitvec;
  7312. typedef struct CollSeq CollSeq;
  7313. typedef struct Column Column;
  7314. typedef struct Db Db;
  7315. typedef struct Schema Schema;
  7316. typedef struct Expr Expr;
  7317. typedef struct ExprList ExprList;
  7318. typedef struct ExprSpan ExprSpan;
  7319. typedef struct FKey FKey;
  7320. typedef struct FuncDestructor FuncDestructor;
  7321. typedef struct FuncDef FuncDef;
  7322. typedef struct FuncDefHash FuncDefHash;
  7323. typedef struct IdList IdList;
  7324. typedef struct Index Index;
  7325. typedef struct IndexSample IndexSample;
  7326. typedef struct KeyClass KeyClass;
  7327. typedef struct KeyInfo KeyInfo;
  7328. typedef struct Lookaside Lookaside;
  7329. typedef struct LookasideSlot LookasideSlot;
  7330. typedef struct Module Module;
  7331. typedef struct NameContext NameContext;
  7332. typedef struct Parse Parse;
  7333. typedef struct RowSet RowSet;
  7334. typedef struct Savepoint Savepoint;
  7335. typedef struct Select Select;
  7336. typedef struct SrcList SrcList;
  7337. typedef struct StrAccum StrAccum;
  7338. typedef struct Table Table;
  7339. typedef struct TableLock TableLock;
  7340. typedef struct Token Token;
  7341. typedef struct Trigger Trigger;
  7342. typedef struct TriggerPrg TriggerPrg;
  7343. typedef struct TriggerStep TriggerStep;
  7344. typedef struct UnpackedRecord UnpackedRecord;
  7345. typedef struct VTable VTable;
  7346. typedef struct Walker Walker;
  7347. typedef struct WherePlan WherePlan;
  7348. typedef struct WhereInfo WhereInfo;
  7349. typedef struct WhereLevel WhereLevel;
  7350. /*
  7351. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  7352. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  7353. ** pointer types (i.e. FuncDef) defined above.
  7354. */
  7355. /************** Include btree.h in the middle of sqliteInt.h *****************/
  7356. /************** Begin file btree.h *******************************************/
  7357. /*
  7358. ** 2001 September 15
  7359. **
  7360. ** The author disclaims copyright to this source code. In place of
  7361. ** a legal notice, here is a blessing:
  7362. **
  7363. ** May you do good and not evil.
  7364. ** May you find forgiveness for yourself and forgive others.
  7365. ** May you share freely, never taking more than you give.
  7366. **
  7367. *************************************************************************
  7368. ** This header file defines the interface that the sqlite B-Tree file
  7369. ** subsystem. See comments in the source code for a detailed description
  7370. ** of what each interface routine does.
  7371. */
  7372. #ifndef _BTREE_H_
  7373. #define _BTREE_H_
  7374. /* TODO: This definition is just included so other modules compile. It
  7375. ** needs to be revisited.
  7376. */
  7377. #define SQLITE_N_BTREE_META 10
  7378. /*
  7379. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  7380. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  7381. */
  7382. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  7383. #define SQLITE_DEFAULT_AUTOVACUUM 0
  7384. #endif
  7385. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  7386. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  7387. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  7388. /*
  7389. ** Forward declarations of structure
  7390. */
  7391. typedef struct Btree Btree;
  7392. typedef struct BtCursor BtCursor;
  7393. typedef struct BtShared BtShared;
  7394. SQLITE_PRIVATE int sqlite3BtreeOpen(
  7395. const char *zFilename, /* Name of database file to open */
  7396. sqlite3 *db, /* Associated database connection */
  7397. Btree **ppBtree, /* Return open Btree* here */
  7398. int flags, /* Flags */
  7399. int vfsFlags /* Flags passed through to VFS open */
  7400. );
  7401. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  7402. ** following values.
  7403. **
  7404. ** NOTE: These values must match the corresponding PAGER_ values in
  7405. ** pager.h.
  7406. */
  7407. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  7408. #define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
  7409. #define BTREE_MEMORY 4 /* This is an in-memory DB */
  7410. #define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
  7411. #define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
  7412. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  7413. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  7414. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
  7415. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  7416. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  7417. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  7418. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  7419. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  7420. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  7421. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  7422. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  7423. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  7424. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  7425. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  7426. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  7427. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  7428. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
  7429. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  7430. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  7431. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  7432. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  7433. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  7434. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  7435. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  7436. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  7437. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  7438. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  7439. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  7440. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  7441. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  7442. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  7443. ** of the flags shown below.
  7444. **
  7445. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  7446. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  7447. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  7448. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  7449. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  7450. ** indices.)
  7451. */
  7452. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  7453. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  7454. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  7455. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  7456. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  7457. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  7458. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  7459. /*
  7460. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  7461. ** should be one of the following values. The integer values are assigned
  7462. ** to constants so that the offset of the corresponding field in an
  7463. ** SQLite database header may be found using the following formula:
  7464. **
  7465. ** offset = 36 + (idx * 4)
  7466. **
  7467. ** For example, the free-page-count field is located at byte offset 36 of
  7468. ** the database file header. The incr-vacuum-flag field is located at
  7469. ** byte offset 64 (== 36+4*7).
  7470. */
  7471. #define BTREE_FREE_PAGE_COUNT 0
  7472. #define BTREE_SCHEMA_VERSION 1
  7473. #define BTREE_FILE_FORMAT 2
  7474. #define BTREE_DEFAULT_CACHE_SIZE 3
  7475. #define BTREE_LARGEST_ROOT_PAGE 4
  7476. #define BTREE_TEXT_ENCODING 5
  7477. #define BTREE_USER_VERSION 6
  7478. #define BTREE_INCR_VACUUM 7
  7479. SQLITE_PRIVATE int sqlite3BtreeCursor(
  7480. Btree*, /* BTree containing table to open */
  7481. int iTable, /* Index of root page */
  7482. int wrFlag, /* 1 for writing. 0 for read-only */
  7483. struct KeyInfo*, /* First argument to compare function */
  7484. BtCursor *pCursor /* Space to write cursor structure */
  7485. );
  7486. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  7487. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  7488. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  7489. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  7490. BtCursor*,
  7491. UnpackedRecord *pUnKey,
  7492. i64 intKey,
  7493. int bias,
  7494. int *pRes
  7495. );
  7496. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  7497. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  7498. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  7499. const void *pData, int nData,
  7500. int nZero, int bias, int seekResult);
  7501. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  7502. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  7503. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  7504. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  7505. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  7506. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  7507. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  7508. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  7509. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  7510. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  7511. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  7512. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  7513. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  7514. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  7515. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  7516. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  7517. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  7518. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  7519. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  7520. #ifndef NDEBUG
  7521. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  7522. #endif
  7523. #ifndef SQLITE_OMIT_BTREECOUNT
  7524. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  7525. #endif
  7526. #ifdef SQLITE_TEST
  7527. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  7528. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  7529. #endif
  7530. #ifndef SQLITE_OMIT_WAL
  7531. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  7532. #endif
  7533. /*
  7534. ** If we are not using shared cache, then there is no need to
  7535. ** use mutexes to access the BtShared structures. So make the
  7536. ** Enter and Leave procedures no-ops.
  7537. */
  7538. #ifndef SQLITE_OMIT_SHARED_CACHE
  7539. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  7540. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  7541. #else
  7542. # define sqlite3BtreeEnter(X)
  7543. # define sqlite3BtreeEnterAll(X)
  7544. #endif
  7545. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  7546. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  7547. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  7548. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  7549. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  7550. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  7551. #ifndef NDEBUG
  7552. /* These routines are used inside assert() statements only. */
  7553. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  7554. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  7555. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  7556. #endif
  7557. #else
  7558. # define sqlite3BtreeSharable(X) 0
  7559. # define sqlite3BtreeLeave(X)
  7560. # define sqlite3BtreeEnterCursor(X)
  7561. # define sqlite3BtreeLeaveCursor(X)
  7562. # define sqlite3BtreeLeaveAll(X)
  7563. # define sqlite3BtreeHoldsMutex(X) 1
  7564. # define sqlite3BtreeHoldsAllMutexes(X) 1
  7565. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  7566. #endif
  7567. #endif /* _BTREE_H_ */
  7568. /************** End of btree.h ***********************************************/
  7569. /************** Continuing where we left off in sqliteInt.h ******************/
  7570. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  7571. /************** Begin file vdbe.h ********************************************/
  7572. /*
  7573. ** 2001 September 15
  7574. **
  7575. ** The author disclaims copyright to this source code. In place of
  7576. ** a legal notice, here is a blessing:
  7577. **
  7578. ** May you do good and not evil.
  7579. ** May you find forgiveness for yourself and forgive others.
  7580. ** May you share freely, never taking more than you give.
  7581. **
  7582. *************************************************************************
  7583. ** Header file for the Virtual DataBase Engine (VDBE)
  7584. **
  7585. ** This header defines the interface to the virtual database engine
  7586. ** or VDBE. The VDBE implements an abstract machine that runs a
  7587. ** simple program to access and modify the underlying database.
  7588. */
  7589. #ifndef _SQLITE_VDBE_H_
  7590. #define _SQLITE_VDBE_H_
  7591. /*
  7592. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  7593. ** in the source file sqliteVdbe.c are allowed to see the insides
  7594. ** of this structure.
  7595. */
  7596. typedef struct Vdbe Vdbe;
  7597. /*
  7598. ** The names of the following types declared in vdbeInt.h are required
  7599. ** for the VdbeOp definition.
  7600. */
  7601. typedef struct VdbeFunc VdbeFunc;
  7602. typedef struct Mem Mem;
  7603. typedef struct SubProgram SubProgram;
  7604. /*
  7605. ** A single instruction of the virtual machine has an opcode
  7606. ** and as many as three operands. The instruction is recorded
  7607. ** as an instance of the following structure:
  7608. */
  7609. struct VdbeOp {
  7610. u8 opcode; /* What operation to perform */
  7611. signed char p4type; /* One of the P4_xxx constants for p4 */
  7612. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  7613. u8 p5; /* Fifth parameter is an unsigned character */
  7614. int p1; /* First operand */
  7615. int p2; /* Second parameter (often the jump destination) */
  7616. int p3; /* The third parameter */
  7617. union { /* fourth parameter */
  7618. int i; /* Integer value if p4type==P4_INT32 */
  7619. void *p; /* Generic pointer */
  7620. char *z; /* Pointer to data for string (char array) types */
  7621. i64 *pI64; /* Used when p4type is P4_INT64 */
  7622. double *pReal; /* Used when p4type is P4_REAL */
  7623. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  7624. VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
  7625. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  7626. Mem *pMem; /* Used when p4type is P4_MEM */
  7627. VTable *pVtab; /* Used when p4type is P4_VTAB */
  7628. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  7629. int *ai; /* Used when p4type is P4_INTARRAY */
  7630. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  7631. } p4;
  7632. #ifdef SQLITE_DEBUG
  7633. char *zComment; /* Comment to improve readability */
  7634. #endif
  7635. #ifdef VDBE_PROFILE
  7636. int cnt; /* Number of times this instruction was executed */
  7637. u64 cycles; /* Total time spent executing this instruction */
  7638. #endif
  7639. };
  7640. typedef struct VdbeOp VdbeOp;
  7641. /*
  7642. ** A sub-routine used to implement a trigger program.
  7643. */
  7644. struct SubProgram {
  7645. VdbeOp *aOp; /* Array of opcodes for sub-program */
  7646. int nOp; /* Elements in aOp[] */
  7647. int nMem; /* Number of memory cells required */
  7648. int nCsr; /* Number of cursors required */
  7649. void *token; /* id that may be used to recursive triggers */
  7650. SubProgram *pNext; /* Next sub-program already visited */
  7651. };
  7652. /*
  7653. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  7654. ** it takes up less space.
  7655. */
  7656. struct VdbeOpList {
  7657. u8 opcode; /* What operation to perform */
  7658. signed char p1; /* First operand */
  7659. signed char p2; /* Second parameter (often the jump destination) */
  7660. signed char p3; /* Third parameter */
  7661. };
  7662. typedef struct VdbeOpList VdbeOpList;
  7663. /*
  7664. ** Allowed values of VdbeOp.p4type
  7665. */
  7666. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  7667. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  7668. #define P4_STATIC (-2) /* Pointer to a static string */
  7669. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  7670. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  7671. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  7672. #define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */
  7673. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  7674. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  7675. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  7676. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  7677. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  7678. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  7679. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  7680. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  7681. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  7682. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  7683. ** is made. That copy is freed when the Vdbe is finalized. But if the
  7684. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  7685. ** gets freed when the Vdbe is finalized so it still should be obtained
  7686. ** from a single sqliteMalloc(). But no copy is made and the calling
  7687. ** function should *not* try to free the KeyInfo.
  7688. */
  7689. #define P4_KEYINFO_HANDOFF (-16)
  7690. #define P4_KEYINFO_STATIC (-17)
  7691. /*
  7692. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  7693. ** number of columns of data returned by the statement.
  7694. */
  7695. #define COLNAME_NAME 0
  7696. #define COLNAME_DECLTYPE 1
  7697. #define COLNAME_DATABASE 2
  7698. #define COLNAME_TABLE 3
  7699. #define COLNAME_COLUMN 4
  7700. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  7701. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  7702. #else
  7703. # ifdef SQLITE_OMIT_DECLTYPE
  7704. # define COLNAME_N 1 /* Store only the name */
  7705. # else
  7706. # define COLNAME_N 2 /* Store the name and decltype */
  7707. # endif
  7708. #endif
  7709. /*
  7710. ** The following macro converts a relative address in the p2 field
  7711. ** of a VdbeOp structure into a negative number so that
  7712. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  7713. ** the macro again restores the address.
  7714. */
  7715. #define ADDR(X) (-1-(X))
  7716. /*
  7717. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  7718. ** header file that defines a number for each opcode used by the VDBE.
  7719. */
  7720. /************** Include opcodes.h in the middle of vdbe.h ********************/
  7721. /************** Begin file opcodes.h *****************************************/
  7722. /* Automatically generated. Do not edit */
  7723. /* See the mkopcodeh.awk script for details */
  7724. #define OP_Goto 1
  7725. #define OP_Gosub 2
  7726. #define OP_Return 3
  7727. #define OP_Yield 4
  7728. #define OP_HaltIfNull 5
  7729. #define OP_Halt 6
  7730. #define OP_Integer 7
  7731. #define OP_Int64 8
  7732. #define OP_Real 130 /* same as TK_FLOAT */
  7733. #define OP_String8 94 /* same as TK_STRING */
  7734. #define OP_String 9
  7735. #define OP_Null 10
  7736. #define OP_Blob 11
  7737. #define OP_Variable 12
  7738. #define OP_Move 13
  7739. #define OP_Copy 14
  7740. #define OP_SCopy 15
  7741. #define OP_ResultRow 16
  7742. #define OP_Concat 91 /* same as TK_CONCAT */
  7743. #define OP_Add 86 /* same as TK_PLUS */
  7744. #define OP_Subtract 87 /* same as TK_MINUS */
  7745. #define OP_Multiply 88 /* same as TK_STAR */
  7746. #define OP_Divide 89 /* same as TK_SLASH */
  7747. #define OP_Remainder 90 /* same as TK_REM */
  7748. #define OP_CollSeq 17
  7749. #define OP_Function 18
  7750. #define OP_BitAnd 82 /* same as TK_BITAND */
  7751. #define OP_BitOr 83 /* same as TK_BITOR */
  7752. #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
  7753. #define OP_ShiftRight 85 /* same as TK_RSHIFT */
  7754. #define OP_AddImm 20
  7755. #define OP_MustBeInt 21
  7756. #define OP_RealAffinity 22
  7757. #define OP_ToText 141 /* same as TK_TO_TEXT */
  7758. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  7759. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  7760. #define OP_ToInt 144 /* same as TK_TO_INT */
  7761. #define OP_ToReal 145 /* same as TK_TO_REAL */
  7762. #define OP_Eq 76 /* same as TK_EQ */
  7763. #define OP_Ne 75 /* same as TK_NE */
  7764. #define OP_Lt 79 /* same as TK_LT */
  7765. #define OP_Le 78 /* same as TK_LE */
  7766. #define OP_Gt 77 /* same as TK_GT */
  7767. #define OP_Ge 80 /* same as TK_GE */
  7768. #define OP_Permutation 23
  7769. #define OP_Compare 24
  7770. #define OP_Jump 25
  7771. #define OP_And 69 /* same as TK_AND */
  7772. #define OP_Or 68 /* same as TK_OR */
  7773. #define OP_Not 19 /* same as TK_NOT */
  7774. #define OP_BitNot 93 /* same as TK_BITNOT */
  7775. #define OP_If 26
  7776. #define OP_IfNot 27
  7777. #define OP_IsNull 73 /* same as TK_ISNULL */
  7778. #define OP_NotNull 74 /* same as TK_NOTNULL */
  7779. #define OP_Column 28
  7780. #define OP_Affinity 29
  7781. #define OP_MakeRecord 30
  7782. #define OP_Count 31
  7783. #define OP_Savepoint 32
  7784. #define OP_AutoCommit 33
  7785. #define OP_Transaction 34
  7786. #define OP_ReadCookie 35
  7787. #define OP_SetCookie 36
  7788. #define OP_VerifyCookie 37
  7789. #define OP_OpenRead 38
  7790. #define OP_OpenWrite 39
  7791. #define OP_OpenAutoindex 40
  7792. #define OP_OpenEphemeral 41
  7793. #define OP_OpenPseudo 42
  7794. #define OP_Close 43
  7795. #define OP_SeekLt 44
  7796. #define OP_SeekLe 45
  7797. #define OP_SeekGe 46
  7798. #define OP_SeekGt 47
  7799. #define OP_Seek 48
  7800. #define OP_NotFound 49
  7801. #define OP_Found 50
  7802. #define OP_IsUnique 51
  7803. #define OP_NotExists 52
  7804. #define OP_Sequence 53
  7805. #define OP_NewRowid 54
  7806. #define OP_Insert 55
  7807. #define OP_InsertInt 56
  7808. #define OP_Delete 57
  7809. #define OP_ResetCount 58
  7810. #define OP_RowKey 59
  7811. #define OP_RowData 60
  7812. #define OP_Rowid 61
  7813. #define OP_NullRow 62
  7814. #define OP_Last 63
  7815. #define OP_Sort 64
  7816. #define OP_Rewind 65
  7817. #define OP_Prev 66
  7818. #define OP_Next 67
  7819. #define OP_IdxInsert 70
  7820. #define OP_IdxDelete 71
  7821. #define OP_IdxRowid 72
  7822. #define OP_IdxLT 81
  7823. #define OP_IdxGE 92
  7824. #define OP_Destroy 95
  7825. #define OP_Clear 96
  7826. #define OP_CreateIndex 97
  7827. #define OP_CreateTable 98
  7828. #define OP_ParseSchema 99
  7829. #define OP_LoadAnalysis 100
  7830. #define OP_DropTable 101
  7831. #define OP_DropIndex 102
  7832. #define OP_DropTrigger 103
  7833. #define OP_IntegrityCk 104
  7834. #define OP_RowSetAdd 105
  7835. #define OP_RowSetRead 106
  7836. #define OP_RowSetTest 107
  7837. #define OP_Program 108
  7838. #define OP_Param 109
  7839. #define OP_FkCounter 110
  7840. #define OP_FkIfZero 111
  7841. #define OP_MemMax 112
  7842. #define OP_IfPos 113
  7843. #define OP_IfNeg 114
  7844. #define OP_IfZero 115
  7845. #define OP_AggStep 116
  7846. #define OP_AggFinal 117
  7847. #define OP_Checkpoint 118
  7848. #define OP_JournalMode 119
  7849. #define OP_Vacuum 120
  7850. #define OP_IncrVacuum 121
  7851. #define OP_Expire 122
  7852. #define OP_TableLock 123
  7853. #define OP_VBegin 124
  7854. #define OP_VCreate 125
  7855. #define OP_VDestroy 126
  7856. #define OP_VOpen 127
  7857. #define OP_VFilter 128
  7858. #define OP_VColumn 129
  7859. #define OP_VNext 131
  7860. #define OP_VRename 132
  7861. #define OP_VUpdate 133
  7862. #define OP_Pagecount 134
  7863. #define OP_MaxPgcnt 135
  7864. #define OP_Trace 136
  7865. #define OP_Noop 137
  7866. #define OP_Explain 138
  7867. /* The following opcode values are never used */
  7868. #define OP_NotUsed_139 139
  7869. #define OP_NotUsed_140 140
  7870. /* Properties such as "out2" or "jump" that are specified in
  7871. ** comments following the "case" for each opcode in the vdbe.c
  7872. ** are encoded into bitvectors as follows:
  7873. */
  7874. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  7875. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  7876. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  7877. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  7878. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  7879. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  7880. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  7881. #define OPFLG_INITIALIZER {\
  7882. /* 0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
  7883. /* 8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
  7884. /* 16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
  7885. /* 24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
  7886. /* 32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
  7887. /* 40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
  7888. /* 48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
  7889. /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
  7890. /* 64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
  7891. /* 72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
  7892. /* 80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
  7893. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
  7894. /* 96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
  7895. /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
  7896. /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
  7897. /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  7898. /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
  7899. /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
  7900. /* 144 */ 0x04, 0x04,}
  7901. /************** End of opcodes.h *********************************************/
  7902. /************** Continuing where we left off in vdbe.h ***********************/
  7903. /*
  7904. ** Prototypes for the VDBE interface. See comments on the implementation
  7905. ** for a description of what each of these routines does.
  7906. */
  7907. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  7908. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  7909. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  7910. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  7911. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  7912. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  7913. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  7914. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  7915. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
  7916. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
  7917. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
  7918. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  7919. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  7920. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
  7921. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  7922. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  7923. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  7924. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  7925. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  7926. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  7927. SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
  7928. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
  7929. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  7930. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  7931. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  7932. #ifdef SQLITE_DEBUG
  7933. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  7934. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  7935. #endif
  7936. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  7937. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  7938. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  7939. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  7940. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  7941. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  7942. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  7943. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  7944. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  7945. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
  7946. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  7947. #ifndef SQLITE_OMIT_TRACE
  7948. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  7949. #endif
  7950. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
  7951. SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
  7952. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  7953. #ifndef SQLITE_OMIT_TRIGGER
  7954. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  7955. #endif
  7956. #ifndef NDEBUG
  7957. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  7958. # define VdbeComment(X) sqlite3VdbeComment X
  7959. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  7960. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  7961. #else
  7962. # define VdbeComment(X)
  7963. # define VdbeNoopComment(X)
  7964. #endif
  7965. #endif
  7966. /************** End of vdbe.h ************************************************/
  7967. /************** Continuing where we left off in sqliteInt.h ******************/
  7968. /************** Include pager.h in the middle of sqliteInt.h *****************/
  7969. /************** Begin file pager.h *******************************************/
  7970. /*
  7971. ** 2001 September 15
  7972. **
  7973. ** The author disclaims copyright to this source code. In place of
  7974. ** a legal notice, here is a blessing:
  7975. **
  7976. ** May you do good and not evil.
  7977. ** May you find forgiveness for yourself and forgive others.
  7978. ** May you share freely, never taking more than you give.
  7979. **
  7980. *************************************************************************
  7981. ** This header file defines the interface that the sqlite page cache
  7982. ** subsystem. The page cache subsystem reads and writes a file a page
  7983. ** at a time and provides a journal for rollback.
  7984. */
  7985. #ifndef _PAGER_H_
  7986. #define _PAGER_H_
  7987. /*
  7988. ** Default maximum size for persistent journal files. A negative
  7989. ** value means no limit. This value may be overridden using the
  7990. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  7991. */
  7992. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  7993. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  7994. #endif
  7995. /*
  7996. ** The type used to represent a page number. The first page in a file
  7997. ** is called page 1. 0 is used to represent "not a page".
  7998. */
  7999. typedef u32 Pgno;
  8000. /*
  8001. ** Each open file is managed by a separate instance of the "Pager" structure.
  8002. */
  8003. typedef struct Pager Pager;
  8004. /*
  8005. ** Handle type for pages.
  8006. */
  8007. typedef struct PgHdr DbPage;
  8008. /*
  8009. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  8010. ** reserved for working around a windows/posix incompatibility). It is
  8011. ** used in the journal to signify that the remainder of the journal file
  8012. ** is devoted to storing a master journal name - there are no more pages to
  8013. ** roll back. See comments for function writeMasterJournal() in pager.c
  8014. ** for details.
  8015. */
  8016. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  8017. /*
  8018. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  8019. **
  8020. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  8021. */
  8022. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  8023. #define PAGER_NO_READLOCK 0x0002 /* Omit readlocks on readonly files */
  8024. #define PAGER_MEMORY 0x0004 /* In-memory database */
  8025. /*
  8026. ** Valid values for the second argument to sqlite3PagerLockingMode().
  8027. */
  8028. #define PAGER_LOCKINGMODE_QUERY -1
  8029. #define PAGER_LOCKINGMODE_NORMAL 0
  8030. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  8031. /*
  8032. ** Numeric constants that encode the journalmode.
  8033. */
  8034. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  8035. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  8036. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  8037. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  8038. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  8039. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  8040. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  8041. /*
  8042. ** The remainder of this file contains the declarations of the functions
  8043. ** that make up the Pager sub-system API. See source code comments for
  8044. ** a detailed description of each routine.
  8045. */
  8046. /* Open and close a Pager connection. */
  8047. SQLITE_PRIVATE int sqlite3PagerOpen(
  8048. sqlite3_vfs*,
  8049. Pager **ppPager,
  8050. const char*,
  8051. int,
  8052. int,
  8053. int,
  8054. void(*)(DbPage*)
  8055. );
  8056. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  8057. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  8058. /* Functions used to configure a Pager object. */
  8059. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  8060. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  8061. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  8062. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  8063. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
  8064. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  8065. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  8066. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  8067. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  8068. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  8069. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  8070. /* Functions used to obtain and release page references. */
  8071. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  8072. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  8073. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  8074. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  8075. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  8076. /* Operations on page references. */
  8077. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  8078. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  8079. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  8080. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  8081. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  8082. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  8083. /* Functions used to manage pager transactions and savepoints. */
  8084. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  8085. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  8086. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  8087. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  8088. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  8089. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  8090. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  8091. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  8092. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  8093. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  8094. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  8095. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  8096. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  8097. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  8098. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  8099. /* Functions used to query pager state and configuration. */
  8100. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  8101. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  8102. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  8103. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
  8104. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  8105. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  8106. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  8107. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  8108. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  8109. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  8110. /* Functions used to truncate the database file. */
  8111. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  8112. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  8113. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  8114. #endif
  8115. /* Functions to support testing and debugging. */
  8116. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  8117. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  8118. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  8119. #endif
  8120. #ifdef SQLITE_TEST
  8121. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  8122. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  8123. void disable_simulated_io_errors(void);
  8124. void enable_simulated_io_errors(void);
  8125. #else
  8126. # define disable_simulated_io_errors()
  8127. # define enable_simulated_io_errors()
  8128. #endif
  8129. #endif /* _PAGER_H_ */
  8130. /************** End of pager.h ***********************************************/
  8131. /************** Continuing where we left off in sqliteInt.h ******************/
  8132. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  8133. /************** Begin file pcache.h ******************************************/
  8134. /*
  8135. ** 2008 August 05
  8136. **
  8137. ** The author disclaims copyright to this source code. In place of
  8138. ** a legal notice, here is a blessing:
  8139. **
  8140. ** May you do good and not evil.
  8141. ** May you find forgiveness for yourself and forgive others.
  8142. ** May you share freely, never taking more than you give.
  8143. **
  8144. *************************************************************************
  8145. ** This header file defines the interface that the sqlite page cache
  8146. ** subsystem.
  8147. */
  8148. #ifndef _PCACHE_H_
  8149. typedef struct PgHdr PgHdr;
  8150. typedef struct PCache PCache;
  8151. /*
  8152. ** Every page in the cache is controlled by an instance of the following
  8153. ** structure.
  8154. */
  8155. struct PgHdr {
  8156. void *pData; /* Content of this page */
  8157. void *pExtra; /* Extra content */
  8158. PgHdr *pDirty; /* Transient list of dirty pages */
  8159. Pgno pgno; /* Page number for this page */
  8160. Pager *pPager; /* The pager this page is part of */
  8161. #ifdef SQLITE_CHECK_PAGES
  8162. u32 pageHash; /* Hash of page content */
  8163. #endif
  8164. u16 flags; /* PGHDR flags defined below */
  8165. /**********************************************************************
  8166. ** Elements above are public. All that follows is private to pcache.c
  8167. ** and should not be accessed by other modules.
  8168. */
  8169. i16 nRef; /* Number of users of this page */
  8170. PCache *pCache; /* Cache that owns this page */
  8171. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  8172. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  8173. };
  8174. /* Bit values for PgHdr.flags */
  8175. #define PGHDR_DIRTY 0x002 /* Page has changed */
  8176. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  8177. ** writing this page to the database */
  8178. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  8179. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  8180. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  8181. /* Initialize and shutdown the page cache subsystem */
  8182. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  8183. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  8184. /* Page cache buffer management:
  8185. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  8186. */
  8187. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  8188. /* Create a new pager cache.
  8189. ** Under memory stress, invoke xStress to try to make pages clean.
  8190. ** Only clean and unpinned pages can be reclaimed.
  8191. */
  8192. SQLITE_PRIVATE void sqlite3PcacheOpen(
  8193. int szPage, /* Size of every page */
  8194. int szExtra, /* Extra space associated with each page */
  8195. int bPurgeable, /* True if pages are on backing store */
  8196. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  8197. void *pStress, /* Argument to xStress */
  8198. PCache *pToInit /* Preallocated space for the PCache */
  8199. );
  8200. /* Modify the page-size after the cache has been created. */
  8201. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  8202. /* Return the size in bytes of a PCache object. Used to preallocate
  8203. ** storage space.
  8204. */
  8205. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  8206. /* One release per successful fetch. Page is pinned until released.
  8207. ** Reference counted.
  8208. */
  8209. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  8210. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  8211. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  8212. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  8213. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  8214. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  8215. /* Change a page number. Used by incr-vacuum. */
  8216. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  8217. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  8218. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  8219. /* Get a list of all dirty pages in the cache, sorted by page number */
  8220. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  8221. /* Reset and close the cache object */
  8222. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  8223. /* Clear flags from pages of the page cache */
  8224. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  8225. /* Discard the contents of the cache */
  8226. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  8227. /* Return the total number of outstanding page references */
  8228. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  8229. /* Increment the reference count of an existing page */
  8230. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  8231. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  8232. /* Return the total number of pages stored in the cache */
  8233. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  8234. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  8235. /* Iterate through all dirty pages currently stored in the cache. This
  8236. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  8237. ** library is built.
  8238. */
  8239. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  8240. #endif
  8241. /* Set and get the suggested cache-size for the specified pager-cache.
  8242. **
  8243. ** If no global maximum is configured, then the system attempts to limit
  8244. ** the total number of pages cached by purgeable pager-caches to the sum
  8245. ** of the suggested cache-sizes.
  8246. */
  8247. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  8248. #ifdef SQLITE_TEST
  8249. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  8250. #endif
  8251. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  8252. /* Try to return memory used by the pcache module to the main memory heap */
  8253. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  8254. #endif
  8255. #ifdef SQLITE_TEST
  8256. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  8257. #endif
  8258. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  8259. #endif /* _PCACHE_H_ */
  8260. /************** End of pcache.h **********************************************/
  8261. /************** Continuing where we left off in sqliteInt.h ******************/
  8262. /************** Include os.h in the middle of sqliteInt.h ********************/
  8263. /************** Begin file os.h **********************************************/
  8264. /*
  8265. ** 2001 September 16
  8266. **
  8267. ** The author disclaims copyright to this source code. In place of
  8268. ** a legal notice, here is a blessing:
  8269. **
  8270. ** May you do good and not evil.
  8271. ** May you find forgiveness for yourself and forgive others.
  8272. ** May you share freely, never taking more than you give.
  8273. **
  8274. ******************************************************************************
  8275. **
  8276. ** This header file (together with is companion C source-code file
  8277. ** "os.c") attempt to abstract the underlying operating system so that
  8278. ** the SQLite library will work on both POSIX and windows systems.
  8279. **
  8280. ** This header file is #include-ed by sqliteInt.h and thus ends up
  8281. ** being included by every source file.
  8282. */
  8283. #ifndef _SQLITE_OS_H_
  8284. #define _SQLITE_OS_H_
  8285. /*
  8286. ** Figure out if we are dealing with Unix, Windows, or some other
  8287. ** operating system. After the following block of preprocess macros,
  8288. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
  8289. ** will defined to either 1 or 0. One of the four will be 1. The other
  8290. ** three will be 0.
  8291. */
  8292. #if defined(SQLITE_OS_OTHER)
  8293. # if SQLITE_OS_OTHER==1
  8294. # undef SQLITE_OS_UNIX
  8295. # define SQLITE_OS_UNIX 0
  8296. # undef SQLITE_OS_WIN
  8297. # define SQLITE_OS_WIN 0
  8298. # undef SQLITE_OS_OS2
  8299. # define SQLITE_OS_OS2 0
  8300. # else
  8301. # undef SQLITE_OS_OTHER
  8302. # endif
  8303. #endif
  8304. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  8305. # define SQLITE_OS_OTHER 0
  8306. # ifndef SQLITE_OS_WIN
  8307. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  8308. # define SQLITE_OS_WIN 1
  8309. # define SQLITE_OS_UNIX 0
  8310. # define SQLITE_OS_OS2 0
  8311. # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
  8312. # define SQLITE_OS_WIN 0
  8313. # define SQLITE_OS_UNIX 0
  8314. # define SQLITE_OS_OS2 1
  8315. # else
  8316. # define SQLITE_OS_WIN 0
  8317. # define SQLITE_OS_UNIX 1
  8318. # define SQLITE_OS_OS2 0
  8319. # endif
  8320. # else
  8321. # define SQLITE_OS_UNIX 0
  8322. # define SQLITE_OS_OS2 0
  8323. # endif
  8324. #else
  8325. # ifndef SQLITE_OS_WIN
  8326. # define SQLITE_OS_WIN 0
  8327. # endif
  8328. #endif
  8329. /*
  8330. ** Determine if we are dealing with WindowsCE - which has a much
  8331. ** reduced API.
  8332. */
  8333. #if defined(_WIN32_WCE)
  8334. # define SQLITE_OS_WINCE 1
  8335. #else
  8336. # define SQLITE_OS_WINCE 0
  8337. #endif
  8338. /*
  8339. ** Define the maximum size of a temporary filename
  8340. */
  8341. #if SQLITE_OS_WIN
  8342. # include <windows.h>
  8343. # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
  8344. #elif SQLITE_OS_OS2
  8345. # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
  8346. # include <os2safe.h> /* has to be included before os2.h for linking to work */
  8347. # endif
  8348. # define INCL_DOSDATETIME
  8349. # define INCL_DOSFILEMGR
  8350. # define INCL_DOSERRORS
  8351. # define INCL_DOSMISC
  8352. # define INCL_DOSPROCESS
  8353. # define INCL_DOSMODULEMGR
  8354. # define INCL_DOSSEMAPHORES
  8355. # include <os2.h>
  8356. # include <uconv.h>
  8357. # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
  8358. #else
  8359. # define SQLITE_TEMPNAME_SIZE 200
  8360. #endif
  8361. /* If the SET_FULLSYNC macro is not defined above, then make it
  8362. ** a no-op
  8363. */
  8364. #ifndef SET_FULLSYNC
  8365. # define SET_FULLSYNC(x,y)
  8366. #endif
  8367. /*
  8368. ** The default size of a disk sector
  8369. */
  8370. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  8371. # define SQLITE_DEFAULT_SECTOR_SIZE 512
  8372. #endif
  8373. /*
  8374. ** Temporary files are named starting with this prefix followed by 16 random
  8375. ** alphanumeric characters, and no file extension. They are stored in the
  8376. ** OS's standard temporary file directory, and are deleted prior to exit.
  8377. ** If sqlite is being embedded in another program, you may wish to change the
  8378. ** prefix to reflect your program's name, so that if your program exits
  8379. ** prematurely, old temporary files can be easily identified. This can be done
  8380. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  8381. **
  8382. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  8383. ** Mcafee started using SQLite in their anti-virus product and it
  8384. ** started putting files with the "sqlite" name in the c:/temp folder.
  8385. ** This annoyed many windows users. Those users would then do a
  8386. ** Google search for "sqlite", find the telephone numbers of the
  8387. ** developers and call to wake them up at night and complain.
  8388. ** For this reason, the default name prefix is changed to be "sqlite"
  8389. ** spelled backwards. So the temp files are still identified, but
  8390. ** anybody smart enough to figure out the code is also likely smart
  8391. ** enough to know that calling the developer will not help get rid
  8392. ** of the file.
  8393. */
  8394. #ifndef SQLITE_TEMP_FILE_PREFIX
  8395. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  8396. #endif
  8397. /*
  8398. ** The following values may be passed as the second argument to
  8399. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  8400. **
  8401. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  8402. ** RESERVED: A single process may hold a RESERVED lock on a file at
  8403. ** any time. Other processes may hold and obtain new SHARED locks.
  8404. ** PENDING: A single process may hold a PENDING lock on a file at
  8405. ** any one time. Existing SHARED locks may persist, but no new
  8406. ** SHARED locks may be obtained by other processes.
  8407. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  8408. **
  8409. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  8410. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  8411. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  8412. ** sqlite3OsLock().
  8413. */
  8414. #define NO_LOCK 0
  8415. #define SHARED_LOCK 1
  8416. #define RESERVED_LOCK 2
  8417. #define PENDING_LOCK 3
  8418. #define EXCLUSIVE_LOCK 4
  8419. /*
  8420. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  8421. **
  8422. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  8423. ** those functions are not available. So we use only LockFile() and
  8424. ** UnlockFile().
  8425. **
  8426. ** LockFile() prevents not just writing but also reading by other processes.
  8427. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  8428. ** byte out of a specific range of bytes. The lock byte is obtained at
  8429. ** random so two separate readers can probably access the file at the
  8430. ** same time, unless they are unlucky and choose the same lock byte.
  8431. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  8432. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  8433. ** a single byte of the file that is designated as the reserved lock byte.
  8434. ** A PENDING_LOCK is obtained by locking a designated byte different from
  8435. ** the RESERVED_LOCK byte.
  8436. **
  8437. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  8438. ** which means we can use reader/writer locks. When reader/writer locks
  8439. ** are used, the lock is placed on the same range of bytes that is used
  8440. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  8441. ** will support two or more Win95 readers or two or more WinNT readers.
  8442. ** But a single Win95 reader will lock out all WinNT readers and a single
  8443. ** WinNT reader will lock out all other Win95 readers.
  8444. **
  8445. ** The following #defines specify the range of bytes used for locking.
  8446. ** SHARED_SIZE is the number of bytes available in the pool from which
  8447. ** a random byte is selected for a shared lock. The pool of bytes for
  8448. ** shared locks begins at SHARED_FIRST.
  8449. **
  8450. ** The same locking strategy and
  8451. ** byte ranges are used for Unix. This leaves open the possiblity of having
  8452. ** clients on win95, winNT, and unix all talking to the same shared file
  8453. ** and all locking correctly. To do so would require that samba (or whatever
  8454. ** tool is being used for file sharing) implements locks correctly between
  8455. ** windows and unix. I'm guessing that isn't likely to happen, but by
  8456. ** using the same locking range we are at least open to the possibility.
  8457. **
  8458. ** Locking in windows is manditory. For this reason, we cannot store
  8459. ** actual data in the bytes used for locking. The pager never allocates
  8460. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  8461. ** that all locks will fit on a single page even at the minimum page size.
  8462. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  8463. ** is set high so that we don't have to allocate an unused page except
  8464. ** for very large databases. But one should test the page skipping logic
  8465. ** by setting PENDING_BYTE low and running the entire regression suite.
  8466. **
  8467. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  8468. ** file format. Depending on how it is changed, you might not notice
  8469. ** the incompatibility right away, even running a full regression test.
  8470. ** The default location of PENDING_BYTE is the first byte past the
  8471. ** 1GB boundary.
  8472. **
  8473. */
  8474. #ifdef SQLITE_OMIT_WSD
  8475. # define PENDING_BYTE (0x40000000)
  8476. #else
  8477. # define PENDING_BYTE sqlite3PendingByte
  8478. #endif
  8479. #define RESERVED_BYTE (PENDING_BYTE+1)
  8480. #define SHARED_FIRST (PENDING_BYTE+2)
  8481. #define SHARED_SIZE 510
  8482. /*
  8483. ** Wrapper around OS specific sqlite3_os_init() function.
  8484. */
  8485. SQLITE_PRIVATE int sqlite3OsInit(void);
  8486. /*
  8487. ** Functions for accessing sqlite3_file methods
  8488. */
  8489. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  8490. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  8491. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  8492. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  8493. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  8494. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  8495. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  8496. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  8497. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  8498. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  8499. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  8500. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  8501. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  8502. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  8503. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  8504. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  8505. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  8506. /*
  8507. ** Functions for accessing sqlite3_vfs methods
  8508. */
  8509. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  8510. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  8511. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  8512. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  8513. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  8514. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  8515. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  8516. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  8517. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  8518. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  8519. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  8520. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  8521. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  8522. /*
  8523. ** Convenience functions for opening and closing files using
  8524. ** sqlite3_malloc() to obtain space for the file-handle structure.
  8525. */
  8526. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  8527. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  8528. #endif /* _SQLITE_OS_H_ */
  8529. /************** End of os.h **************************************************/
  8530. /************** Continuing where we left off in sqliteInt.h ******************/
  8531. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  8532. /************** Begin file mutex.h *******************************************/
  8533. /*
  8534. ** 2007 August 28
  8535. **
  8536. ** The author disclaims copyright to this source code. In place of
  8537. ** a legal notice, here is a blessing:
  8538. **
  8539. ** May you do good and not evil.
  8540. ** May you find forgiveness for yourself and forgive others.
  8541. ** May you share freely, never taking more than you give.
  8542. **
  8543. *************************************************************************
  8544. **
  8545. ** This file contains the common header for all mutex implementations.
  8546. ** The sqliteInt.h header #includes this file so that it is available
  8547. ** to all source files. We break it out in an effort to keep the code
  8548. ** better organized.
  8549. **
  8550. ** NOTE: source files should *not* #include this header file directly.
  8551. ** Source files should #include the sqliteInt.h file and let that file
  8552. ** include this one indirectly.
  8553. */
  8554. /*
  8555. ** Figure out what version of the code to use. The choices are
  8556. **
  8557. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  8558. ** mutexes implemention cannot be overridden
  8559. ** at start-time.
  8560. **
  8561. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  8562. ** mutual exclusion is provided. But this
  8563. ** implementation can be overridden at
  8564. ** start-time.
  8565. **
  8566. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  8567. **
  8568. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  8569. **
  8570. ** SQLITE_MUTEX_OS2 For multi-threaded applications on OS/2.
  8571. */
  8572. #if !SQLITE_THREADSAFE
  8573. # define SQLITE_MUTEX_OMIT
  8574. #endif
  8575. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  8576. # if SQLITE_OS_UNIX
  8577. # define SQLITE_MUTEX_PTHREADS
  8578. # elif SQLITE_OS_WIN
  8579. # define SQLITE_MUTEX_W32
  8580. # elif SQLITE_OS_OS2
  8581. # define SQLITE_MUTEX_OS2
  8582. # else
  8583. # define SQLITE_MUTEX_NOOP
  8584. # endif
  8585. #endif
  8586. #ifdef SQLITE_MUTEX_OMIT
  8587. /*
  8588. ** If this is a no-op implementation, implement everything as macros.
  8589. */
  8590. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  8591. #define sqlite3_mutex_free(X)
  8592. #define sqlite3_mutex_enter(X)
  8593. #define sqlite3_mutex_try(X) SQLITE_OK
  8594. #define sqlite3_mutex_leave(X)
  8595. #define sqlite3_mutex_held(X) ((void)(X),1)
  8596. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  8597. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  8598. #define sqlite3MutexInit() SQLITE_OK
  8599. #define sqlite3MutexEnd()
  8600. #endif /* defined(SQLITE_MUTEX_OMIT) */
  8601. /************** End of mutex.h ***********************************************/
  8602. /************** Continuing where we left off in sqliteInt.h ******************/
  8603. /*
  8604. ** Each database file to be accessed by the system is an instance
  8605. ** of the following structure. There are normally two of these structures
  8606. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  8607. ** aDb[1] is the database file used to hold temporary tables. Additional
  8608. ** databases may be attached.
  8609. */
  8610. struct Db {
  8611. char *zName; /* Name of this database */
  8612. Btree *pBt; /* The B*Tree structure for this database file */
  8613. u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
  8614. u8 safety_level; /* How aggressive at syncing data to disk */
  8615. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  8616. };
  8617. /*
  8618. ** An instance of the following structure stores a database schema.
  8619. **
  8620. ** Most Schema objects are associated with a Btree. The exception is
  8621. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  8622. ** In shared cache mode, a single Schema object can be shared by multiple
  8623. ** Btrees that refer to the same underlying BtShared object.
  8624. **
  8625. ** Schema objects are automatically deallocated when the last Btree that
  8626. ** references them is destroyed. The TEMP Schema is manually freed by
  8627. ** sqlite3_close().
  8628. *
  8629. ** A thread must be holding a mutex on the corresponding Btree in order
  8630. ** to access Schema content. This implies that the thread must also be
  8631. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  8632. ** For a TEMP Schema, on the connection mutex is required.
  8633. */
  8634. struct Schema {
  8635. int schema_cookie; /* Database schema version number for this file */
  8636. int iGeneration; /* Generation counter. Incremented with each change */
  8637. Hash tblHash; /* All tables indexed by name */
  8638. Hash idxHash; /* All (named) indices indexed by name */
  8639. Hash trigHash; /* All triggers indexed by name */
  8640. Hash fkeyHash; /* All foreign keys by referenced table name */
  8641. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  8642. u8 file_format; /* Schema format version for this file */
  8643. u8 enc; /* Text encoding used by this database */
  8644. u16 flags; /* Flags associated with this schema */
  8645. int cache_size; /* Number of pages to use in the cache */
  8646. };
  8647. /*
  8648. ** These macros can be used to test, set, or clear bits in the
  8649. ** Db.pSchema->flags field.
  8650. */
  8651. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  8652. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  8653. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  8654. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  8655. /*
  8656. ** Allowed values for the DB.pSchema->flags field.
  8657. **
  8658. ** The DB_SchemaLoaded flag is set after the database schema has been
  8659. ** read into internal hash tables.
  8660. **
  8661. ** DB_UnresetViews means that one or more views have column names that
  8662. ** have been filled out. If the schema changes, these column names might
  8663. ** changes and so the view will need to be reset.
  8664. */
  8665. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  8666. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  8667. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  8668. /*
  8669. ** The number of different kinds of things that can be limited
  8670. ** using the sqlite3_limit() interface.
  8671. */
  8672. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  8673. /*
  8674. ** Lookaside malloc is a set of fixed-size buffers that can be used
  8675. ** to satisfy small transient memory allocation requests for objects
  8676. ** associated with a particular database connection. The use of
  8677. ** lookaside malloc provides a significant performance enhancement
  8678. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  8679. ** SQL statements.
  8680. **
  8681. ** The Lookaside structure holds configuration information about the
  8682. ** lookaside malloc subsystem. Each available memory allocation in
  8683. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  8684. ** objects.
  8685. **
  8686. ** Lookaside allocations are only allowed for objects that are associated
  8687. ** with a particular database connection. Hence, schema information cannot
  8688. ** be stored in lookaside because in shared cache mode the schema information
  8689. ** is shared by multiple database connections. Therefore, while parsing
  8690. ** schema information, the Lookaside.bEnabled flag is cleared so that
  8691. ** lookaside allocations are not used to construct the schema objects.
  8692. */
  8693. struct Lookaside {
  8694. u16 sz; /* Size of each buffer in bytes */
  8695. u8 bEnabled; /* False to disable new lookaside allocations */
  8696. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  8697. int nOut; /* Number of buffers currently checked out */
  8698. int mxOut; /* Highwater mark for nOut */
  8699. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  8700. LookasideSlot *pFree; /* List of available buffers */
  8701. void *pStart; /* First byte of available memory space */
  8702. void *pEnd; /* First byte past end of available space */
  8703. };
  8704. struct LookasideSlot {
  8705. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  8706. };
  8707. /*
  8708. ** A hash table for function definitions.
  8709. **
  8710. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  8711. ** Collisions are on the FuncDef.pHash chain.
  8712. */
  8713. struct FuncDefHash {
  8714. FuncDef *a[23]; /* Hash table for functions */
  8715. };
  8716. /*
  8717. ** Each database connection is an instance of the following structure.
  8718. **
  8719. ** The sqlite.lastRowid records the last insert rowid generated by an
  8720. ** insert statement. Inserts on views do not affect its value. Each
  8721. ** trigger has its own context, so that lastRowid can be updated inside
  8722. ** triggers as usual. The previous value will be restored once the trigger
  8723. ** exits. Upon entering a before or instead of trigger, lastRowid is no
  8724. ** longer (since after version 2.8.12) reset to -1.
  8725. **
  8726. ** The sqlite.nChange does not count changes within triggers and keeps no
  8727. ** context. It is reset at start of sqlite3_exec.
  8728. ** The sqlite.lsChange represents the number of changes made by the last
  8729. ** insert, update, or delete statement. It remains constant throughout the
  8730. ** length of a statement and is then updated by OP_SetCounts. It keeps a
  8731. ** context stack just like lastRowid so that the count of changes
  8732. ** within a trigger is not seen outside the trigger. Changes to views do not
  8733. ** affect the value of lsChange.
  8734. ** The sqlite.csChange keeps track of the number of current changes (since
  8735. ** the last statement) and is used to update sqlite_lsChange.
  8736. **
  8737. ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
  8738. ** store the most recent error code and, if applicable, string. The
  8739. ** internal function sqlite3Error() is used to set these variables
  8740. ** consistently.
  8741. */
  8742. struct sqlite3 {
  8743. sqlite3_vfs *pVfs; /* OS Interface */
  8744. int nDb; /* Number of backends currently in use */
  8745. Db *aDb; /* All backends */
  8746. int flags; /* Miscellaneous flags. See below */
  8747. int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  8748. int errCode; /* Most recent error code (SQLITE_*) */
  8749. int errMask; /* & result codes with this before returning */
  8750. u8 autoCommit; /* The auto-commit flag. */
  8751. u8 temp_store; /* 1: file 2: memory 0: default */
  8752. u8 mallocFailed; /* True if we have seen a malloc failure */
  8753. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  8754. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  8755. u8 suppressErr; /* Do not issue error messages if true */
  8756. int nextPagesize; /* Pagesize after VACUUM if >0 */
  8757. int nTable; /* Number of tables in the database */
  8758. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  8759. i64 lastRowid; /* ROWID of most recent insert (see above) */
  8760. u32 magic; /* Magic number for detect library misuse */
  8761. int nChange; /* Value returned by sqlite3_changes() */
  8762. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  8763. sqlite3_mutex *mutex; /* Connection mutex */
  8764. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  8765. struct sqlite3InitInfo { /* Information used during initialization */
  8766. int iDb; /* When back is being initialized */
  8767. int newTnum; /* Rootpage of table being initialized */
  8768. u8 busy; /* TRUE if currently initializing */
  8769. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  8770. } init;
  8771. int nExtension; /* Number of loaded extensions */
  8772. void **aExtension; /* Array of shared library handles */
  8773. struct Vdbe *pVdbe; /* List of active virtual machines */
  8774. int activeVdbeCnt; /* Number of VDBEs currently executing */
  8775. int writeVdbeCnt; /* Number of active VDBEs that are writing */
  8776. int vdbeExecCnt; /* Number of nested calls to VdbeExec() */
  8777. void (*xTrace)(void*,const char*); /* Trace function */
  8778. void *pTraceArg; /* Argument to the trace function */
  8779. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  8780. void *pProfileArg; /* Argument to profile function */
  8781. void *pCommitArg; /* Argument to xCommitCallback() */
  8782. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  8783. void *pRollbackArg; /* Argument to xRollbackCallback() */
  8784. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  8785. void *pUpdateArg;
  8786. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  8787. #ifndef SQLITE_OMIT_WAL
  8788. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  8789. void *pWalArg;
  8790. #endif
  8791. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  8792. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  8793. void *pCollNeededArg;
  8794. sqlite3_value *pErr; /* Most recent error message */
  8795. char *zErrMsg; /* Most recent error message (UTF-8 encoded) */
  8796. char *zErrMsg16; /* Most recent error message (UTF-16 encoded) */
  8797. union {
  8798. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  8799. double notUsed1; /* Spacer */
  8800. } u1;
  8801. Lookaside lookaside; /* Lookaside malloc configuration */
  8802. #ifndef SQLITE_OMIT_AUTHORIZATION
  8803. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  8804. /* Access authorization function */
  8805. void *pAuthArg; /* 1st argument to the access auth function */
  8806. #endif
  8807. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  8808. int (*xProgress)(void *); /* The progress callback */
  8809. void *pProgressArg; /* Argument to the progress callback */
  8810. int nProgressOps; /* Number of opcodes for progress callback */
  8811. #endif
  8812. #ifndef SQLITE_OMIT_VIRTUALTABLE
  8813. Hash aModule; /* populated by sqlite3_create_module() */
  8814. Table *pVTab; /* vtab with active Connect/Create method */
  8815. VTable **aVTrans; /* Virtual tables with open transactions */
  8816. int nVTrans; /* Allocated size of aVTrans */
  8817. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  8818. #endif
  8819. FuncDefHash aFunc; /* Hash table of connection functions */
  8820. Hash aCollSeq; /* All collating sequences */
  8821. BusyHandler busyHandler; /* Busy callback */
  8822. int busyTimeout; /* Busy handler timeout, in msec */
  8823. Db aDbStatic[2]; /* Static space for the 2 default backends */
  8824. Savepoint *pSavepoint; /* List of active savepoints */
  8825. int nSavepoint; /* Number of non-transaction savepoints */
  8826. int nStatement; /* Number of nested statement-transactions */
  8827. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  8828. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  8829. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  8830. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  8831. /* The following variables are all protected by the STATIC_MASTER
  8832. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  8833. **
  8834. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  8835. ** unlock so that it can proceed.
  8836. **
  8837. ** When X.pBlockingConnection==Y, that means that something that X tried
  8838. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  8839. ** held by Y.
  8840. */
  8841. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  8842. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  8843. void *pUnlockArg; /* Argument to xUnlockNotify */
  8844. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  8845. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  8846. #endif
  8847. };
  8848. /*
  8849. ** A macro to discover the encoding of a database.
  8850. */
  8851. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  8852. /*
  8853. ** Possible values for the sqlite3.flags.
  8854. */
  8855. #define SQLITE_VdbeTrace 0x00000100 /* True to trace VDBE execution */
  8856. #define SQLITE_InternChanges 0x00000200 /* Uncommitted Hash table changes */
  8857. #define SQLITE_FullColNames 0x00000400 /* Show full column names on SELECT */
  8858. #define SQLITE_ShortColNames 0x00000800 /* Show short columns names */
  8859. #define SQLITE_CountRows 0x00001000 /* Count rows changed by INSERT, */
  8860. /* DELETE, or UPDATE and return */
  8861. /* the count using a callback. */
  8862. #define SQLITE_NullCallback 0x00002000 /* Invoke the callback once if the */
  8863. /* result set is empty */
  8864. #define SQLITE_SqlTrace 0x00004000 /* Debug print SQL as it executes */
  8865. #define SQLITE_VdbeListing 0x00008000 /* Debug listings of VDBE programs */
  8866. #define SQLITE_WriteSchema 0x00010000 /* OK to update SQLITE_MASTER */
  8867. #define SQLITE_NoReadlock 0x00020000 /* Readlocks are omitted when
  8868. ** accessing read-only databases */
  8869. #define SQLITE_IgnoreChecks 0x00040000 /* Do not enforce check constraints */
  8870. #define SQLITE_ReadUncommitted 0x0080000 /* For shared-cache mode */
  8871. #define SQLITE_LegacyFileFmt 0x00100000 /* Create new databases in format 1 */
  8872. #define SQLITE_FullFSync 0x00200000 /* Use full fsync on the backend */
  8873. #define SQLITE_CkptFullFSync 0x00400000 /* Use full fsync for checkpoint */
  8874. #define SQLITE_RecoveryMode 0x00800000 /* Ignore schema errors */
  8875. #define SQLITE_ReverseOrder 0x01000000 /* Reverse unordered SELECTs */
  8876. #define SQLITE_RecTriggers 0x02000000 /* Enable recursive triggers */
  8877. #define SQLITE_ForeignKeys 0x04000000 /* Enforce foreign key constraints */
  8878. #define SQLITE_AutoIndex 0x08000000 /* Enable automatic indexes */
  8879. #define SQLITE_PreferBuiltin 0x10000000 /* Preference to built-in funcs */
  8880. #define SQLITE_LoadExtension 0x20000000 /* Enable load_extension */
  8881. #define SQLITE_EnableTrigger 0x40000000 /* True to enable triggers */
  8882. /*
  8883. ** Bits of the sqlite3.flags field that are used by the
  8884. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
  8885. ** These must be the low-order bits of the flags field.
  8886. */
  8887. #define SQLITE_QueryFlattener 0x01 /* Disable query flattening */
  8888. #define SQLITE_ColumnCache 0x02 /* Disable the column cache */
  8889. #define SQLITE_IndexSort 0x04 /* Disable indexes for sorting */
  8890. #define SQLITE_IndexSearch 0x08 /* Disable indexes for searching */
  8891. #define SQLITE_IndexCover 0x10 /* Disable index covering table */
  8892. #define SQLITE_GroupByOrder 0x20 /* Disable GROUPBY cover of ORDERBY */
  8893. #define SQLITE_FactorOutConst 0x40 /* Disable factoring out constants */
  8894. #define SQLITE_OptMask 0xff /* Mask of all disablable opts */
  8895. /*
  8896. ** Possible values for the sqlite.magic field.
  8897. ** The numbers are obtained at random and have no special meaning, other
  8898. ** than being distinct from one another.
  8899. */
  8900. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  8901. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  8902. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  8903. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  8904. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  8905. /*
  8906. ** Each SQL function is defined by an instance of the following
  8907. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  8908. ** hash table. When multiple functions have the same name, the hash table
  8909. ** points to a linked list of these structures.
  8910. */
  8911. struct FuncDef {
  8912. i16 nArg; /* Number of arguments. -1 means unlimited */
  8913. u8 iPrefEnc; /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  8914. u8 flags; /* Some combination of SQLITE_FUNC_* */
  8915. void *pUserData; /* User data parameter */
  8916. FuncDef *pNext; /* Next function with same name */
  8917. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  8918. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  8919. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  8920. char *zName; /* SQL name of the function. */
  8921. FuncDef *pHash; /* Next with a different name but the same hash */
  8922. FuncDestructor *pDestructor; /* Reference counted destructor function */
  8923. };
  8924. /*
  8925. ** This structure encapsulates a user-function destructor callback (as
  8926. ** configured using create_function_v2()) and a reference counter. When
  8927. ** create_function_v2() is called to create a function with a destructor,
  8928. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  8929. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  8930. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  8931. ** member of each of the new FuncDef objects is set to point to the allocated
  8932. ** FuncDestructor.
  8933. **
  8934. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  8935. ** count on this object is decremented. When it reaches 0, the destructor
  8936. ** is invoked and the FuncDestructor structure freed.
  8937. */
  8938. struct FuncDestructor {
  8939. int nRef;
  8940. void (*xDestroy)(void *);
  8941. void *pUserData;
  8942. };
  8943. /*
  8944. ** Possible values for FuncDef.flags
  8945. */
  8946. #define SQLITE_FUNC_LIKE 0x01 /* Candidate for the LIKE optimization */
  8947. #define SQLITE_FUNC_CASE 0x02 /* Case-sensitive LIKE-type function */
  8948. #define SQLITE_FUNC_EPHEM 0x04 /* Ephemeral. Delete with VDBE */
  8949. #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
  8950. #define SQLITE_FUNC_PRIVATE 0x10 /* Allowed for internal use only */
  8951. #define SQLITE_FUNC_COUNT 0x20 /* Built-in count(*) aggregate */
  8952. #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
  8953. /*
  8954. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  8955. ** used to create the initializers for the FuncDef structures.
  8956. **
  8957. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  8958. ** Used to create a scalar function definition of a function zName
  8959. ** implemented by C function xFunc that accepts nArg arguments. The
  8960. ** value passed as iArg is cast to a (void*) and made available
  8961. ** as the user-data (sqlite3_user_data()) for the function. If
  8962. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  8963. **
  8964. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  8965. ** Used to create an aggregate function definition implemented by
  8966. ** the C functions xStep and xFinal. The first four parameters
  8967. ** are interpreted in the same way as the first 4 parameters to
  8968. ** FUNCTION().
  8969. **
  8970. ** LIKEFUNC(zName, nArg, pArg, flags)
  8971. ** Used to create a scalar function definition of a function zName
  8972. ** that accepts nArg arguments and is implemented by a call to C
  8973. ** function likeFunc. Argument pArg is cast to a (void *) and made
  8974. ** available as the function user-data (sqlite3_user_data()). The
  8975. ** FuncDef.flags variable is set to the value passed as the flags
  8976. ** parameter.
  8977. */
  8978. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  8979. {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
  8980. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  8981. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  8982. {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
  8983. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  8984. #define LIKEFUNC(zName, nArg, arg, flags) \
  8985. {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  8986. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  8987. {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
  8988. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  8989. /*
  8990. ** All current savepoints are stored in a linked list starting at
  8991. ** sqlite3.pSavepoint. The first element in the list is the most recently
  8992. ** opened savepoint. Savepoints are added to the list by the vdbe
  8993. ** OP_Savepoint instruction.
  8994. */
  8995. struct Savepoint {
  8996. char *zName; /* Savepoint name (nul-terminated) */
  8997. i64 nDeferredCons; /* Number of deferred fk violations */
  8998. Savepoint *pNext; /* Parent savepoint (if any) */
  8999. };
  9000. /*
  9001. ** The following are used as the second parameter to sqlite3Savepoint(),
  9002. ** and as the P1 argument to the OP_Savepoint instruction.
  9003. */
  9004. #define SAVEPOINT_BEGIN 0
  9005. #define SAVEPOINT_RELEASE 1
  9006. #define SAVEPOINT_ROLLBACK 2
  9007. /*
  9008. ** Each SQLite module (virtual table definition) is defined by an
  9009. ** instance of the following structure, stored in the sqlite3.aModule
  9010. ** hash table.
  9011. */
  9012. struct Module {
  9013. const sqlite3_module *pModule; /* Callback pointers */
  9014. const char *zName; /* Name passed to create_module() */
  9015. void *pAux; /* pAux passed to create_module() */
  9016. void (*xDestroy)(void *); /* Module destructor function */
  9017. };
  9018. /*
  9019. ** information about each column of an SQL table is held in an instance
  9020. ** of this structure.
  9021. */
  9022. struct Column {
  9023. char *zName; /* Name of this column */
  9024. Expr *pDflt; /* Default value of this column */
  9025. char *zDflt; /* Original text of the default value */
  9026. char *zType; /* Data type for this column */
  9027. char *zColl; /* Collating sequence. If NULL, use the default */
  9028. u8 notNull; /* True if there is a NOT NULL constraint */
  9029. u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
  9030. char affinity; /* One of the SQLITE_AFF_... values */
  9031. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9032. u8 isHidden; /* True if this column is 'hidden' */
  9033. #endif
  9034. };
  9035. /*
  9036. ** A "Collating Sequence" is defined by an instance of the following
  9037. ** structure. Conceptually, a collating sequence consists of a name and
  9038. ** a comparison routine that defines the order of that sequence.
  9039. **
  9040. ** There may two separate implementations of the collation function, one
  9041. ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
  9042. ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
  9043. ** native byte order. When a collation sequence is invoked, SQLite selects
  9044. ** the version that will require the least expensive encoding
  9045. ** translations, if any.
  9046. **
  9047. ** The CollSeq.pUser member variable is an extra parameter that passed in
  9048. ** as the first argument to the UTF-8 comparison function, xCmp.
  9049. ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
  9050. ** xCmp16.
  9051. **
  9052. ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
  9053. ** collating sequence is undefined. Indices built on an undefined
  9054. ** collating sequence may not be read or written.
  9055. */
  9056. struct CollSeq {
  9057. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  9058. u8 enc; /* Text encoding handled by xCmp() */
  9059. u8 type; /* One of the SQLITE_COLL_... values below */
  9060. void *pUser; /* First argument to xCmp() */
  9061. int (*xCmp)(void*,int, const void*, int, const void*);
  9062. void (*xDel)(void*); /* Destructor for pUser */
  9063. };
  9064. /*
  9065. ** Allowed values of CollSeq.type:
  9066. */
  9067. #define SQLITE_COLL_BINARY 1 /* The default memcmp() collating sequence */
  9068. #define SQLITE_COLL_NOCASE 2 /* The built-in NOCASE collating sequence */
  9069. #define SQLITE_COLL_REVERSE 3 /* The built-in REVERSE collating sequence */
  9070. #define SQLITE_COLL_USER 0 /* Any other user-defined collating sequence */
  9071. /*
  9072. ** A sort order can be either ASC or DESC.
  9073. */
  9074. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  9075. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  9076. /*
  9077. ** Column affinity types.
  9078. **
  9079. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  9080. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  9081. ** the speed a little by numbering the values consecutively.
  9082. **
  9083. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  9084. ** when multiple affinity types are concatenated into a string and
  9085. ** used as the P4 operand, they will be more readable.
  9086. **
  9087. ** Note also that the numeric types are grouped together so that testing
  9088. ** for a numeric type is a single comparison.
  9089. */
  9090. #define SQLITE_AFF_TEXT 'a'
  9091. #define SQLITE_AFF_NONE 'b'
  9092. #define SQLITE_AFF_NUMERIC 'c'
  9093. #define SQLITE_AFF_INTEGER 'd'
  9094. #define SQLITE_AFF_REAL 'e'
  9095. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  9096. /*
  9097. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  9098. ** affinity value.
  9099. */
  9100. #define SQLITE_AFF_MASK 0x67
  9101. /*
  9102. ** Additional bit values that can be ORed with an affinity without
  9103. ** changing the affinity.
  9104. */
  9105. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  9106. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  9107. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  9108. /*
  9109. ** An object of this type is created for each virtual table present in
  9110. ** the database schema.
  9111. **
  9112. ** If the database schema is shared, then there is one instance of this
  9113. ** structure for each database connection (sqlite3*) that uses the shared
  9114. ** schema. This is because each database connection requires its own unique
  9115. ** instance of the sqlite3_vtab* handle used to access the virtual table
  9116. ** implementation. sqlite3_vtab* handles can not be shared between
  9117. ** database connections, even when the rest of the in-memory database
  9118. ** schema is shared, as the implementation often stores the database
  9119. ** connection handle passed to it via the xConnect() or xCreate() method
  9120. ** during initialization internally. This database connection handle may
  9121. ** then be used by the virtual table implementation to access real tables
  9122. ** within the database. So that they appear as part of the callers
  9123. ** transaction, these accesses need to be made via the same database
  9124. ** connection as that used to execute SQL operations on the virtual table.
  9125. **
  9126. ** All VTable objects that correspond to a single table in a shared
  9127. ** database schema are initially stored in a linked-list pointed to by
  9128. ** the Table.pVTable member variable of the corresponding Table object.
  9129. ** When an sqlite3_prepare() operation is required to access the virtual
  9130. ** table, it searches the list for the VTable that corresponds to the
  9131. ** database connection doing the preparing so as to use the correct
  9132. ** sqlite3_vtab* handle in the compiled query.
  9133. **
  9134. ** When an in-memory Table object is deleted (for example when the
  9135. ** schema is being reloaded for some reason), the VTable objects are not
  9136. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  9137. ** immediately. Instead, they are moved from the Table.pVTable list to
  9138. ** another linked list headed by the sqlite3.pDisconnect member of the
  9139. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  9140. ** next time a statement is prepared using said sqlite3*. This is done
  9141. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  9142. ** Refer to comments above function sqlite3VtabUnlockList() for an
  9143. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  9144. ** list without holding the corresponding sqlite3.mutex mutex.
  9145. **
  9146. ** The memory for objects of this type is always allocated by
  9147. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  9148. ** the first argument.
  9149. */
  9150. struct VTable {
  9151. sqlite3 *db; /* Database connection associated with this table */
  9152. Module *pMod; /* Pointer to module implementation */
  9153. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  9154. int nRef; /* Number of pointers to this structure */
  9155. VTable *pNext; /* Next in linked list (see above) */
  9156. };
  9157. /*
  9158. ** Each SQL table is represented in memory by an instance of the
  9159. ** following structure.
  9160. **
  9161. ** Table.zName is the name of the table. The case of the original
  9162. ** CREATE TABLE statement is stored, but case is not significant for
  9163. ** comparisons.
  9164. **
  9165. ** Table.nCol is the number of columns in this table. Table.aCol is a
  9166. ** pointer to an array of Column structures, one for each column.
  9167. **
  9168. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  9169. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  9170. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  9171. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  9172. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  9173. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  9174. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  9175. **
  9176. ** Table.tnum is the page number for the root BTree page of the table in the
  9177. ** database file. If Table.iDb is the index of the database table backend
  9178. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  9179. ** holds temporary tables and indices. If TF_Ephemeral is set
  9180. ** then the table is stored in a file that is automatically deleted
  9181. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  9182. ** refers VDBE cursor number that holds the table open, not to the root
  9183. ** page number. Transient tables are used to hold the results of a
  9184. ** sub-query that appears instead of a real table name in the FROM clause
  9185. ** of a SELECT statement.
  9186. */
  9187. struct Table {
  9188. char *zName; /* Name of the table or view */
  9189. int iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  9190. int nCol; /* Number of columns in this table */
  9191. Column *aCol; /* Information about each column */
  9192. Index *pIndex; /* List of SQL indexes on this table. */
  9193. int tnum; /* Root BTree node for this table (see note above) */
  9194. unsigned nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  9195. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  9196. u16 nRef; /* Number of pointers to this Table */
  9197. u8 tabFlags; /* Mask of TF_* values */
  9198. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  9199. FKey *pFKey; /* Linked list of all foreign keys in this table */
  9200. char *zColAff; /* String defining the affinity of each column */
  9201. #ifndef SQLITE_OMIT_CHECK
  9202. Expr *pCheck; /* The AND of all CHECK constraints */
  9203. #endif
  9204. #ifndef SQLITE_OMIT_ALTERTABLE
  9205. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  9206. #endif
  9207. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9208. VTable *pVTable; /* List of VTable objects. */
  9209. int nModuleArg; /* Number of arguments to the module */
  9210. char **azModuleArg; /* Text of all module args. [0] is module name */
  9211. #endif
  9212. Trigger *pTrigger; /* List of triggers stored in pSchema */
  9213. Schema *pSchema; /* Schema that contains this table */
  9214. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  9215. };
  9216. /*
  9217. ** Allowed values for Tabe.tabFlags.
  9218. */
  9219. #define TF_Readonly 0x01 /* Read-only system table */
  9220. #define TF_Ephemeral 0x02 /* An ephemeral table */
  9221. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  9222. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  9223. #define TF_Virtual 0x10 /* Is a virtual table */
  9224. #define TF_NeedMetadata 0x20 /* aCol[].zType and aCol[].pColl missing */
  9225. /*
  9226. ** Test to see whether or not a table is a virtual table. This is
  9227. ** done as a macro so that it will be optimized out when virtual
  9228. ** table support is omitted from the build.
  9229. */
  9230. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9231. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  9232. # define IsHiddenColumn(X) ((X)->isHidden)
  9233. #else
  9234. # define IsVirtual(X) 0
  9235. # define IsHiddenColumn(X) 0
  9236. #endif
  9237. /*
  9238. ** Each foreign key constraint is an instance of the following structure.
  9239. **
  9240. ** A foreign key is associated with two tables. The "from" table is
  9241. ** the table that contains the REFERENCES clause that creates the foreign
  9242. ** key. The "to" table is the table that is named in the REFERENCES clause.
  9243. ** Consider this example:
  9244. **
  9245. ** CREATE TABLE ex1(
  9246. ** a INTEGER PRIMARY KEY,
  9247. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  9248. ** );
  9249. **
  9250. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  9251. **
  9252. ** Each REFERENCES clause generates an instance of the following structure
  9253. ** which is attached to the from-table. The to-table need not exist when
  9254. ** the from-table is created. The existence of the to-table is not checked.
  9255. */
  9256. struct FKey {
  9257. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  9258. FKey *pNextFrom; /* Next foreign key in pFrom */
  9259. char *zTo; /* Name of table that the key points to (aka: Parent) */
  9260. FKey *pNextTo; /* Next foreign key on table named zTo */
  9261. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  9262. int nCol; /* Number of columns in this key */
  9263. /* EV: R-30323-21917 */
  9264. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  9265. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  9266. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  9267. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  9268. int iFrom; /* Index of column in pFrom */
  9269. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  9270. } aCol[1]; /* One entry for each of nCol column s */
  9271. };
  9272. /*
  9273. ** SQLite supports many different ways to resolve a constraint
  9274. ** error. ROLLBACK processing means that a constraint violation
  9275. ** causes the operation in process to fail and for the current transaction
  9276. ** to be rolled back. ABORT processing means the operation in process
  9277. ** fails and any prior changes from that one operation are backed out,
  9278. ** but the transaction is not rolled back. FAIL processing means that
  9279. ** the operation in progress stops and returns an error code. But prior
  9280. ** changes due to the same operation are not backed out and no rollback
  9281. ** occurs. IGNORE means that the particular row that caused the constraint
  9282. ** error is not inserted or updated. Processing continues and no error
  9283. ** is returned. REPLACE means that preexisting database rows that caused
  9284. ** a UNIQUE constraint violation are removed so that the new insert or
  9285. ** update can proceed. Processing continues and no error is reported.
  9286. **
  9287. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  9288. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  9289. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  9290. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  9291. ** referenced table row is propagated into the row that holds the
  9292. ** foreign key.
  9293. **
  9294. ** The following symbolic values are used to record which type
  9295. ** of action to take.
  9296. */
  9297. #define OE_None 0 /* There is no constraint to check */
  9298. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  9299. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  9300. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  9301. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  9302. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  9303. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  9304. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  9305. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  9306. #define OE_Cascade 9 /* Cascade the changes */
  9307. #define OE_Default 99 /* Do whatever the default action is */
  9308. /*
  9309. ** An instance of the following structure is passed as the first
  9310. ** argument to sqlite3VdbeKeyCompare and is used to control the
  9311. ** comparison of the two index keys.
  9312. */
  9313. struct KeyInfo {
  9314. sqlite3 *db; /* The database connection */
  9315. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  9316. u16 nField; /* Number of entries in aColl[] */
  9317. u8 *aSortOrder; /* Sort order for each column. May be NULL */
  9318. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  9319. };
  9320. /*
  9321. ** An instance of the following structure holds information about a
  9322. ** single index record that has already been parsed out into individual
  9323. ** values.
  9324. **
  9325. ** A record is an object that contains one or more fields of data.
  9326. ** Records are used to store the content of a table row and to store
  9327. ** the key of an index. A blob encoding of a record is created by
  9328. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  9329. ** OP_Column opcode.
  9330. **
  9331. ** This structure holds a record that has already been disassembled
  9332. ** into its constituent fields.
  9333. */
  9334. struct UnpackedRecord {
  9335. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  9336. u16 nField; /* Number of entries in apMem[] */
  9337. u16 flags; /* Boolean settings. UNPACKED_... below */
  9338. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  9339. Mem *aMem; /* Values */
  9340. };
  9341. /*
  9342. ** Allowed values of UnpackedRecord.flags
  9343. */
  9344. #define UNPACKED_NEED_FREE 0x0001 /* Memory is from sqlite3Malloc() */
  9345. #define UNPACKED_NEED_DESTROY 0x0002 /* apMem[]s should all be destroyed */
  9346. #define UNPACKED_IGNORE_ROWID 0x0004 /* Ignore trailing rowid on key1 */
  9347. #define UNPACKED_INCRKEY 0x0008 /* Make this key an epsilon larger */
  9348. #define UNPACKED_PREFIX_MATCH 0x0010 /* A prefix match is considered OK */
  9349. #define UNPACKED_PREFIX_SEARCH 0x0020 /* A prefix match is considered OK */
  9350. /*
  9351. ** Each SQL index is represented in memory by an
  9352. ** instance of the following structure.
  9353. **
  9354. ** The columns of the table that are to be indexed are described
  9355. ** by the aiColumn[] field of this structure. For example, suppose
  9356. ** we have the following table and index:
  9357. **
  9358. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  9359. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  9360. **
  9361. ** In the Table structure describing Ex1, nCol==3 because there are
  9362. ** three columns in the table. In the Index structure describing
  9363. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  9364. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  9365. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  9366. ** The second column to be indexed (c1) has an index of 0 in
  9367. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  9368. **
  9369. ** The Index.onError field determines whether or not the indexed columns
  9370. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  9371. ** it means this is not a unique index. Otherwise it is a unique index
  9372. ** and the value of Index.onError indicate the which conflict resolution
  9373. ** algorithm to employ whenever an attempt is made to insert a non-unique
  9374. ** element.
  9375. */
  9376. struct Index {
  9377. char *zName; /* Name of this index */
  9378. int nColumn; /* Number of columns in the table used by this index */
  9379. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  9380. unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
  9381. Table *pTable; /* The SQL table being indexed */
  9382. int tnum; /* Page containing root of this index in database file */
  9383. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  9384. u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
  9385. u8 bUnordered; /* Use this index for == or IN queries only */
  9386. char *zColAff; /* String defining the affinity of each column */
  9387. Index *pNext; /* The next index associated with the same table */
  9388. Schema *pSchema; /* Schema containing this index */
  9389. u8 *aSortOrder; /* Array of size Index.nColumn. True==DESC, False==ASC */
  9390. char **azColl; /* Array of collation sequence names for index */
  9391. IndexSample *aSample; /* Array of SQLITE_INDEX_SAMPLES samples */
  9392. };
  9393. /*
  9394. ** Each sample stored in the sqlite_stat2 table is represented in memory
  9395. ** using a structure of this type.
  9396. */
  9397. struct IndexSample {
  9398. union {
  9399. char *z; /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
  9400. double r; /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
  9401. } u;
  9402. u8 eType; /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
  9403. u8 nByte; /* Size in byte of text or blob. */
  9404. };
  9405. /*
  9406. ** Each token coming out of the lexer is an instance of
  9407. ** this structure. Tokens are also used as part of an expression.
  9408. **
  9409. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  9410. ** may contain random values. Do not make any assumptions about Token.dyn
  9411. ** and Token.n when Token.z==0.
  9412. */
  9413. struct Token {
  9414. const char *z; /* Text of the token. Not NULL-terminated! */
  9415. unsigned int n; /* Number of characters in this token */
  9416. };
  9417. /*
  9418. ** An instance of this structure contains information needed to generate
  9419. ** code for a SELECT that contains aggregate functions.
  9420. **
  9421. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  9422. ** pointer to this structure. The Expr.iColumn field is the index in
  9423. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  9424. ** code for that node.
  9425. **
  9426. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  9427. ** original Select structure that describes the SELECT statement. These
  9428. ** fields do not need to be freed when deallocating the AggInfo structure.
  9429. */
  9430. struct AggInfo {
  9431. u8 directMode; /* Direct rendering mode means take data directly
  9432. ** from source tables rather than from accumulators */
  9433. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  9434. ** than the source table */
  9435. int sortingIdx; /* Cursor number of the sorting index */
  9436. ExprList *pGroupBy; /* The group by clause */
  9437. int nSortingColumn; /* Number of columns in the sorting index */
  9438. struct AggInfo_col { /* For each column used in source tables */
  9439. Table *pTab; /* Source table */
  9440. int iTable; /* Cursor number of the source table */
  9441. int iColumn; /* Column number within the source table */
  9442. int iSorterColumn; /* Column number in the sorting index */
  9443. int iMem; /* Memory location that acts as accumulator */
  9444. Expr *pExpr; /* The original expression */
  9445. } *aCol;
  9446. int nColumn; /* Number of used entries in aCol[] */
  9447. int nColumnAlloc; /* Number of slots allocated for aCol[] */
  9448. int nAccumulator; /* Number of columns that show through to the output.
  9449. ** Additional columns are used only as parameters to
  9450. ** aggregate functions */
  9451. struct AggInfo_func { /* For each aggregate function */
  9452. Expr *pExpr; /* Expression encoding the function */
  9453. FuncDef *pFunc; /* The aggregate function implementation */
  9454. int iMem; /* Memory location that acts as accumulator */
  9455. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  9456. } *aFunc;
  9457. int nFunc; /* Number of entries in aFunc[] */
  9458. int nFuncAlloc; /* Number of slots allocated for aFunc[] */
  9459. };
  9460. /*
  9461. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  9462. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  9463. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  9464. ** it uses less memory in the Expr object, which is a big memory user
  9465. ** in systems with lots of prepared statements. And few applications
  9466. ** need more than about 10 or 20 variables. But some extreme users want
  9467. ** to have prepared statements with over 32767 variables, and for them
  9468. ** the option is available (at compile-time).
  9469. */
  9470. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  9471. typedef i16 ynVar;
  9472. #else
  9473. typedef int ynVar;
  9474. #endif
  9475. /*
  9476. ** Each node of an expression in the parse tree is an instance
  9477. ** of this structure.
  9478. **
  9479. ** Expr.op is the opcode. The integer parser token codes are reused
  9480. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  9481. ** code representing the ">=" operator. This same integer code is reused
  9482. ** to represent the greater-than-or-equal-to operator in the expression
  9483. ** tree.
  9484. **
  9485. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  9486. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  9487. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  9488. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  9489. ** then Expr.token contains the name of the function.
  9490. **
  9491. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  9492. ** binary operator. Either or both may be NULL.
  9493. **
  9494. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  9495. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  9496. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  9497. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  9498. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  9499. ** valid.
  9500. **
  9501. ** An expression of the form ID or ID.ID refers to a column in a table.
  9502. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  9503. ** the integer cursor number of a VDBE cursor pointing to that table and
  9504. ** Expr.iColumn is the column number for the specific column. If the
  9505. ** expression is used as a result in an aggregate SELECT, then the
  9506. ** value is also stored in the Expr.iAgg column in the aggregate so that
  9507. ** it can be accessed after all aggregates are computed.
  9508. **
  9509. ** If the expression is an unbound variable marker (a question mark
  9510. ** character '?' in the original SQL) then the Expr.iTable holds the index
  9511. ** number for that variable.
  9512. **
  9513. ** If the expression is a subquery then Expr.iColumn holds an integer
  9514. ** register number containing the result of the subquery. If the
  9515. ** subquery gives a constant result, then iTable is -1. If the subquery
  9516. ** gives a different answer at different times during statement processing
  9517. ** then iTable is the address of a subroutine that computes the subquery.
  9518. **
  9519. ** If the Expr is of type OP_Column, and the table it is selecting from
  9520. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  9521. ** corresponding table definition.
  9522. **
  9523. ** ALLOCATION NOTES:
  9524. **
  9525. ** Expr objects can use a lot of memory space in database schema. To
  9526. ** help reduce memory requirements, sometimes an Expr object will be
  9527. ** truncated. And to reduce the number of memory allocations, sometimes
  9528. ** two or more Expr objects will be stored in a single memory allocation,
  9529. ** together with Expr.zToken strings.
  9530. **
  9531. ** If the EP_Reduced and EP_TokenOnly flags are set when
  9532. ** an Expr object is truncated. When EP_Reduced is set, then all
  9533. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  9534. ** are contained within the same memory allocation. Note, however, that
  9535. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  9536. ** allocated, regardless of whether or not EP_Reduced is set.
  9537. */
  9538. struct Expr {
  9539. u8 op; /* Operation performed by this node */
  9540. char affinity; /* The affinity of the column or 0 if not a column */
  9541. u16 flags; /* Various flags. EP_* See below */
  9542. union {
  9543. char *zToken; /* Token value. Zero terminated and dequoted */
  9544. int iValue; /* Non-negative integer value if EP_IntValue */
  9545. } u;
  9546. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  9547. ** space is allocated for the fields below this point. An attempt to
  9548. ** access them will result in a segfault or malfunction.
  9549. *********************************************************************/
  9550. Expr *pLeft; /* Left subnode */
  9551. Expr *pRight; /* Right subnode */
  9552. union {
  9553. ExprList *pList; /* Function arguments or in "<expr> IN (<expr-list)" */
  9554. Select *pSelect; /* Used for sub-selects and "<expr> IN (<select>)" */
  9555. } x;
  9556. CollSeq *pColl; /* The collation type of the column or 0 */
  9557. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  9558. ** space is allocated for the fields below this point. An attempt to
  9559. ** access them will result in a segfault or malfunction.
  9560. *********************************************************************/
  9561. int iTable; /* TK_COLUMN: cursor number of table holding column
  9562. ** TK_REGISTER: register number
  9563. ** TK_TRIGGER: 1 -> new, 0 -> old */
  9564. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  9565. ** TK_VARIABLE: variable number (always >= 1). */
  9566. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  9567. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  9568. u8 flags2; /* Second set of flags. EP2_... */
  9569. u8 op2; /* If a TK_REGISTER, the original value of Expr.op */
  9570. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  9571. Table *pTab; /* Table for TK_COLUMN expressions. */
  9572. #if SQLITE_MAX_EXPR_DEPTH>0
  9573. int nHeight; /* Height of the tree headed by this node */
  9574. #endif
  9575. };
  9576. /*
  9577. ** The following are the meanings of bits in the Expr.flags field.
  9578. */
  9579. #define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
  9580. #define EP_Agg 0x0002 /* Contains one or more aggregate functions */
  9581. #define EP_Resolved 0x0004 /* IDs have been resolved to COLUMNs */
  9582. #define EP_Error 0x0008 /* Expression contains one or more errors */
  9583. #define EP_Distinct 0x0010 /* Aggregate function with DISTINCT keyword */
  9584. #define EP_VarSelect 0x0020 /* pSelect is correlated, not constant */
  9585. #define EP_DblQuoted 0x0040 /* token.z was originally in "..." */
  9586. #define EP_InfixFunc 0x0080 /* True for an infix function: LIKE, GLOB, etc */
  9587. #define EP_ExpCollate 0x0100 /* Collating sequence specified explicitly */
  9588. #define EP_FixedDest 0x0200 /* Result needed in a specific register */
  9589. #define EP_IntValue 0x0400 /* Integer value contained in u.iValue */
  9590. #define EP_xIsSelect 0x0800 /* x.pSelect is valid (otherwise x.pList is) */
  9591. #define EP_Reduced 0x1000 /* Expr struct is EXPR_REDUCEDSIZE bytes only */
  9592. #define EP_TokenOnly 0x2000 /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
  9593. #define EP_Static 0x4000 /* Held in memory not obtained from malloc() */
  9594. /*
  9595. ** The following are the meanings of bits in the Expr.flags2 field.
  9596. */
  9597. #define EP2_MallocedToken 0x0001 /* Need to sqlite3DbFree() Expr.zToken */
  9598. #define EP2_Irreducible 0x0002 /* Cannot EXPRDUP_REDUCE this Expr */
  9599. /*
  9600. ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
  9601. ** flag on an expression structure. This flag is used for VV&A only. The
  9602. ** routine is implemented as a macro that only works when in debugging mode,
  9603. ** so as not to burden production code.
  9604. */
  9605. #ifdef SQLITE_DEBUG
  9606. # define ExprSetIrreducible(X) (X)->flags2 |= EP2_Irreducible
  9607. #else
  9608. # define ExprSetIrreducible(X)
  9609. #endif
  9610. /*
  9611. ** These macros can be used to test, set, or clear bits in the
  9612. ** Expr.flags field.
  9613. */
  9614. #define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
  9615. #define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
  9616. #define ExprSetProperty(E,P) (E)->flags|=(P)
  9617. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  9618. /*
  9619. ** Macros to determine the number of bytes required by a normal Expr
  9620. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  9621. ** and an Expr struct with the EP_TokenOnly flag set.
  9622. */
  9623. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  9624. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  9625. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  9626. /*
  9627. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  9628. ** above sqlite3ExprDup() for details.
  9629. */
  9630. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  9631. /*
  9632. ** A list of expressions. Each expression may optionally have a
  9633. ** name. An expr/name combination can be used in several ways, such
  9634. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  9635. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  9636. ** also be used as the argument to a function, in which case the a.zName
  9637. ** field is not used.
  9638. */
  9639. struct ExprList {
  9640. int nExpr; /* Number of expressions on the list */
  9641. int nAlloc; /* Number of entries allocated below */
  9642. int iECursor; /* VDBE Cursor associated with this ExprList */
  9643. struct ExprList_item {
  9644. Expr *pExpr; /* The list of expressions */
  9645. char *zName; /* Token associated with this expression */
  9646. char *zSpan; /* Original text of the expression */
  9647. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  9648. u8 done; /* A flag to indicate when processing is finished */
  9649. u16 iCol; /* For ORDER BY, column number in result set */
  9650. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  9651. } *a; /* One entry for each expression */
  9652. };
  9653. /*
  9654. ** An instance of this structure is used by the parser to record both
  9655. ** the parse tree for an expression and the span of input text for an
  9656. ** expression.
  9657. */
  9658. struct ExprSpan {
  9659. Expr *pExpr; /* The expression parse tree */
  9660. const char *zStart; /* First character of input text */
  9661. const char *zEnd; /* One character past the end of input text */
  9662. };
  9663. /*
  9664. ** An instance of this structure can hold a simple list of identifiers,
  9665. ** such as the list "a,b,c" in the following statements:
  9666. **
  9667. ** INSERT INTO t(a,b,c) VALUES ...;
  9668. ** CREATE INDEX idx ON t(a,b,c);
  9669. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  9670. **
  9671. ** The IdList.a.idx field is used when the IdList represents the list of
  9672. ** column names after a table name in an INSERT statement. In the statement
  9673. **
  9674. ** INSERT INTO t(a,b,c) ...
  9675. **
  9676. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  9677. */
  9678. struct IdList {
  9679. struct IdList_item {
  9680. char *zName; /* Name of the identifier */
  9681. int idx; /* Index in some Table.aCol[] of a column named zName */
  9682. } *a;
  9683. int nId; /* Number of identifiers on the list */
  9684. int nAlloc; /* Number of entries allocated for a[] below */
  9685. };
  9686. /*
  9687. ** The bitmask datatype defined below is used for various optimizations.
  9688. **
  9689. ** Changing this from a 64-bit to a 32-bit type limits the number of
  9690. ** tables in a join to 32 instead of 64. But it also reduces the size
  9691. ** of the library by 738 bytes on ix86.
  9692. */
  9693. typedef u64 Bitmask;
  9694. /*
  9695. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  9696. */
  9697. #define BMS ((int)(sizeof(Bitmask)*8))
  9698. /*
  9699. ** The following structure describes the FROM clause of a SELECT statement.
  9700. ** Each table or subquery in the FROM clause is a separate element of
  9701. ** the SrcList.a[] array.
  9702. **
  9703. ** With the addition of multiple database support, the following structure
  9704. ** can also be used to describe a particular table such as the table that
  9705. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  9706. ** such a table must be a simple name: ID. But in SQLite, the table can
  9707. ** now be identified by a database name, a dot, then the table name: ID.ID.
  9708. **
  9709. ** The jointype starts out showing the join type between the current table
  9710. ** and the next table on the list. The parser builds the list this way.
  9711. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  9712. ** jointype expresses the join between the table and the previous table.
  9713. **
  9714. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  9715. ** contains more than 63 columns and the 64-th or later column is used.
  9716. */
  9717. struct SrcList {
  9718. i16 nSrc; /* Number of tables or subqueries in the FROM clause */
  9719. i16 nAlloc; /* Number of entries allocated in a[] below */
  9720. struct SrcList_item {
  9721. char *zDatabase; /* Name of database holding this table */
  9722. char *zName; /* Name of the table */
  9723. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  9724. Table *pTab; /* An SQL table corresponding to zName */
  9725. Select *pSelect; /* A SELECT statement used in place of a table name */
  9726. u8 isPopulated; /* Temporary table associated with SELECT is populated */
  9727. u8 jointype; /* Type of join between this able and the previous */
  9728. u8 notIndexed; /* True if there is a NOT INDEXED clause */
  9729. #ifndef SQLITE_OMIT_EXPLAIN
  9730. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  9731. #endif
  9732. int iCursor; /* The VDBE cursor number used to access this table */
  9733. Expr *pOn; /* The ON clause of a join */
  9734. IdList *pUsing; /* The USING clause of a join */
  9735. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  9736. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  9737. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  9738. } a[1]; /* One entry for each identifier on the list */
  9739. };
  9740. /*
  9741. ** Permitted values of the SrcList.a.jointype field
  9742. */
  9743. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  9744. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  9745. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  9746. #define JT_LEFT 0x0008 /* Left outer join */
  9747. #define JT_RIGHT 0x0010 /* Right outer join */
  9748. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  9749. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  9750. /*
  9751. ** A WherePlan object holds information that describes a lookup
  9752. ** strategy.
  9753. **
  9754. ** This object is intended to be opaque outside of the where.c module.
  9755. ** It is included here only so that that compiler will know how big it
  9756. ** is. None of the fields in this object should be used outside of
  9757. ** the where.c module.
  9758. **
  9759. ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
  9760. ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true. And pVtabIdx
  9761. ** is only used when wsFlags&WHERE_VIRTUALTABLE is true. It is never the
  9762. ** case that more than one of these conditions is true.
  9763. */
  9764. struct WherePlan {
  9765. u32 wsFlags; /* WHERE_* flags that describe the strategy */
  9766. u32 nEq; /* Number of == constraints */
  9767. double nRow; /* Estimated number of rows (for EQP) */
  9768. union {
  9769. Index *pIdx; /* Index when WHERE_INDEXED is true */
  9770. struct WhereTerm *pTerm; /* WHERE clause term for OR-search */
  9771. sqlite3_index_info *pVtabIdx; /* Virtual table index to use */
  9772. } u;
  9773. };
  9774. /*
  9775. ** For each nested loop in a WHERE clause implementation, the WhereInfo
  9776. ** structure contains a single instance of this structure. This structure
  9777. ** is intended to be private the the where.c module and should not be
  9778. ** access or modified by other modules.
  9779. **
  9780. ** The pIdxInfo field is used to help pick the best index on a
  9781. ** virtual table. The pIdxInfo pointer contains indexing
  9782. ** information for the i-th table in the FROM clause before reordering.
  9783. ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
  9784. ** All other information in the i-th WhereLevel object for the i-th table
  9785. ** after FROM clause ordering.
  9786. */
  9787. struct WhereLevel {
  9788. WherePlan plan; /* query plan for this element of the FROM clause */
  9789. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  9790. int iTabCur; /* The VDBE cursor used to access the table */
  9791. int iIdxCur; /* The VDBE cursor used to access pIdx */
  9792. int addrBrk; /* Jump here to break out of the loop */
  9793. int addrNxt; /* Jump here to start the next IN combination */
  9794. int addrCont; /* Jump here to continue with the next loop cycle */
  9795. int addrFirst; /* First instruction of interior of the loop */
  9796. u8 iFrom; /* Which entry in the FROM clause */
  9797. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  9798. int p1, p2; /* Operands of the opcode used to ends the loop */
  9799. union { /* Information that depends on plan.wsFlags */
  9800. struct {
  9801. int nIn; /* Number of entries in aInLoop[] */
  9802. struct InLoop {
  9803. int iCur; /* The VDBE cursor used by this IN operator */
  9804. int addrInTop; /* Top of the IN loop */
  9805. } *aInLoop; /* Information about each nested IN operator */
  9806. } in; /* Used when plan.wsFlags&WHERE_IN_ABLE */
  9807. } u;
  9808. /* The following field is really not part of the current level. But
  9809. ** we need a place to cache virtual table index information for each
  9810. ** virtual table in the FROM clause and the WhereLevel structure is
  9811. ** a convenient place since there is one WhereLevel for each FROM clause
  9812. ** element.
  9813. */
  9814. sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */
  9815. };
  9816. /*
  9817. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  9818. ** and the WhereInfo.wctrlFlags member.
  9819. */
  9820. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  9821. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  9822. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  9823. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  9824. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  9825. #define WHERE_OMIT_OPEN 0x0010 /* Table cursors are already open */
  9826. #define WHERE_OMIT_CLOSE 0x0020 /* Omit close of table & index cursors */
  9827. #define WHERE_FORCE_TABLE 0x0040 /* Do not use an index-only search */
  9828. #define WHERE_ONETABLE_ONLY 0x0080 /* Only code the 1st table in pTabList */
  9829. /*
  9830. ** The WHERE clause processing routine has two halves. The
  9831. ** first part does the start of the WHERE loop and the second
  9832. ** half does the tail of the WHERE loop. An instance of
  9833. ** this structure is returned by the first half and passed
  9834. ** into the second half to give some continuity.
  9835. */
  9836. struct WhereInfo {
  9837. Parse *pParse; /* Parsing and code generating context */
  9838. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  9839. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE or DELETE */
  9840. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  9841. SrcList *pTabList; /* List of tables in the join */
  9842. int iTop; /* The very beginning of the WHERE loop */
  9843. int iContinue; /* Jump here to continue with next record */
  9844. int iBreak; /* Jump here to break out of the loop */
  9845. int nLevel; /* Number of nested loop */
  9846. struct WhereClause *pWC; /* Decomposition of the WHERE clause */
  9847. double savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  9848. double nRowOut; /* Estimated number of output rows */
  9849. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  9850. };
  9851. /*
  9852. ** A NameContext defines a context in which to resolve table and column
  9853. ** names. The context consists of a list of tables (the pSrcList) field and
  9854. ** a list of named expression (pEList). The named expression list may
  9855. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  9856. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  9857. ** pEList corresponds to the result set of a SELECT and is NULL for
  9858. ** other statements.
  9859. **
  9860. ** NameContexts can be nested. When resolving names, the inner-most
  9861. ** context is searched first. If no match is found, the next outer
  9862. ** context is checked. If there is still no match, the next context
  9863. ** is checked. This process continues until either a match is found
  9864. ** or all contexts are check. When a match is found, the nRef member of
  9865. ** the context containing the match is incremented.
  9866. **
  9867. ** Each subquery gets a new NameContext. The pNext field points to the
  9868. ** NameContext in the parent query. Thus the process of scanning the
  9869. ** NameContext list corresponds to searching through successively outer
  9870. ** subqueries looking for a match.
  9871. */
  9872. struct NameContext {
  9873. Parse *pParse; /* The parser */
  9874. SrcList *pSrcList; /* One or more tables used to resolve names */
  9875. ExprList *pEList; /* Optional list of named expressions */
  9876. int nRef; /* Number of names resolved by this context */
  9877. int nErr; /* Number of errors encountered while resolving names */
  9878. u8 allowAgg; /* Aggregate functions allowed here */
  9879. u8 hasAgg; /* True if aggregates are seen */
  9880. u8 isCheck; /* True if resolving names in a CHECK constraint */
  9881. int nDepth; /* Depth of subquery recursion. 1 for no recursion */
  9882. AggInfo *pAggInfo; /* Information about aggregates at this level */
  9883. NameContext *pNext; /* Next outer name context. NULL for outermost */
  9884. };
  9885. /*
  9886. ** An instance of the following structure contains all information
  9887. ** needed to generate code for a single SELECT statement.
  9888. **
  9889. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  9890. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  9891. ** limit and nOffset to the value of the offset (or 0 if there is not
  9892. ** offset). But later on, nLimit and nOffset become the memory locations
  9893. ** in the VDBE that record the limit and offset counters.
  9894. **
  9895. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  9896. ** These addresses must be stored so that we can go back and fill in
  9897. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  9898. ** the number of columns in P2 can be computed at the same time
  9899. ** as the OP_OpenEphm instruction is coded because not
  9900. ** enough information about the compound query is known at that point.
  9901. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  9902. ** for the result set. The KeyInfo for addrOpenTran[2] contains collating
  9903. ** sequences for the ORDER BY clause.
  9904. */
  9905. struct Select {
  9906. ExprList *pEList; /* The fields of the result */
  9907. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  9908. char affinity; /* MakeRecord with this affinity for SRT_Set */
  9909. u16 selFlags; /* Various SF_* values */
  9910. SrcList *pSrc; /* The FROM clause */
  9911. Expr *pWhere; /* The WHERE clause */
  9912. ExprList *pGroupBy; /* The GROUP BY clause */
  9913. Expr *pHaving; /* The HAVING clause */
  9914. ExprList *pOrderBy; /* The ORDER BY clause */
  9915. Select *pPrior; /* Prior select in a compound select statement */
  9916. Select *pNext; /* Next select to the left in a compound */
  9917. Select *pRightmost; /* Right-most select in a compound select statement */
  9918. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  9919. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  9920. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  9921. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  9922. double nSelectRow; /* Estimated number of result rows */
  9923. };
  9924. /*
  9925. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  9926. ** "Select Flag".
  9927. */
  9928. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  9929. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  9930. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  9931. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  9932. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  9933. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  9934. /*
  9935. ** The results of a select can be distributed in several ways. The
  9936. ** "SRT" prefix means "SELECT Result Type".
  9937. */
  9938. #define SRT_Union 1 /* Store result as keys in an index */
  9939. #define SRT_Except 2 /* Remove result from a UNION index */
  9940. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  9941. #define SRT_Discard 4 /* Do not save the results anywhere */
  9942. /* The ORDER BY clause is ignored for all of the above */
  9943. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  9944. #define SRT_Output 5 /* Output each row of result */
  9945. #define SRT_Mem 6 /* Store result in a memory cell */
  9946. #define SRT_Set 7 /* Store results as keys in an index */
  9947. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  9948. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  9949. #define SRT_Coroutine 10 /* Generate a single row of result */
  9950. /*
  9951. ** A structure used to customize the behavior of sqlite3Select(). See
  9952. ** comments above sqlite3Select() for details.
  9953. */
  9954. typedef struct SelectDest SelectDest;
  9955. struct SelectDest {
  9956. u8 eDest; /* How to dispose of the results */
  9957. u8 affinity; /* Affinity used when eDest==SRT_Set */
  9958. int iParm; /* A parameter used by the eDest disposal method */
  9959. int iMem; /* Base register where results are written */
  9960. int nMem; /* Number of registers allocated */
  9961. };
  9962. /*
  9963. ** During code generation of statements that do inserts into AUTOINCREMENT
  9964. ** tables, the following information is attached to the Table.u.autoInc.p
  9965. ** pointer of each autoincrement table to record some side information that
  9966. ** the code generator needs. We have to keep per-table autoincrement
  9967. ** information in case inserts are down within triggers. Triggers do not
  9968. ** normally coordinate their activities, but we do need to coordinate the
  9969. ** loading and saving of autoincrement information.
  9970. */
  9971. struct AutoincInfo {
  9972. AutoincInfo *pNext; /* Next info block in a list of them all */
  9973. Table *pTab; /* Table this info block refers to */
  9974. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  9975. int regCtr; /* Memory register holding the rowid counter */
  9976. };
  9977. /*
  9978. ** Size of the column cache
  9979. */
  9980. #ifndef SQLITE_N_COLCACHE
  9981. # define SQLITE_N_COLCACHE 10
  9982. #endif
  9983. /*
  9984. ** At least one instance of the following structure is created for each
  9985. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  9986. ** statement. All such objects are stored in the linked list headed at
  9987. ** Parse.pTriggerPrg and deleted once statement compilation has been
  9988. ** completed.
  9989. **
  9990. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  9991. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  9992. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  9993. ** The Parse.pTriggerPrg list never contains two entries with the same
  9994. ** values for both pTrigger and orconf.
  9995. **
  9996. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  9997. ** accessed (or set to 0 for triggers fired as a result of INSERT
  9998. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  9999. ** a mask of new.* columns used by the program.
  10000. */
  10001. struct TriggerPrg {
  10002. Trigger *pTrigger; /* Trigger this program was coded from */
  10003. int orconf; /* Default ON CONFLICT policy */
  10004. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  10005. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  10006. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  10007. };
  10008. /*
  10009. ** The yDbMask datatype for the bitmask of all attached databases.
  10010. */
  10011. #if SQLITE_MAX_ATTACHED>30
  10012. typedef sqlite3_uint64 yDbMask;
  10013. #else
  10014. typedef unsigned int yDbMask;
  10015. #endif
  10016. /*
  10017. ** An SQL parser context. A copy of this structure is passed through
  10018. ** the parser and down into all the parser action routine in order to
  10019. ** carry around information that is global to the entire parse.
  10020. **
  10021. ** The structure is divided into two parts. When the parser and code
  10022. ** generate call themselves recursively, the first part of the structure
  10023. ** is constant but the second part is reset at the beginning and end of
  10024. ** each recursion.
  10025. **
  10026. ** The nTableLock and aTableLock variables are only used if the shared-cache
  10027. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  10028. ** used to store the set of table-locks required by the statement being
  10029. ** compiled. Function sqlite3TableLock() is used to add entries to the
  10030. ** list.
  10031. */
  10032. struct Parse {
  10033. sqlite3 *db; /* The main database structure */
  10034. int rc; /* Return code from execution */
  10035. char *zErrMsg; /* An error message */
  10036. Vdbe *pVdbe; /* An engine for executing database bytecode */
  10037. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  10038. u8 nameClash; /* A permanent table name clashes with temp table name */
  10039. u8 checkSchema; /* Causes schema cookie check after an error */
  10040. u8 nested; /* Number of nested calls to the parser/code generator */
  10041. u8 parseError; /* True after a parsing error. Ticket #1794 */
  10042. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  10043. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  10044. int aTempReg[8]; /* Holding area for temporary registers */
  10045. int nRangeReg; /* Size of the temporary register block */
  10046. int iRangeReg; /* First register in temporary register block */
  10047. int nErr; /* Number of errors seen */
  10048. int nTab; /* Number of previously allocated VDBE cursors */
  10049. int nMem; /* Number of memory cells used so far */
  10050. int nSet; /* Number of sets used so far */
  10051. int ckBase; /* Base register of data during check constraints */
  10052. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  10053. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  10054. u8 nColCache; /* Number of entries in the column cache */
  10055. u8 iColCache; /* Next entry of the cache to replace */
  10056. struct yColCache {
  10057. int iTable; /* Table cursor number */
  10058. int iColumn; /* Table column number */
  10059. u8 tempReg; /* iReg is a temp register that needs to be freed */
  10060. int iLevel; /* Nesting level */
  10061. int iReg; /* Reg with value of this column. 0 means none. */
  10062. int lru; /* Least recently used entry has the smallest value */
  10063. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  10064. yDbMask writeMask; /* Start a write transaction on these databases */
  10065. yDbMask cookieMask; /* Bitmask of schema verified databases */
  10066. u8 isMultiWrite; /* True if statement may affect/insert multiple rows */
  10067. u8 mayAbort; /* True if statement may throw an ABORT exception */
  10068. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  10069. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  10070. #ifndef SQLITE_OMIT_SHARED_CACHE
  10071. int nTableLock; /* Number of locks in aTableLock */
  10072. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  10073. #endif
  10074. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  10075. int regRoot; /* Register holding root page number for new objects */
  10076. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  10077. int nMaxArg; /* Max args passed to user function by sub-program */
  10078. /* Information used while coding trigger programs. */
  10079. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  10080. Table *pTriggerTab; /* Table triggers are being coded for */
  10081. u32 oldmask; /* Mask of old.* columns referenced */
  10082. u32 newmask; /* Mask of new.* columns referenced */
  10083. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  10084. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  10085. u8 disableTriggers; /* True to disable triggers */
  10086. double nQueryLoop; /* Estimated number of iterations of a query */
  10087. /* Above is constant between recursions. Below is reset before and after
  10088. ** each recursion */
  10089. int nVar; /* Number of '?' variables seen in the SQL so far */
  10090. int nVarExpr; /* Number of used slots in apVarExpr[] */
  10091. int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */
  10092. Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */
  10093. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  10094. int nAlias; /* Number of aliased result set columns */
  10095. int nAliasAlloc; /* Number of allocated slots for aAlias[] */
  10096. int *aAlias; /* Register used to hold aliased result */
  10097. u8 explain; /* True if the EXPLAIN flag is found on the query */
  10098. Token sNameToken; /* Token with unqualified schema object name */
  10099. Token sLastToken; /* The last token parsed */
  10100. const char *zTail; /* All SQL text past the last semicolon parsed */
  10101. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  10102. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  10103. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  10104. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10105. Token sArg; /* Complete text of a module argument */
  10106. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  10107. int nVtabLock; /* Number of virtual tables to lock */
  10108. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  10109. #endif
  10110. int nHeight; /* Expression tree height of current sub-select */
  10111. Table *pZombieTab; /* List of Table objects to delete after code gen */
  10112. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  10113. #ifndef SQLITE_OMIT_EXPLAIN
  10114. int iSelectId;
  10115. int iNextSelectId;
  10116. #endif
  10117. };
  10118. #ifdef SQLITE_OMIT_VIRTUALTABLE
  10119. #define IN_DECLARE_VTAB 0
  10120. #else
  10121. #define IN_DECLARE_VTAB (pParse->declareVtab)
  10122. #endif
  10123. /*
  10124. ** An instance of the following structure can be declared on a stack and used
  10125. ** to save the Parse.zAuthContext value so that it can be restored later.
  10126. */
  10127. struct AuthContext {
  10128. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  10129. Parse *pParse; /* The Parse structure */
  10130. };
  10131. /*
  10132. ** Bitfield flags for P5 value in OP_Insert and OP_Delete
  10133. */
  10134. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  10135. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  10136. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  10137. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  10138. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  10139. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  10140. /*
  10141. * Each trigger present in the database schema is stored as an instance of
  10142. * struct Trigger.
  10143. *
  10144. * Pointers to instances of struct Trigger are stored in two ways.
  10145. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  10146. * database). This allows Trigger structures to be retrieved by name.
  10147. * 2. All triggers associated with a single table form a linked list, using the
  10148. * pNext member of struct Trigger. A pointer to the first element of the
  10149. * linked list is stored as the "pTrigger" member of the associated
  10150. * struct Table.
  10151. *
  10152. * The "step_list" member points to the first element of a linked list
  10153. * containing the SQL statements specified as the trigger program.
  10154. */
  10155. struct Trigger {
  10156. char *zName; /* The name of the trigger */
  10157. char *table; /* The table or view to which the trigger applies */
  10158. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  10159. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  10160. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  10161. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  10162. the <column-list> is stored here */
  10163. Schema *pSchema; /* Schema containing the trigger */
  10164. Schema *pTabSchema; /* Schema containing the table */
  10165. TriggerStep *step_list; /* Link list of trigger program steps */
  10166. Trigger *pNext; /* Next trigger associated with the table */
  10167. };
  10168. /*
  10169. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  10170. ** determine which.
  10171. **
  10172. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  10173. ** In that cases, the constants below can be ORed together.
  10174. */
  10175. #define TRIGGER_BEFORE 1
  10176. #define TRIGGER_AFTER 2
  10177. /*
  10178. * An instance of struct TriggerStep is used to store a single SQL statement
  10179. * that is a part of a trigger-program.
  10180. *
  10181. * Instances of struct TriggerStep are stored in a singly linked list (linked
  10182. * using the "pNext" member) referenced by the "step_list" member of the
  10183. * associated struct Trigger instance. The first element of the linked list is
  10184. * the first step of the trigger-program.
  10185. *
  10186. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  10187. * "SELECT" statement. The meanings of the other members is determined by the
  10188. * value of "op" as follows:
  10189. *
  10190. * (op == TK_INSERT)
  10191. * orconf -> stores the ON CONFLICT algorithm
  10192. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  10193. * this stores a pointer to the SELECT statement. Otherwise NULL.
  10194. * target -> A token holding the quoted name of the table to insert into.
  10195. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  10196. * this stores values to be inserted. Otherwise NULL.
  10197. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  10198. * statement, then this stores the column-names to be
  10199. * inserted into.
  10200. *
  10201. * (op == TK_DELETE)
  10202. * target -> A token holding the quoted name of the table to delete from.
  10203. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  10204. * Otherwise NULL.
  10205. *
  10206. * (op == TK_UPDATE)
  10207. * target -> A token holding the quoted name of the table to update rows of.
  10208. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  10209. * Otherwise NULL.
  10210. * pExprList -> A list of the columns to update and the expressions to update
  10211. * them to. See sqlite3Update() documentation of "pChanges"
  10212. * argument.
  10213. *
  10214. */
  10215. struct TriggerStep {
  10216. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  10217. u8 orconf; /* OE_Rollback etc. */
  10218. Trigger *pTrig; /* The trigger that this step is a part of */
  10219. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  10220. Token target; /* Target table for DELETE, UPDATE, INSERT */
  10221. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  10222. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  10223. IdList *pIdList; /* Column names for INSERT */
  10224. TriggerStep *pNext; /* Next in the link-list */
  10225. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  10226. };
  10227. /*
  10228. ** The following structure contains information used by the sqliteFix...
  10229. ** routines as they walk the parse tree to make database references
  10230. ** explicit.
  10231. */
  10232. typedef struct DbFixer DbFixer;
  10233. struct DbFixer {
  10234. Parse *pParse; /* The parsing context. Error messages written here */
  10235. const char *zDb; /* Make sure all objects are contained in this database */
  10236. const char *zType; /* Type of the container - used for error messages */
  10237. const Token *pName; /* Name of the container - used for error messages */
  10238. };
  10239. /*
  10240. ** An objected used to accumulate the text of a string where we
  10241. ** do not necessarily know how big the string will be in the end.
  10242. */
  10243. struct StrAccum {
  10244. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  10245. char *zBase; /* A base allocation. Not from malloc. */
  10246. char *zText; /* The string collected so far */
  10247. int nChar; /* Length of the string so far */
  10248. int nAlloc; /* Amount of space allocated in zText */
  10249. int mxAlloc; /* Maximum allowed string length */
  10250. u8 mallocFailed; /* Becomes true if any memory allocation fails */
  10251. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  10252. u8 tooBig; /* Becomes true if string size exceeds limits */
  10253. };
  10254. /*
  10255. ** A pointer to this structure is used to communicate information
  10256. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  10257. */
  10258. typedef struct {
  10259. sqlite3 *db; /* The database being initialized */
  10260. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  10261. char **pzErrMsg; /* Error message stored here */
  10262. int rc; /* Result code stored here */
  10263. } InitData;
  10264. /*
  10265. ** Structure containing global configuration data for the SQLite library.
  10266. **
  10267. ** This structure also contains some state information.
  10268. */
  10269. struct Sqlite3Config {
  10270. int bMemstat; /* True to enable memory status */
  10271. int bCoreMutex; /* True to enable core mutexing */
  10272. int bFullMutex; /* True to enable full mutexing */
  10273. int mxStrlen; /* Maximum string length */
  10274. int szLookaside; /* Default lookaside buffer size */
  10275. int nLookaside; /* Default lookaside buffer count */
  10276. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  10277. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  10278. sqlite3_pcache_methods pcache; /* Low-level page-cache interface */
  10279. void *pHeap; /* Heap storage space */
  10280. int nHeap; /* Size of pHeap[] */
  10281. int mnReq, mxReq; /* Min and max heap requests sizes */
  10282. void *pScratch; /* Scratch memory */
  10283. int szScratch; /* Size of each scratch buffer */
  10284. int nScratch; /* Number of scratch buffers */
  10285. void *pPage; /* Page cache memory */
  10286. int szPage; /* Size of each page in pPage[] */
  10287. int nPage; /* Number of pages in pPage[] */
  10288. int mxParserStack; /* maximum depth of the parser stack */
  10289. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  10290. /* The above might be initialized to non-zero. The following need to always
  10291. ** initially be zero, however. */
  10292. int isInit; /* True after initialization has finished */
  10293. int inProgress; /* True while initialization in progress */
  10294. int isMutexInit; /* True after mutexes are initialized */
  10295. int isMallocInit; /* True after malloc is initialized */
  10296. int isPCacheInit; /* True after malloc is initialized */
  10297. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  10298. int nRefInitMutex; /* Number of users of pInitMutex */
  10299. void (*xLog)(void*,int,const char*); /* Function for logging */
  10300. void *pLogArg; /* First argument to xLog() */
  10301. };
  10302. /*
  10303. ** Context pointer passed down through the tree-walk.
  10304. */
  10305. struct Walker {
  10306. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  10307. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  10308. Parse *pParse; /* Parser context. */
  10309. union { /* Extra data for callback */
  10310. NameContext *pNC; /* Naming context */
  10311. int i; /* Integer value */
  10312. } u;
  10313. };
  10314. /* Forward declarations */
  10315. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  10316. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  10317. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  10318. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  10319. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  10320. /*
  10321. ** Return code from the parse-tree walking primitives and their
  10322. ** callbacks.
  10323. */
  10324. #define WRC_Continue 0 /* Continue down into children */
  10325. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  10326. #define WRC_Abort 2 /* Abandon the tree walk */
  10327. /*
  10328. ** Assuming zIn points to the first byte of a UTF-8 character,
  10329. ** advance zIn to point to the first byte of the next UTF-8 character.
  10330. */
  10331. #define SQLITE_SKIP_UTF8(zIn) { \
  10332. if( (*(zIn++))>=0xc0 ){ \
  10333. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  10334. } \
  10335. }
  10336. /*
  10337. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  10338. ** the same name but without the _BKPT suffix. These macros invoke
  10339. ** routines that report the line-number on which the error originated
  10340. ** using sqlite3_log(). The routines also provide a convenient place
  10341. ** to set a debugger breakpoint.
  10342. */
  10343. SQLITE_PRIVATE int sqlite3CorruptError(int);
  10344. SQLITE_PRIVATE int sqlite3MisuseError(int);
  10345. SQLITE_PRIVATE int sqlite3CantopenError(int);
  10346. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  10347. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  10348. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  10349. /*
  10350. ** FTS4 is really an extension for FTS3. It is enabled using the
  10351. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  10352. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  10353. */
  10354. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  10355. # define SQLITE_ENABLE_FTS3
  10356. #endif
  10357. /*
  10358. ** The ctype.h header is needed for non-ASCII systems. It is also
  10359. ** needed by FTS3 when FTS3 is included in the amalgamation.
  10360. */
  10361. #if !defined(SQLITE_ASCII) || \
  10362. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  10363. # include <ctype.h>
  10364. #endif
  10365. /*
  10366. ** The following macros mimic the standard library functions toupper(),
  10367. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  10368. ** sqlite versions only work for ASCII characters, regardless of locale.
  10369. */
  10370. #ifdef SQLITE_ASCII
  10371. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  10372. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  10373. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  10374. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  10375. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  10376. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  10377. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  10378. #else
  10379. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  10380. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  10381. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  10382. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  10383. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  10384. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  10385. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  10386. #endif
  10387. /*
  10388. ** Internal function prototypes
  10389. */
  10390. SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
  10391. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  10392. #define sqlite3StrNICmp sqlite3_strnicmp
  10393. SQLITE_PRIVATE int sqlite3MallocInit(void);
  10394. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  10395. SQLITE_PRIVATE void *sqlite3Malloc(int);
  10396. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  10397. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  10398. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  10399. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  10400. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  10401. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  10402. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  10403. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  10404. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  10405. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  10406. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  10407. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  10408. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  10409. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  10410. SQLITE_PRIVATE void sqlite3PageFree(void*);
  10411. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  10412. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  10413. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  10414. /*
  10415. ** On systems with ample stack space and that support alloca(), make
  10416. ** use of alloca() to obtain space for large automatic objects. By default,
  10417. ** obtain space from malloc().
  10418. **
  10419. ** The alloca() routine never returns NULL. This will cause code paths
  10420. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  10421. */
  10422. #ifdef SQLITE_USE_ALLOCA
  10423. # define sqlite3StackAllocRaw(D,N) alloca(N)
  10424. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  10425. # define sqlite3StackFree(D,P)
  10426. #else
  10427. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  10428. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  10429. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  10430. #endif
  10431. #ifdef SQLITE_ENABLE_MEMSYS3
  10432. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  10433. #endif
  10434. #ifdef SQLITE_ENABLE_MEMSYS5
  10435. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  10436. #endif
  10437. #ifndef SQLITE_MUTEX_OMIT
  10438. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  10439. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  10440. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  10441. SQLITE_PRIVATE int sqlite3MutexInit(void);
  10442. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  10443. #endif
  10444. SQLITE_PRIVATE int sqlite3StatusValue(int);
  10445. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  10446. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  10447. #ifndef SQLITE_OMIT_FLOATING_POINT
  10448. SQLITE_PRIVATE int sqlite3IsNaN(double);
  10449. #else
  10450. # define sqlite3IsNaN(X) 0
  10451. #endif
  10452. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  10453. #ifndef SQLITE_OMIT_TRACE
  10454. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  10455. #endif
  10456. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  10457. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  10458. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  10459. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  10460. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  10461. #endif
  10462. #if defined(SQLITE_TEST)
  10463. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  10464. #endif
  10465. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  10466. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  10467. SQLITE_PRIVATE int sqlite3Dequote(char*);
  10468. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  10469. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  10470. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  10471. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  10472. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  10473. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  10474. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  10475. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  10476. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  10477. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  10478. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  10479. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  10480. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  10481. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  10482. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  10483. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  10484. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  10485. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  10486. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  10487. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  10488. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  10489. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  10490. SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
  10491. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  10492. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  10493. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  10494. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  10495. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  10496. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  10497. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  10498. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  10499. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  10500. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  10501. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  10502. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  10503. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  10504. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  10505. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  10506. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  10507. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  10508. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  10509. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  10510. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  10511. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  10512. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  10513. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  10514. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  10515. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  10516. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  10517. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  10518. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  10519. #else
  10520. # define sqlite3ViewGetColumnNames(A,B) 0
  10521. #endif
  10522. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  10523. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  10524. #ifndef SQLITE_OMIT_AUTOINCREMENT
  10525. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  10526. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  10527. #else
  10528. # define sqlite3AutoincrementBegin(X)
  10529. # define sqlite3AutoincrementEnd(X)
  10530. #endif
  10531. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  10532. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
  10533. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  10534. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  10535. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  10536. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  10537. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  10538. Token*, Select*, Expr*, IdList*);
  10539. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  10540. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  10541. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  10542. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  10543. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  10544. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  10545. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  10546. Token*, int, int);
  10547. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  10548. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  10549. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  10550. Expr*,ExprList*,int,Expr*,Expr*);
  10551. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  10552. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  10553. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  10554. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  10555. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  10556. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
  10557. #endif
  10558. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  10559. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  10560. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
  10561. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  10562. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
  10563. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  10564. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  10565. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
  10566. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  10567. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  10568. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
  10569. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  10570. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  10571. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  10572. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  10573. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  10574. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  10575. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  10576. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  10577. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  10578. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  10579. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  10580. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  10581. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  10582. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  10583. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  10584. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  10585. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  10586. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  10587. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  10588. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
  10589. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
  10590. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  10591. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  10592. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  10593. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  10594. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  10595. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  10596. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
  10597. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  10598. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  10599. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  10600. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  10601. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  10602. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  10603. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  10604. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  10605. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  10606. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  10607. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  10608. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  10609. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  10610. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  10611. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  10612. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  10613. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  10614. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
  10615. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  10616. int*,int,int,int,int,int*);
  10617. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  10618. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  10619. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  10620. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  10621. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  10622. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
  10623. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  10624. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  10625. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  10626. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  10627. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  10628. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  10629. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
  10630. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  10631. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  10632. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  10633. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  10634. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  10635. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  10636. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  10637. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  10638. #endif
  10639. #ifndef SQLITE_OMIT_TRIGGER
  10640. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  10641. Expr*,int, int);
  10642. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  10643. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  10644. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  10645. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  10646. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  10647. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  10648. int, int, int);
  10649. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  10650. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  10651. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  10652. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  10653. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  10654. ExprList*,Select*,u8);
  10655. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  10656. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  10657. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  10658. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  10659. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  10660. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  10661. #else
  10662. # define sqlite3TriggersExist(B,C,D,E,F) 0
  10663. # define sqlite3DeleteTrigger(A,B)
  10664. # define sqlite3DropTriggerPtr(A,B)
  10665. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  10666. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  10667. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  10668. # define sqlite3TriggerList(X, Y) 0
  10669. # define sqlite3ParseToplevel(p) p
  10670. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  10671. #endif
  10672. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  10673. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  10674. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  10675. #ifndef SQLITE_OMIT_AUTHORIZATION
  10676. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  10677. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  10678. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  10679. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  10680. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  10681. #else
  10682. # define sqlite3AuthRead(a,b,c,d)
  10683. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  10684. # define sqlite3AuthContextPush(a,b,c)
  10685. # define sqlite3AuthContextPop(a) ((void)(a))
  10686. #endif
  10687. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  10688. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  10689. SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  10690. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  10691. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  10692. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  10693. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  10694. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  10695. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  10696. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  10697. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  10698. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  10699. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  10700. SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
  10701. /*
  10702. ** Routines to read and write variable-length integers. These used to
  10703. ** be defined locally, but now we use the varint routines in the util.c
  10704. ** file. Code should use the MACRO forms below, as the Varint32 versions
  10705. ** are coded to assume the single byte case is already handled (which
  10706. ** the MACRO form does).
  10707. */
  10708. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  10709. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  10710. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  10711. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  10712. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  10713. /*
  10714. ** The header of a record consists of a sequence variable-length integers.
  10715. ** These integers are almost always small and are encoded as a single byte.
  10716. ** The following macros take advantage this fact to provide a fast encode
  10717. ** and decode of the integers in a record header. It is faster for the common
  10718. ** case where the integer is a single byte. It is a little slower when the
  10719. ** integer is two or more bytes. But overall it is faster.
  10720. **
  10721. ** The following expressions are equivalent:
  10722. **
  10723. ** x = sqlite3GetVarint32( A, &B );
  10724. ** x = sqlite3PutVarint32( A, B );
  10725. **
  10726. ** x = getVarint32( A, B );
  10727. ** x = putVarint32( A, B );
  10728. **
  10729. */
  10730. #define getVarint32(A,B) (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
  10731. #define putVarint32(A,B) (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
  10732. #define getVarint sqlite3GetVarint
  10733. #define putVarint sqlite3PutVarint
  10734. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  10735. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  10736. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  10737. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  10738. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  10739. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  10740. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  10741. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  10742. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  10743. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  10744. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  10745. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  10746. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  10747. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  10748. SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
  10749. SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
  10750. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  10751. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  10752. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  10753. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  10754. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  10755. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  10756. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  10757. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  10758. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  10759. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  10760. void(*)(void*));
  10761. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  10762. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  10763. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  10764. #ifdef SQLITE_ENABLE_STAT2
  10765. SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
  10766. #endif
  10767. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  10768. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  10769. #ifndef SQLITE_AMALGAMATION
  10770. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  10771. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  10772. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  10773. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  10774. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  10775. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  10776. #ifndef SQLITE_OMIT_WSD
  10777. SQLITE_PRIVATE int sqlite3PendingByte;
  10778. #endif
  10779. #endif
  10780. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  10781. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  10782. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  10783. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  10784. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  10785. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  10786. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  10787. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  10788. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  10789. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  10790. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  10791. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  10792. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  10793. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  10794. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  10795. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
  10796. SQLITE_PRIVATE char sqlite3AffinityType(const char*);
  10797. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  10798. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  10799. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  10800. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  10801. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  10802. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  10803. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  10804. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  10805. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  10806. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  10807. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  10808. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  10809. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  10810. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  10811. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  10812. void (*)(sqlite3_context*,int,sqlite3_value **),
  10813. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  10814. FuncDestructor *pDestructor
  10815. );
  10816. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  10817. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  10818. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  10819. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  10820. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  10821. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  10822. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  10823. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  10824. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  10825. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  10826. /*
  10827. ** The interface to the LEMON-generated parser
  10828. */
  10829. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  10830. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  10831. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  10832. #ifdef YYTRACKMAXSTACKDEPTH
  10833. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  10834. #endif
  10835. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  10836. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10837. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  10838. #else
  10839. # define sqlite3CloseExtensions(X)
  10840. #endif
  10841. #ifndef SQLITE_OMIT_SHARED_CACHE
  10842. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  10843. #else
  10844. #define sqlite3TableLock(v,w,x,y,z)
  10845. #endif
  10846. #ifdef SQLITE_TEST
  10847. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  10848. #endif
  10849. #ifdef SQLITE_OMIT_VIRTUALTABLE
  10850. # define sqlite3VtabClear(Y)
  10851. # define sqlite3VtabSync(X,Y) SQLITE_OK
  10852. # define sqlite3VtabRollback(X)
  10853. # define sqlite3VtabCommit(X)
  10854. # define sqlite3VtabInSync(db) 0
  10855. # define sqlite3VtabLock(X)
  10856. # define sqlite3VtabUnlock(X)
  10857. # define sqlite3VtabUnlockList(X)
  10858. #else
  10859. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  10860. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **);
  10861. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  10862. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  10863. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  10864. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  10865. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  10866. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  10867. #endif
  10868. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  10869. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
  10870. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  10871. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  10872. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  10873. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  10874. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  10875. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  10876. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  10877. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  10878. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  10879. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  10880. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  10881. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  10882. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  10883. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  10884. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  10885. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  10886. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  10887. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  10888. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  10889. /* Declarations for functions in fkey.c. All of these are replaced by
  10890. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  10891. ** key functionality is available. If OMIT_TRIGGER is defined but
  10892. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  10893. ** this case foreign keys are parsed, but no other functionality is
  10894. ** provided (enforcement of FK constraints requires the triggers sub-system).
  10895. */
  10896. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  10897. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int);
  10898. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  10899. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int);
  10900. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  10901. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  10902. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  10903. #else
  10904. #define sqlite3FkActions(a,b,c,d)
  10905. #define sqlite3FkCheck(a,b,c,d)
  10906. #define sqlite3FkDropTable(a,b,c)
  10907. #define sqlite3FkOldmask(a,b) 0
  10908. #define sqlite3FkRequired(a,b,c,d) 0
  10909. #endif
  10910. #ifndef SQLITE_OMIT_FOREIGN_KEY
  10911. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  10912. #else
  10913. #define sqlite3FkDelete(a,b)
  10914. #endif
  10915. /*
  10916. ** Available fault injectors. Should be numbered beginning with 0.
  10917. */
  10918. #define SQLITE_FAULTINJECTOR_MALLOC 0
  10919. #define SQLITE_FAULTINJECTOR_COUNT 1
  10920. /*
  10921. ** The interface to the code in fault.c used for identifying "benign"
  10922. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  10923. ** is not defined.
  10924. */
  10925. #ifndef SQLITE_OMIT_BUILTIN_TEST
  10926. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  10927. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  10928. #else
  10929. #define sqlite3BeginBenignMalloc()
  10930. #define sqlite3EndBenignMalloc()
  10931. #endif
  10932. #define IN_INDEX_ROWID 1
  10933. #define IN_INDEX_EPH 2
  10934. #define IN_INDEX_INDEX 3
  10935. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  10936. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  10937. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  10938. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  10939. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  10940. #else
  10941. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  10942. #endif
  10943. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  10944. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  10945. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  10946. #if SQLITE_MAX_EXPR_DEPTH>0
  10947. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  10948. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  10949. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  10950. #else
  10951. #define sqlite3ExprSetHeight(x,y)
  10952. #define sqlite3SelectExprHeight(x) 0
  10953. #define sqlite3ExprCheckHeight(x,y)
  10954. #endif
  10955. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  10956. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  10957. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  10958. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  10959. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  10960. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  10961. #else
  10962. #define sqlite3ConnectionBlocked(x,y)
  10963. #define sqlite3ConnectionUnlocked(x)
  10964. #define sqlite3ConnectionClosed(x)
  10965. #endif
  10966. #ifdef SQLITE_DEBUG
  10967. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  10968. #endif
  10969. /*
  10970. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  10971. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  10972. ** print I/O tracing messages.
  10973. */
  10974. #ifdef SQLITE_ENABLE_IOTRACE
  10975. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  10976. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  10977. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  10978. #else
  10979. # define IOTRACE(A)
  10980. # define sqlite3VdbeIOTraceSql(X)
  10981. #endif
  10982. /*
  10983. ** These routines are available for the mem2.c debugging memory allocator
  10984. ** only. They are used to verify that different "types" of memory
  10985. ** allocations are properly tracked by the system.
  10986. **
  10987. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  10988. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  10989. ** a single bit set.
  10990. **
  10991. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  10992. ** argument match the type set by the previous sqlite3MemdebugSetType().
  10993. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  10994. **
  10995. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  10996. ** argument match the type set by the previous sqlite3MemdebugSetType().
  10997. **
  10998. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  10999. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  11000. ** it might have been allocated by lookaside, except the allocation was
  11001. ** too large or lookaside was already full. It is important to verify
  11002. ** that allocations that might have been satisfied by lookaside are not
  11003. ** passed back to non-lookaside free() routines. Asserts such as the
  11004. ** example above are placed on the non-lookaside free() routines to verify
  11005. ** this constraint.
  11006. **
  11007. ** All of this is no-op for a production build. It only comes into
  11008. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  11009. */
  11010. #ifdef SQLITE_MEMDEBUG
  11011. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  11012. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  11013. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  11014. #else
  11015. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  11016. # define sqlite3MemdebugHasType(X,Y) 1
  11017. # define sqlite3MemdebugNoType(X,Y) 1
  11018. #endif
  11019. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  11020. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  11021. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  11022. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  11023. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  11024. #endif /* _SQLITEINT_H_ */
  11025. /************** End of sqliteInt.h *******************************************/
  11026. /************** Begin file global.c ******************************************/
  11027. /*
  11028. ** 2008 June 13
  11029. **
  11030. ** The author disclaims copyright to this source code. In place of
  11031. ** a legal notice, here is a blessing:
  11032. **
  11033. ** May you do good and not evil.
  11034. ** May you find forgiveness for yourself and forgive others.
  11035. ** May you share freely, never taking more than you give.
  11036. **
  11037. *************************************************************************
  11038. **
  11039. ** This file contains definitions of global variables and contants.
  11040. */
  11041. /* An array to map all upper-case characters into their corresponding
  11042. ** lower-case character.
  11043. **
  11044. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  11045. ** handle case conversions for the UTF character set since the tables
  11046. ** involved are nearly as big or bigger than SQLite itself.
  11047. */
  11048. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  11049. #ifdef SQLITE_ASCII
  11050. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  11051. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  11052. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  11053. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  11054. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  11055. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  11056. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  11057. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  11058. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  11059. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  11060. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  11061. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  11062. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  11063. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  11064. 252,253,254,255
  11065. #endif
  11066. #ifdef SQLITE_EBCDIC
  11067. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  11068. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  11069. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  11070. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  11071. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  11072. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  11073. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  11074. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  11075. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  11076. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  11077. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  11078. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  11079. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  11080. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  11081. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  11082. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  11083. #endif
  11084. };
  11085. /*
  11086. ** The following 256 byte lookup table is used to support SQLites built-in
  11087. ** equivalents to the following standard library functions:
  11088. **
  11089. ** isspace() 0x01
  11090. ** isalpha() 0x02
  11091. ** isdigit() 0x04
  11092. ** isalnum() 0x06
  11093. ** isxdigit() 0x08
  11094. ** toupper() 0x20
  11095. ** SQLite identifier character 0x40
  11096. **
  11097. ** Bit 0x20 is set if the mapped character requires translation to upper
  11098. ** case. i.e. if the character is a lower-case ASCII character.
  11099. ** If x is a lower-case ASCII character, then its upper-case equivalent
  11100. ** is (x - 0x20). Therefore toupper() can be implemented as:
  11101. **
  11102. ** (x & ~(map[x]&0x20))
  11103. **
  11104. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  11105. ** array. tolower() is used more often than toupper() by SQLite.
  11106. **
  11107. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  11108. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  11109. ** non-ASCII UTF character. Hence the test for whether or not a character is
  11110. ** part of an identifier is 0x46.
  11111. **
  11112. ** SQLite's versions are identical to the standard versions assuming a
  11113. ** locale of "C". They are implemented as macros in sqliteInt.h.
  11114. */
  11115. #ifdef SQLITE_ASCII
  11116. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  11117. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  11118. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  11119. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  11120. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  11121. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  11122. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  11123. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  11124. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  11125. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  11126. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  11127. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  11128. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  11129. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  11130. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  11131. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  11132. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  11133. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  11134. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  11135. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  11136. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  11137. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  11138. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  11139. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  11140. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  11141. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  11142. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  11143. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  11144. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  11145. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  11146. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  11147. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  11148. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  11149. };
  11150. #endif
  11151. /*
  11152. ** The following singleton contains the global configuration for
  11153. ** the SQLite library.
  11154. */
  11155. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  11156. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  11157. 1, /* bCoreMutex */
  11158. SQLITE_THREADSAFE==1, /* bFullMutex */
  11159. 0x7ffffffe, /* mxStrlen */
  11160. 100, /* szLookaside */
  11161. 500, /* nLookaside */
  11162. {0,0,0,0,0,0,0,0}, /* m */
  11163. {0,0,0,0,0,0,0,0,0}, /* mutex */
  11164. {0,0,0,0,0,0,0,0,0,0,0}, /* pcache */
  11165. (void*)0, /* pHeap */
  11166. 0, /* nHeap */
  11167. 0, 0, /* mnHeap, mxHeap */
  11168. (void*)0, /* pScratch */
  11169. 0, /* szScratch */
  11170. 0, /* nScratch */
  11171. (void*)0, /* pPage */
  11172. 0, /* szPage */
  11173. 0, /* nPage */
  11174. 0, /* mxParserStack */
  11175. 0, /* sharedCacheEnabled */
  11176. /* All the rest should always be initialized to zero */
  11177. 0, /* isInit */
  11178. 0, /* inProgress */
  11179. 0, /* isMutexInit */
  11180. 0, /* isMallocInit */
  11181. 0, /* isPCacheInit */
  11182. 0, /* pInitMutex */
  11183. 0, /* nRefInitMutex */
  11184. 0, /* xLog */
  11185. 0, /* pLogArg */
  11186. };
  11187. /*
  11188. ** Hash table for global functions - functions common to all
  11189. ** database connections. After initialization, this table is
  11190. ** read-only.
  11191. */
  11192. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11193. /*
  11194. ** Constant tokens for values 0 and 1.
  11195. */
  11196. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  11197. { "0", 1 },
  11198. { "1", 1 }
  11199. };
  11200. /*
  11201. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  11202. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  11203. ** the database page that contains the pending byte. It never attempts
  11204. ** to read or write that page. The pending byte page is set assign
  11205. ** for use by the VFS layers as space for managing file locks.
  11206. **
  11207. ** During testing, it is often desirable to move the pending byte to
  11208. ** a different position in the file. This allows code that has to
  11209. ** deal with the pending byte to run on files that are much smaller
  11210. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  11211. ** move the pending byte.
  11212. **
  11213. ** IMPORTANT: Changing the pending byte to any value other than
  11214. ** 0x40000000 results in an incompatible database file format!
  11215. ** Changing the pending byte during operating results in undefined
  11216. ** and dileterious behavior.
  11217. */
  11218. #ifndef SQLITE_OMIT_WSD
  11219. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  11220. #endif
  11221. /*
  11222. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  11223. ** created by mkopcodeh.awk during compilation. Data is obtained
  11224. ** from the comments following the "case OP_xxxx:" statements in
  11225. ** the vdbe.c file.
  11226. */
  11227. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  11228. /************** End of global.c **********************************************/
  11229. /************** Begin file ctime.c *******************************************/
  11230. /*
  11231. ** 2010 February 23
  11232. **
  11233. ** The author disclaims copyright to this source code. In place of
  11234. ** a legal notice, here is a blessing:
  11235. **
  11236. ** May you do good and not evil.
  11237. ** May you find forgiveness for yourself and forgive others.
  11238. ** May you share freely, never taking more than you give.
  11239. **
  11240. *************************************************************************
  11241. **
  11242. ** This file implements routines used to report what compile-time options
  11243. ** SQLite was built with.
  11244. */
  11245. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  11246. /*
  11247. ** An array of names of all compile-time options. This array should
  11248. ** be sorted A-Z.
  11249. **
  11250. ** This array looks large, but in a typical installation actually uses
  11251. ** only a handful of compile-time options, so most times this array is usually
  11252. ** rather short and uses little memory space.
  11253. */
  11254. static const char * const azCompileOpt[] = {
  11255. /* These macros are provided to "stringify" the value of the define
  11256. ** for those options in which the value is meaningful. */
  11257. #define CTIMEOPT_VAL_(opt) #opt
  11258. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  11259. #ifdef SQLITE_32BIT_ROWID
  11260. "32BIT_ROWID",
  11261. #endif
  11262. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  11263. "4_BYTE_ALIGNED_MALLOC",
  11264. #endif
  11265. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  11266. "CASE_SENSITIVE_LIKE",
  11267. #endif
  11268. #ifdef SQLITE_CHECK_PAGES
  11269. "CHECK_PAGES",
  11270. #endif
  11271. #ifdef SQLITE_COVERAGE_TEST
  11272. "COVERAGE_TEST",
  11273. #endif
  11274. #ifdef SQLITE_DEBUG
  11275. "DEBUG",
  11276. #endif
  11277. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  11278. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  11279. #endif
  11280. #ifdef SQLITE_DISABLE_DIRSYNC
  11281. "DISABLE_DIRSYNC",
  11282. #endif
  11283. #ifdef SQLITE_DISABLE_LFS
  11284. "DISABLE_LFS",
  11285. #endif
  11286. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  11287. "ENABLE_ATOMIC_WRITE",
  11288. #endif
  11289. #ifdef SQLITE_ENABLE_CEROD
  11290. "ENABLE_CEROD",
  11291. #endif
  11292. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  11293. "ENABLE_COLUMN_METADATA",
  11294. #endif
  11295. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  11296. "ENABLE_EXPENSIVE_ASSERT",
  11297. #endif
  11298. #ifdef SQLITE_ENABLE_FTS1
  11299. "ENABLE_FTS1",
  11300. #endif
  11301. #ifdef SQLITE_ENABLE_FTS2
  11302. "ENABLE_FTS2",
  11303. #endif
  11304. #ifdef SQLITE_ENABLE_FTS3
  11305. "ENABLE_FTS3",
  11306. #endif
  11307. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  11308. "ENABLE_FTS3_PARENTHESIS",
  11309. #endif
  11310. #ifdef SQLITE_ENABLE_FTS4
  11311. "ENABLE_FTS4",
  11312. #endif
  11313. #ifdef SQLITE_ENABLE_ICU
  11314. "ENABLE_ICU",
  11315. #endif
  11316. #ifdef SQLITE_ENABLE_IOTRACE
  11317. "ENABLE_IOTRACE",
  11318. #endif
  11319. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  11320. "ENABLE_LOAD_EXTENSION",
  11321. #endif
  11322. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  11323. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  11324. #endif
  11325. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  11326. "ENABLE_MEMORY_MANAGEMENT",
  11327. #endif
  11328. #ifdef SQLITE_ENABLE_MEMSYS3
  11329. "ENABLE_MEMSYS3",
  11330. #endif
  11331. #ifdef SQLITE_ENABLE_MEMSYS5
  11332. "ENABLE_MEMSYS5",
  11333. #endif
  11334. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  11335. "ENABLE_OVERSIZE_CELL_CHECK",
  11336. #endif
  11337. #ifdef SQLITE_ENABLE_RTREE
  11338. "ENABLE_RTREE",
  11339. #endif
  11340. #ifdef SQLITE_ENABLE_STAT2
  11341. "ENABLE_STAT2",
  11342. #endif
  11343. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11344. "ENABLE_UNLOCK_NOTIFY",
  11345. #endif
  11346. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  11347. "ENABLE_UPDATE_DELETE_LIMIT",
  11348. #endif
  11349. #ifdef SQLITE_HAS_CODEC
  11350. "HAS_CODEC",
  11351. #endif
  11352. #ifdef SQLITE_HAVE_ISNAN
  11353. "HAVE_ISNAN",
  11354. #endif
  11355. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  11356. "HOMEGROWN_RECURSIVE_MUTEX",
  11357. #endif
  11358. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  11359. "IGNORE_AFP_LOCK_ERRORS",
  11360. #endif
  11361. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  11362. "IGNORE_FLOCK_LOCK_ERRORS",
  11363. #endif
  11364. #ifdef SQLITE_INT64_TYPE
  11365. "INT64_TYPE",
  11366. #endif
  11367. #ifdef SQLITE_LOCK_TRACE
  11368. "LOCK_TRACE",
  11369. #endif
  11370. #ifdef SQLITE_MEMDEBUG
  11371. "MEMDEBUG",
  11372. #endif
  11373. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  11374. "MIXED_ENDIAN_64BIT_FLOAT",
  11375. #endif
  11376. #ifdef SQLITE_NO_SYNC
  11377. "NO_SYNC",
  11378. #endif
  11379. #ifdef SQLITE_OMIT_ALTERTABLE
  11380. "OMIT_ALTERTABLE",
  11381. #endif
  11382. #ifdef SQLITE_OMIT_ANALYZE
  11383. "OMIT_ANALYZE",
  11384. #endif
  11385. #ifdef SQLITE_OMIT_ATTACH
  11386. "OMIT_ATTACH",
  11387. #endif
  11388. #ifdef SQLITE_OMIT_AUTHORIZATION
  11389. "OMIT_AUTHORIZATION",
  11390. #endif
  11391. #ifdef SQLITE_OMIT_AUTOINCREMENT
  11392. "OMIT_AUTOINCREMENT",
  11393. #endif
  11394. #ifdef SQLITE_OMIT_AUTOINIT
  11395. "OMIT_AUTOINIT",
  11396. #endif
  11397. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  11398. "OMIT_AUTOMATIC_INDEX",
  11399. #endif
  11400. #ifdef SQLITE_OMIT_AUTORESET
  11401. "OMIT_AUTORESET",
  11402. #endif
  11403. #ifdef SQLITE_OMIT_AUTOVACUUM
  11404. "OMIT_AUTOVACUUM",
  11405. #endif
  11406. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  11407. "OMIT_BETWEEN_OPTIMIZATION",
  11408. #endif
  11409. #ifdef SQLITE_OMIT_BLOB_LITERAL
  11410. "OMIT_BLOB_LITERAL",
  11411. #endif
  11412. #ifdef SQLITE_OMIT_BTREECOUNT
  11413. "OMIT_BTREECOUNT",
  11414. #endif
  11415. #ifdef SQLITE_OMIT_BUILTIN_TEST
  11416. "OMIT_BUILTIN_TEST",
  11417. #endif
  11418. #ifdef SQLITE_OMIT_CAST
  11419. "OMIT_CAST",
  11420. #endif
  11421. #ifdef SQLITE_OMIT_CHECK
  11422. "OMIT_CHECK",
  11423. #endif
  11424. /* // redundant
  11425. ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
  11426. ** "OMIT_COMPILEOPTION_DIAGS",
  11427. ** #endif
  11428. */
  11429. #ifdef SQLITE_OMIT_COMPLETE
  11430. "OMIT_COMPLETE",
  11431. #endif
  11432. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  11433. "OMIT_COMPOUND_SELECT",
  11434. #endif
  11435. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  11436. "OMIT_DATETIME_FUNCS",
  11437. #endif
  11438. #ifdef SQLITE_OMIT_DECLTYPE
  11439. "OMIT_DECLTYPE",
  11440. #endif
  11441. #ifdef SQLITE_OMIT_DEPRECATED
  11442. "OMIT_DEPRECATED",
  11443. #endif
  11444. #ifdef SQLITE_OMIT_DISKIO
  11445. "OMIT_DISKIO",
  11446. #endif
  11447. #ifdef SQLITE_OMIT_EXPLAIN
  11448. "OMIT_EXPLAIN",
  11449. #endif
  11450. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  11451. "OMIT_FLAG_PRAGMAS",
  11452. #endif
  11453. #ifdef SQLITE_OMIT_FLOATING_POINT
  11454. "OMIT_FLOATING_POINT",
  11455. #endif
  11456. #ifdef SQLITE_OMIT_FOREIGN_KEY
  11457. "OMIT_FOREIGN_KEY",
  11458. #endif
  11459. #ifdef SQLITE_OMIT_GET_TABLE
  11460. "OMIT_GET_TABLE",
  11461. #endif
  11462. #ifdef SQLITE_OMIT_INCRBLOB
  11463. "OMIT_INCRBLOB",
  11464. #endif
  11465. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  11466. "OMIT_INTEGRITY_CHECK",
  11467. #endif
  11468. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  11469. "OMIT_LIKE_OPTIMIZATION",
  11470. #endif
  11471. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  11472. "OMIT_LOAD_EXTENSION",
  11473. #endif
  11474. #ifdef SQLITE_OMIT_LOCALTIME
  11475. "OMIT_LOCALTIME",
  11476. #endif
  11477. #ifdef SQLITE_OMIT_LOOKASIDE
  11478. "OMIT_LOOKASIDE",
  11479. #endif
  11480. #ifdef SQLITE_OMIT_MEMORYDB
  11481. "OMIT_MEMORYDB",
  11482. #endif
  11483. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  11484. "OMIT_OR_OPTIMIZATION",
  11485. #endif
  11486. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  11487. "OMIT_PAGER_PRAGMAS",
  11488. #endif
  11489. #ifdef SQLITE_OMIT_PRAGMA
  11490. "OMIT_PRAGMA",
  11491. #endif
  11492. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  11493. "OMIT_PROGRESS_CALLBACK",
  11494. #endif
  11495. #ifdef SQLITE_OMIT_QUICKBALANCE
  11496. "OMIT_QUICKBALANCE",
  11497. #endif
  11498. #ifdef SQLITE_OMIT_REINDEX
  11499. "OMIT_REINDEX",
  11500. #endif
  11501. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  11502. "OMIT_SCHEMA_PRAGMAS",
  11503. #endif
  11504. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  11505. "OMIT_SCHEMA_VERSION_PRAGMAS",
  11506. #endif
  11507. #ifdef SQLITE_OMIT_SHARED_CACHE
  11508. "OMIT_SHARED_CACHE",
  11509. #endif
  11510. #ifdef SQLITE_OMIT_SUBQUERY
  11511. "OMIT_SUBQUERY",
  11512. #endif
  11513. #ifdef SQLITE_OMIT_TCL_VARIABLE
  11514. "OMIT_TCL_VARIABLE",
  11515. #endif
  11516. #ifdef SQLITE_OMIT_TEMPDB
  11517. "OMIT_TEMPDB",
  11518. #endif
  11519. #ifdef SQLITE_OMIT_TRACE
  11520. "OMIT_TRACE",
  11521. #endif
  11522. #ifdef SQLITE_OMIT_TRIGGER
  11523. "OMIT_TRIGGER",
  11524. #endif
  11525. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  11526. "OMIT_TRUNCATE_OPTIMIZATION",
  11527. #endif
  11528. #ifdef SQLITE_OMIT_UTF16
  11529. "OMIT_UTF16",
  11530. #endif
  11531. #ifdef SQLITE_OMIT_VACUUM
  11532. "OMIT_VACUUM",
  11533. #endif
  11534. #ifdef SQLITE_OMIT_VIEW
  11535. "OMIT_VIEW",
  11536. #endif
  11537. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11538. "OMIT_VIRTUALTABLE",
  11539. #endif
  11540. #ifdef SQLITE_OMIT_WAL
  11541. "OMIT_WAL",
  11542. #endif
  11543. #ifdef SQLITE_OMIT_WSD
  11544. "OMIT_WSD",
  11545. #endif
  11546. #ifdef SQLITE_OMIT_XFER_OPT
  11547. "OMIT_XFER_OPT",
  11548. #endif
  11549. #ifdef SQLITE_PERFORMANCE_TRACE
  11550. "PERFORMANCE_TRACE",
  11551. #endif
  11552. #ifdef SQLITE_PROXY_DEBUG
  11553. "PROXY_DEBUG",
  11554. #endif
  11555. #ifdef SQLITE_SECURE_DELETE
  11556. "SECURE_DELETE",
  11557. #endif
  11558. #ifdef SQLITE_SMALL_STACK
  11559. "SMALL_STACK",
  11560. #endif
  11561. #ifdef SQLITE_SOUNDEX
  11562. "SOUNDEX",
  11563. #endif
  11564. #ifdef SQLITE_TCL
  11565. "TCL",
  11566. #endif
  11567. #ifdef SQLITE_TEMP_STORE
  11568. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  11569. #endif
  11570. #ifdef SQLITE_TEST
  11571. "TEST",
  11572. #endif
  11573. #ifdef SQLITE_THREADSAFE
  11574. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  11575. #endif
  11576. #ifdef SQLITE_USE_ALLOCA
  11577. "USE_ALLOCA",
  11578. #endif
  11579. #ifdef SQLITE_ZERO_MALLOC
  11580. "ZERO_MALLOC"
  11581. #endif
  11582. };
  11583. /*
  11584. ** Given the name of a compile-time option, return true if that option
  11585. ** was used and false if not.
  11586. **
  11587. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  11588. ** is not required for a match.
  11589. */
  11590. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  11591. int i, n;
  11592. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  11593. n = sqlite3Strlen30(zOptName);
  11594. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  11595. ** linear search is adequate. No need for a binary search. */
  11596. for(i=0; i<ArraySize(azCompileOpt); i++){
  11597. if( (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
  11598. && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
  11599. }
  11600. return 0;
  11601. }
  11602. /*
  11603. ** Return the N-th compile-time option string. If N is out of range,
  11604. ** return a NULL pointer.
  11605. */
  11606. SQLITE_API const char *sqlite3_compileoption_get(int N){
  11607. if( N>=0 && N<ArraySize(azCompileOpt) ){
  11608. return azCompileOpt[N];
  11609. }
  11610. return 0;
  11611. }
  11612. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  11613. /************** End of ctime.c ***********************************************/
  11614. /************** Begin file status.c ******************************************/
  11615. /*
  11616. ** 2008 June 18
  11617. **
  11618. ** The author disclaims copyright to this source code. In place of
  11619. ** a legal notice, here is a blessing:
  11620. **
  11621. ** May you do good and not evil.
  11622. ** May you find forgiveness for yourself and forgive others.
  11623. ** May you share freely, never taking more than you give.
  11624. **
  11625. *************************************************************************
  11626. **
  11627. ** This module implements the sqlite3_status() interface and related
  11628. ** functionality.
  11629. */
  11630. /************** Include vdbeInt.h in the middle of status.c ******************/
  11631. /************** Begin file vdbeInt.h *****************************************/
  11632. /*
  11633. ** 2003 September 6
  11634. **
  11635. ** The author disclaims copyright to this source code. In place of
  11636. ** a legal notice, here is a blessing:
  11637. **
  11638. ** May you do good and not evil.
  11639. ** May you find forgiveness for yourself and forgive others.
  11640. ** May you share freely, never taking more than you give.
  11641. **
  11642. *************************************************************************
  11643. ** This is the header file for information that is private to the
  11644. ** VDBE. This information used to all be at the top of the single
  11645. ** source code file "vdbe.c". When that file became too big (over
  11646. ** 6000 lines long) it was split up into several smaller files and
  11647. ** this header information was factored out.
  11648. */
  11649. #ifndef _VDBEINT_H_
  11650. #define _VDBEINT_H_
  11651. /*
  11652. ** SQL is translated into a sequence of instructions to be
  11653. ** executed by a virtual machine. Each instruction is an instance
  11654. ** of the following structure.
  11655. */
  11656. typedef struct VdbeOp Op;
  11657. /*
  11658. ** Boolean values
  11659. */
  11660. typedef unsigned char Bool;
  11661. /*
  11662. ** A cursor is a pointer into a single BTree within a database file.
  11663. ** The cursor can seek to a BTree entry with a particular key, or
  11664. ** loop over all entries of the Btree. You can also insert new BTree
  11665. ** entries or retrieve the key or data from the entry that the cursor
  11666. ** is currently pointing to.
  11667. **
  11668. ** Every cursor that the virtual machine has open is represented by an
  11669. ** instance of the following structure.
  11670. */
  11671. struct VdbeCursor {
  11672. BtCursor *pCursor; /* The cursor structure of the backend */
  11673. Btree *pBt; /* Separate file holding temporary table */
  11674. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  11675. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  11676. int pseudoTableReg; /* Register holding pseudotable content. */
  11677. int nField; /* Number of fields in the header */
  11678. Bool zeroed; /* True if zeroed out and ready for reuse */
  11679. Bool rowidIsValid; /* True if lastRowid is valid */
  11680. Bool atFirst; /* True if pointing to first entry */
  11681. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  11682. Bool nullRow; /* True if pointing to a row with no data */
  11683. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  11684. Bool isTable; /* True if a table requiring integer keys */
  11685. Bool isIndex; /* True if an index containing keys only - no data */
  11686. Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
  11687. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  11688. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  11689. i64 seqCount; /* Sequence counter */
  11690. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  11691. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  11692. /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
  11693. ** OP_IsUnique opcode on this cursor. */
  11694. int seekResult;
  11695. /* Cached information about the header for the data record that the
  11696. ** cursor is currently pointing to. Only valid if cacheStatus matches
  11697. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  11698. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  11699. ** the cache is out of date.
  11700. **
  11701. ** aRow might point to (ephemeral) data for the current row, or it might
  11702. ** be NULL.
  11703. */
  11704. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  11705. int payloadSize; /* Total number of bytes in the record */
  11706. u32 *aType; /* Type values for all entries in the record */
  11707. u32 *aOffset; /* Cached offsets to the start of each columns data */
  11708. u8 *aRow; /* Data for the current row, if all on one page */
  11709. };
  11710. typedef struct VdbeCursor VdbeCursor;
  11711. /*
  11712. ** When a sub-program is executed (OP_Program), a structure of this type
  11713. ** is allocated to store the current value of the program counter, as
  11714. ** well as the current memory cell array and various other frame specific
  11715. ** values stored in the Vdbe struct. When the sub-program is finished,
  11716. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  11717. ** restoring the state of the VM to as it was before the sub-program
  11718. ** began executing.
  11719. **
  11720. ** The memory for a VdbeFrame object is allocated and managed by a memory
  11721. ** cell in the parent (calling) frame. When the memory cell is deleted or
  11722. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  11723. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  11724. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  11725. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  11726. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  11727. ** child frame are released.
  11728. **
  11729. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  11730. ** set to NULL if the currently executing frame is the main program.
  11731. */
  11732. typedef struct VdbeFrame VdbeFrame;
  11733. struct VdbeFrame {
  11734. Vdbe *v; /* VM this frame belongs to */
  11735. int pc; /* Program Counter in parent (calling) frame */
  11736. Op *aOp; /* Program instructions for parent frame */
  11737. int nOp; /* Size of aOp array */
  11738. Mem *aMem; /* Array of memory cells for parent frame */
  11739. int nMem; /* Number of entries in aMem */
  11740. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  11741. u16 nCursor; /* Number of entries in apCsr */
  11742. void *token; /* Copy of SubProgram.token */
  11743. int nChildMem; /* Number of memory cells for child frame */
  11744. int nChildCsr; /* Number of cursors for child frame */
  11745. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  11746. int nChange; /* Statement changes (Vdbe.nChanges) */
  11747. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  11748. };
  11749. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  11750. /*
  11751. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  11752. */
  11753. #define CACHE_STALE 0
  11754. /*
  11755. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  11756. ** structures. Each Mem struct may cache multiple representations (string,
  11757. ** integer etc.) of the same value.
  11758. */
  11759. struct Mem {
  11760. sqlite3 *db; /* The associated database connection */
  11761. char *z; /* String or BLOB value */
  11762. double r; /* Real value */
  11763. union {
  11764. i64 i; /* Integer value used when MEM_Int is set in flags */
  11765. int nZero; /* Used when bit MEM_Zero is set in flags */
  11766. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  11767. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  11768. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  11769. } u;
  11770. int n; /* Number of characters in string value, excluding '\0' */
  11771. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  11772. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  11773. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  11774. #ifdef SQLITE_DEBUG
  11775. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  11776. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  11777. #endif
  11778. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  11779. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  11780. };
  11781. /* One or more of the following flags are set to indicate the validOK
  11782. ** representations of the value stored in the Mem struct.
  11783. **
  11784. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  11785. ** No other flags may be set in this case.
  11786. **
  11787. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  11788. ** Usually this is encoded in the same unicode encoding as the main
  11789. ** database (see below for exceptions). If the MEM_Term flag is also
  11790. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  11791. ** flags may coexist with the MEM_Str flag.
  11792. */
  11793. #define MEM_Null 0x0001 /* Value is NULL */
  11794. #define MEM_Str 0x0002 /* Value is a string */
  11795. #define MEM_Int 0x0004 /* Value is an integer */
  11796. #define MEM_Real 0x0008 /* Value is a real number */
  11797. #define MEM_Blob 0x0010 /* Value is a BLOB */
  11798. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  11799. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  11800. #define MEM_Invalid 0x0080 /* Value is undefined */
  11801. #define MEM_TypeMask 0x00ff /* Mask of type bits */
  11802. /* Whenever Mem contains a valid string or blob representation, one of
  11803. ** the following flags must be set to determine the memory management
  11804. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  11805. ** string is \000 or \u0000 terminated
  11806. */
  11807. #define MEM_Term 0x0200 /* String rep is nul terminated */
  11808. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  11809. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  11810. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  11811. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  11812. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  11813. #ifdef SQLITE_OMIT_INCRBLOB
  11814. #undef MEM_Zero
  11815. #define MEM_Zero 0x0000
  11816. #endif
  11817. /*
  11818. ** Clear any existing type flags from a Mem and replace them with f
  11819. */
  11820. #define MemSetTypeFlag(p, f) \
  11821. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  11822. /*
  11823. ** Return true if a memory cell is not marked as invalid. This macro
  11824. ** is for use inside assert() statements only.
  11825. */
  11826. #ifdef SQLITE_DEBUG
  11827. #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
  11828. #endif
  11829. /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
  11830. ** additional information about auxiliary information bound to arguments
  11831. ** of the function. This is used to implement the sqlite3_get_auxdata()
  11832. ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
  11833. ** that can be associated with a constant argument to a function. This
  11834. ** allows functions such as "regexp" to compile their constant regular
  11835. ** expression argument once and reused the compiled code for multiple
  11836. ** invocations.
  11837. */
  11838. struct VdbeFunc {
  11839. FuncDef *pFunc; /* The definition of the function */
  11840. int nAux; /* Number of entries allocated for apAux[] */
  11841. struct AuxData {
  11842. void *pAux; /* Aux data for the i-th argument */
  11843. void (*xDelete)(void *); /* Destructor for the aux data */
  11844. } apAux[1]; /* One slot for each function argument */
  11845. };
  11846. /*
  11847. ** The "context" argument for a installable function. A pointer to an
  11848. ** instance of this structure is the first argument to the routines used
  11849. ** implement the SQL functions.
  11850. **
  11851. ** There is a typedef for this structure in sqlite.h. So all routines,
  11852. ** even the public interface to SQLite, can use a pointer to this structure.
  11853. ** But this file is the only place where the internal details of this
  11854. ** structure are known.
  11855. **
  11856. ** This structure is defined inside of vdbeInt.h because it uses substructures
  11857. ** (Mem) which are only defined there.
  11858. */
  11859. struct sqlite3_context {
  11860. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  11861. VdbeFunc *pVdbeFunc; /* Auxilary data, if created. */
  11862. Mem s; /* The return value is stored here */
  11863. Mem *pMem; /* Memory cell used to store aggregate context */
  11864. int isError; /* Error code returned by the function. */
  11865. CollSeq *pColl; /* Collating sequence */
  11866. };
  11867. /*
  11868. ** An instance of the virtual machine. This structure contains the complete
  11869. ** state of the virtual machine.
  11870. **
  11871. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  11872. ** is really a pointer to an instance of this structure.
  11873. **
  11874. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  11875. ** any virtual table method invocations made by the vdbe program. It is
  11876. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  11877. ** variable is used for two purposes: to allow xDestroy methods to execute
  11878. ** "DROP TABLE" statements and to prevent some nasty side effects of
  11879. ** malloc failure when SQLite is invoked recursively by a virtual table
  11880. ** method function.
  11881. */
  11882. struct Vdbe {
  11883. sqlite3 *db; /* The database connection that owns this statement */
  11884. Op *aOp; /* Space to hold the virtual machine's program */
  11885. Mem *aMem; /* The memory locations */
  11886. Mem **apArg; /* Arguments to currently executing user function */
  11887. Mem *aColName; /* Column names to return */
  11888. Mem *pResultSet; /* Pointer to an array of results */
  11889. int nMem; /* Number of memory locations currently allocated */
  11890. int nOp; /* Number of instructions in the program */
  11891. int nOpAlloc; /* Number of slots allocated for aOp[] */
  11892. int nLabel; /* Number of labels used */
  11893. int nLabelAlloc; /* Number of slots allocated in aLabel[] */
  11894. int *aLabel; /* Space to hold the labels */
  11895. u16 nResColumn; /* Number of columns in one row of the result set */
  11896. u16 nCursor; /* Number of slots in apCsr[] */
  11897. u32 magic; /* Magic number for sanity checking */
  11898. char *zErrMsg; /* Error message written here */
  11899. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  11900. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  11901. Mem *aVar; /* Values for the OP_Variable opcode. */
  11902. char **azVar; /* Name of variables */
  11903. ynVar nVar; /* Number of entries in aVar[] */
  11904. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  11905. int pc; /* The program counter */
  11906. int rc; /* Value to return */
  11907. u8 errorAction; /* Recovery action to do in case of an error */
  11908. u8 okVar; /* True if azVar[] has been initialized */
  11909. u8 explain; /* True if EXPLAIN present on SQL command */
  11910. u8 changeCntOn; /* True to update the change-counter */
  11911. u8 expired; /* True if the VM needs to be recompiled */
  11912. u8 runOnlyOnce; /* Automatically expire on reset */
  11913. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  11914. u8 inVtabMethod; /* See comments above */
  11915. u8 usesStmtJournal; /* True if uses a statement journal */
  11916. u8 readOnly; /* True for read-only statements */
  11917. u8 isPrepareV2; /* True if prepared with prepare_v2() */
  11918. int nChange; /* Number of db changes made since last reset */
  11919. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  11920. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  11921. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  11922. int aCounter[3]; /* Counters used by sqlite3_stmt_status() */
  11923. #ifndef SQLITE_OMIT_TRACE
  11924. i64 startTime; /* Time when query started - used for profiling */
  11925. #endif
  11926. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  11927. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  11928. char *zSql; /* Text of the SQL statement that generated this */
  11929. void *pFree; /* Free this when deleting the vdbe */
  11930. #ifdef SQLITE_DEBUG
  11931. FILE *trace; /* Write an execution trace here, if not NULL */
  11932. #endif
  11933. VdbeFrame *pFrame; /* Parent frame */
  11934. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  11935. int nFrame; /* Number of frames in pFrame list */
  11936. u32 expmask; /* Binding to these vars invalidates VM */
  11937. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  11938. };
  11939. /*
  11940. ** The following are allowed values for Vdbe.magic
  11941. */
  11942. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  11943. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  11944. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  11945. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  11946. /*
  11947. ** Function prototypes
  11948. */
  11949. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  11950. void sqliteVdbePopStack(Vdbe*,int);
  11951. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  11952. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  11953. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  11954. #endif
  11955. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  11956. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  11957. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  11958. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  11959. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
  11960. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  11961. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  11962. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
  11963. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  11964. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  11965. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  11966. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  11967. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  11968. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  11969. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  11970. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  11971. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  11972. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  11973. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  11974. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  11975. #ifdef SQLITE_OMIT_FLOATING_POINT
  11976. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  11977. #else
  11978. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  11979. #endif
  11980. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  11981. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  11982. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  11983. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  11984. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  11985. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  11986. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  11987. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  11988. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  11989. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  11990. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  11991. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  11992. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  11993. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  11994. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  11995. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  11996. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  11997. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  11998. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  11999. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  12000. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
  12001. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  12002. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  12003. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  12004. #else
  12005. # define sqlite3VdbeEnter(X)
  12006. # define sqlite3VdbeLeave(X)
  12007. #endif
  12008. #ifdef SQLITE_DEBUG
  12009. SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
  12010. #endif
  12011. #ifndef SQLITE_OMIT_FOREIGN_KEY
  12012. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  12013. #else
  12014. # define sqlite3VdbeCheckFk(p,i) 0
  12015. #endif
  12016. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  12017. #ifdef SQLITE_DEBUG
  12018. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  12019. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  12020. #endif
  12021. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  12022. #ifndef SQLITE_OMIT_INCRBLOB
  12023. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  12024. #else
  12025. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  12026. #endif
  12027. #endif /* !defined(_VDBEINT_H_) */
  12028. /************** End of vdbeInt.h *********************************************/
  12029. /************** Continuing where we left off in status.c *********************/
  12030. /*
  12031. ** Variables in which to record status information.
  12032. */
  12033. typedef struct sqlite3StatType sqlite3StatType;
  12034. static SQLITE_WSD struct sqlite3StatType {
  12035. int nowValue[10]; /* Current value */
  12036. int mxValue[10]; /* Maximum value */
  12037. } sqlite3Stat = { {0,}, {0,} };
  12038. /* The "wsdStat" macro will resolve to the status information
  12039. ** state vector. If writable static data is unsupported on the target,
  12040. ** we have to locate the state vector at run-time. In the more common
  12041. ** case where writable static data is supported, wsdStat can refer directly
  12042. ** to the "sqlite3Stat" state vector declared above.
  12043. */
  12044. #ifdef SQLITE_OMIT_WSD
  12045. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  12046. # define wsdStat x[0]
  12047. #else
  12048. # define wsdStatInit
  12049. # define wsdStat sqlite3Stat
  12050. #endif
  12051. /*
  12052. ** Return the current value of a status parameter.
  12053. */
  12054. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  12055. wsdStatInit;
  12056. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12057. return wsdStat.nowValue[op];
  12058. }
  12059. /*
  12060. ** Add N to the value of a status record. It is assumed that the
  12061. ** caller holds appropriate locks.
  12062. */
  12063. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  12064. wsdStatInit;
  12065. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12066. wsdStat.nowValue[op] += N;
  12067. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  12068. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  12069. }
  12070. }
  12071. /*
  12072. ** Set the value of a status to X.
  12073. */
  12074. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  12075. wsdStatInit;
  12076. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  12077. wsdStat.nowValue[op] = X;
  12078. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  12079. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  12080. }
  12081. }
  12082. /*
  12083. ** Query status information.
  12084. **
  12085. ** This implementation assumes that reading or writing an aligned
  12086. ** 32-bit integer is an atomic operation. If that assumption is not true,
  12087. ** then this routine is not threadsafe.
  12088. */
  12089. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  12090. wsdStatInit;
  12091. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  12092. return SQLITE_MISUSE_BKPT;
  12093. }
  12094. *pCurrent = wsdStat.nowValue[op];
  12095. *pHighwater = wsdStat.mxValue[op];
  12096. if( resetFlag ){
  12097. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  12098. }
  12099. return SQLITE_OK;
  12100. }
  12101. /*
  12102. ** Query status information for a single database connection
  12103. */
  12104. SQLITE_API int sqlite3_db_status(
  12105. sqlite3 *db, /* The database connection whose status is desired */
  12106. int op, /* Status verb */
  12107. int *pCurrent, /* Write current value here */
  12108. int *pHighwater, /* Write high-water mark here */
  12109. int resetFlag /* Reset high-water mark if true */
  12110. ){
  12111. int rc = SQLITE_OK; /* Return code */
  12112. sqlite3_mutex_enter(db->mutex);
  12113. switch( op ){
  12114. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  12115. *pCurrent = db->lookaside.nOut;
  12116. *pHighwater = db->lookaside.mxOut;
  12117. if( resetFlag ){
  12118. db->lookaside.mxOut = db->lookaside.nOut;
  12119. }
  12120. break;
  12121. }
  12122. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  12123. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  12124. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  12125. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  12126. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  12127. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  12128. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  12129. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  12130. *pCurrent = 0;
  12131. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  12132. if( resetFlag ){
  12133. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  12134. }
  12135. break;
  12136. }
  12137. /*
  12138. ** Return an approximation for the amount of memory currently used
  12139. ** by all pagers associated with the given database connection. The
  12140. ** highwater mark is meaningless and is returned as zero.
  12141. */
  12142. case SQLITE_DBSTATUS_CACHE_USED: {
  12143. int totalUsed = 0;
  12144. int i;
  12145. sqlite3BtreeEnterAll(db);
  12146. for(i=0; i<db->nDb; i++){
  12147. Btree *pBt = db->aDb[i].pBt;
  12148. if( pBt ){
  12149. Pager *pPager = sqlite3BtreePager(pBt);
  12150. totalUsed += sqlite3PagerMemUsed(pPager);
  12151. }
  12152. }
  12153. sqlite3BtreeLeaveAll(db);
  12154. *pCurrent = totalUsed;
  12155. *pHighwater = 0;
  12156. break;
  12157. }
  12158. /*
  12159. ** *pCurrent gets an accurate estimate of the amount of memory used
  12160. ** to store the schema for all databases (main, temp, and any ATTACHed
  12161. ** databases. *pHighwater is set to zero.
  12162. */
  12163. case SQLITE_DBSTATUS_SCHEMA_USED: {
  12164. int i; /* Used to iterate through schemas */
  12165. int nByte = 0; /* Used to accumulate return value */
  12166. sqlite3BtreeEnterAll(db);
  12167. db->pnBytesFreed = &nByte;
  12168. for(i=0; i<db->nDb; i++){
  12169. Schema *pSchema = db->aDb[i].pSchema;
  12170. if( ALWAYS(pSchema!=0) ){
  12171. HashElem *p;
  12172. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  12173. pSchema->tblHash.count
  12174. + pSchema->trigHash.count
  12175. + pSchema->idxHash.count
  12176. + pSchema->fkeyHash.count
  12177. );
  12178. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  12179. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  12180. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  12181. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  12182. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  12183. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  12184. }
  12185. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  12186. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  12187. }
  12188. }
  12189. }
  12190. db->pnBytesFreed = 0;
  12191. sqlite3BtreeLeaveAll(db);
  12192. *pHighwater = 0;
  12193. *pCurrent = nByte;
  12194. break;
  12195. }
  12196. /*
  12197. ** *pCurrent gets an accurate estimate of the amount of memory used
  12198. ** to store all prepared statements.
  12199. ** *pHighwater is set to zero.
  12200. */
  12201. case SQLITE_DBSTATUS_STMT_USED: {
  12202. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  12203. int nByte = 0; /* Used to accumulate return value */
  12204. db->pnBytesFreed = &nByte;
  12205. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  12206. sqlite3VdbeDeleteObject(db, pVdbe);
  12207. }
  12208. db->pnBytesFreed = 0;
  12209. *pHighwater = 0;
  12210. *pCurrent = nByte;
  12211. break;
  12212. }
  12213. default: {
  12214. rc = SQLITE_ERROR;
  12215. }
  12216. }
  12217. sqlite3_mutex_leave(db->mutex);
  12218. return rc;
  12219. }
  12220. /************** End of status.c **********************************************/
  12221. /************** Begin file date.c ********************************************/
  12222. /*
  12223. ** 2003 October 31
  12224. **
  12225. ** The author disclaims copyright to this source code. In place of
  12226. ** a legal notice, here is a blessing:
  12227. **
  12228. ** May you do good and not evil.
  12229. ** May you find forgiveness for yourself and forgive others.
  12230. ** May you share freely, never taking more than you give.
  12231. **
  12232. *************************************************************************
  12233. ** This file contains the C functions that implement date and time
  12234. ** functions for SQLite.
  12235. **
  12236. ** There is only one exported symbol in this file - the function
  12237. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  12238. ** All other code has file scope.
  12239. **
  12240. ** SQLite processes all times and dates as Julian Day numbers. The
  12241. ** dates and times are stored as the number of days since noon
  12242. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  12243. ** calendar system.
  12244. **
  12245. ** 1970-01-01 00:00:00 is JD 2440587.5
  12246. ** 2000-01-01 00:00:00 is JD 2451544.5
  12247. **
  12248. ** This implemention requires years to be expressed as a 4-digit number
  12249. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  12250. ** be represented, even though julian day numbers allow a much wider
  12251. ** range of dates.
  12252. **
  12253. ** The Gregorian calendar system is used for all dates and times,
  12254. ** even those that predate the Gregorian calendar. Historians usually
  12255. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  12256. ** dates afterwards, depending on locale. Beware of this difference.
  12257. **
  12258. ** The conversion algorithms are implemented based on descriptions
  12259. ** in the following text:
  12260. **
  12261. ** Jean Meeus
  12262. ** Astronomical Algorithms, 2nd Edition, 1998
  12263. ** ISBM 0-943396-61-1
  12264. ** Willmann-Bell, Inc
  12265. ** Richmond, Virginia (USA)
  12266. */
  12267. #include <time.h>
  12268. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  12269. /*
  12270. ** On recent Windows platforms, the localtime_s() function is available
  12271. ** as part of the "Secure CRT". It is essentially equivalent to
  12272. ** localtime_r() available under most POSIX platforms, except that the
  12273. ** order of the parameters is reversed.
  12274. **
  12275. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  12276. **
  12277. ** If the user has not indicated to use localtime_r() or localtime_s()
  12278. ** already, check for an MSVC build environment that provides
  12279. ** localtime_s().
  12280. */
  12281. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  12282. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  12283. #define HAVE_LOCALTIME_S 1
  12284. #endif
  12285. /*
  12286. ** A structure for holding a single date and time.
  12287. */
  12288. typedef struct DateTime DateTime;
  12289. struct DateTime {
  12290. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  12291. int Y, M, D; /* Year, month, and day */
  12292. int h, m; /* Hour and minutes */
  12293. int tz; /* Timezone offset in minutes */
  12294. double s; /* Seconds */
  12295. char validYMD; /* True (1) if Y,M,D are valid */
  12296. char validHMS; /* True (1) if h,m,s are valid */
  12297. char validJD; /* True (1) if iJD is valid */
  12298. char validTZ; /* True (1) if tz is valid */
  12299. };
  12300. /*
  12301. ** Convert zDate into one or more integers. Additional arguments
  12302. ** come in groups of 5 as follows:
  12303. **
  12304. ** N number of digits in the integer
  12305. ** min minimum allowed value of the integer
  12306. ** max maximum allowed value of the integer
  12307. ** nextC first character after the integer
  12308. ** pVal where to write the integers value.
  12309. **
  12310. ** Conversions continue until one with nextC==0 is encountered.
  12311. ** The function returns the number of successful conversions.
  12312. */
  12313. static int getDigits(const char *zDate, ...){
  12314. va_list ap;
  12315. int val;
  12316. int N;
  12317. int min;
  12318. int max;
  12319. int nextC;
  12320. int *pVal;
  12321. int cnt = 0;
  12322. va_start(ap, zDate);
  12323. do{
  12324. N = va_arg(ap, int);
  12325. min = va_arg(ap, int);
  12326. max = va_arg(ap, int);
  12327. nextC = va_arg(ap, int);
  12328. pVal = va_arg(ap, int*);
  12329. val = 0;
  12330. while( N-- ){
  12331. if( !sqlite3Isdigit(*zDate) ){
  12332. goto end_getDigits;
  12333. }
  12334. val = val*10 + *zDate - '0';
  12335. zDate++;
  12336. }
  12337. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  12338. goto end_getDigits;
  12339. }
  12340. *pVal = val;
  12341. zDate++;
  12342. cnt++;
  12343. }while( nextC );
  12344. end_getDigits:
  12345. va_end(ap);
  12346. return cnt;
  12347. }
  12348. /*
  12349. ** Parse a timezone extension on the end of a date-time.
  12350. ** The extension is of the form:
  12351. **
  12352. ** (+/-)HH:MM
  12353. **
  12354. ** Or the "zulu" notation:
  12355. **
  12356. ** Z
  12357. **
  12358. ** If the parse is successful, write the number of minutes
  12359. ** of change in p->tz and return 0. If a parser error occurs,
  12360. ** return non-zero.
  12361. **
  12362. ** A missing specifier is not considered an error.
  12363. */
  12364. static int parseTimezone(const char *zDate, DateTime *p){
  12365. int sgn = 0;
  12366. int nHr, nMn;
  12367. int c;
  12368. while( sqlite3Isspace(*zDate) ){ zDate++; }
  12369. p->tz = 0;
  12370. c = *zDate;
  12371. if( c=='-' ){
  12372. sgn = -1;
  12373. }else if( c=='+' ){
  12374. sgn = +1;
  12375. }else if( c=='Z' || c=='z' ){
  12376. zDate++;
  12377. goto zulu_time;
  12378. }else{
  12379. return c!=0;
  12380. }
  12381. zDate++;
  12382. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  12383. return 1;
  12384. }
  12385. zDate += 5;
  12386. p->tz = sgn*(nMn + nHr*60);
  12387. zulu_time:
  12388. while( sqlite3Isspace(*zDate) ){ zDate++; }
  12389. return *zDate!=0;
  12390. }
  12391. /*
  12392. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  12393. ** The HH, MM, and SS must each be exactly 2 digits. The
  12394. ** fractional seconds FFFF can be one or more digits.
  12395. **
  12396. ** Return 1 if there is a parsing error and 0 on success.
  12397. */
  12398. static int parseHhMmSs(const char *zDate, DateTime *p){
  12399. int h, m, s;
  12400. double ms = 0.0;
  12401. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  12402. return 1;
  12403. }
  12404. zDate += 5;
  12405. if( *zDate==':' ){
  12406. zDate++;
  12407. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  12408. return 1;
  12409. }
  12410. zDate += 2;
  12411. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  12412. double rScale = 1.0;
  12413. zDate++;
  12414. while( sqlite3Isdigit(*zDate) ){
  12415. ms = ms*10.0 + *zDate - '0';
  12416. rScale *= 10.0;
  12417. zDate++;
  12418. }
  12419. ms /= rScale;
  12420. }
  12421. }else{
  12422. s = 0;
  12423. }
  12424. p->validJD = 0;
  12425. p->validHMS = 1;
  12426. p->h = h;
  12427. p->m = m;
  12428. p->s = s + ms;
  12429. if( parseTimezone(zDate, p) ) return 1;
  12430. p->validTZ = (p->tz!=0)?1:0;
  12431. return 0;
  12432. }
  12433. /*
  12434. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  12435. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  12436. **
  12437. ** Reference: Meeus page 61
  12438. */
  12439. static void computeJD(DateTime *p){
  12440. int Y, M, D, A, B, X1, X2;
  12441. if( p->validJD ) return;
  12442. if( p->validYMD ){
  12443. Y = p->Y;
  12444. M = p->M;
  12445. D = p->D;
  12446. }else{
  12447. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  12448. M = 1;
  12449. D = 1;
  12450. }
  12451. if( M<=2 ){
  12452. Y--;
  12453. M += 12;
  12454. }
  12455. A = Y/100;
  12456. B = 2 - A + (A/4);
  12457. X1 = 36525*(Y+4716)/100;
  12458. X2 = 306001*(M+1)/10000;
  12459. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  12460. p->validJD = 1;
  12461. if( p->validHMS ){
  12462. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  12463. if( p->validTZ ){
  12464. p->iJD -= p->tz*60000;
  12465. p->validYMD = 0;
  12466. p->validHMS = 0;
  12467. p->validTZ = 0;
  12468. }
  12469. }
  12470. }
  12471. /*
  12472. ** Parse dates of the form
  12473. **
  12474. ** YYYY-MM-DD HH:MM:SS.FFF
  12475. ** YYYY-MM-DD HH:MM:SS
  12476. ** YYYY-MM-DD HH:MM
  12477. ** YYYY-MM-DD
  12478. **
  12479. ** Write the result into the DateTime structure and return 0
  12480. ** on success and 1 if the input string is not a well-formed
  12481. ** date.
  12482. */
  12483. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  12484. int Y, M, D, neg;
  12485. if( zDate[0]=='-' ){
  12486. zDate++;
  12487. neg = 1;
  12488. }else{
  12489. neg = 0;
  12490. }
  12491. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  12492. return 1;
  12493. }
  12494. zDate += 10;
  12495. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  12496. if( parseHhMmSs(zDate, p)==0 ){
  12497. /* We got the time */
  12498. }else if( *zDate==0 ){
  12499. p->validHMS = 0;
  12500. }else{
  12501. return 1;
  12502. }
  12503. p->validJD = 0;
  12504. p->validYMD = 1;
  12505. p->Y = neg ? -Y : Y;
  12506. p->M = M;
  12507. p->D = D;
  12508. if( p->validTZ ){
  12509. computeJD(p);
  12510. }
  12511. return 0;
  12512. }
  12513. /*
  12514. ** Set the time to the current time reported by the VFS
  12515. */
  12516. static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  12517. sqlite3 *db = sqlite3_context_db_handle(context);
  12518. sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
  12519. p->validJD = 1;
  12520. }
  12521. /*
  12522. ** Attempt to parse the given string into a Julian Day Number. Return
  12523. ** the number of errors.
  12524. **
  12525. ** The following are acceptable forms for the input string:
  12526. **
  12527. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  12528. ** DDDD.DD
  12529. ** now
  12530. **
  12531. ** In the first form, the +/-HH:MM is always optional. The fractional
  12532. ** seconds extension (the ".FFF") is optional. The seconds portion
  12533. ** (":SS.FFF") is option. The year and date can be omitted as long
  12534. ** as there is a time string. The time string can be omitted as long
  12535. ** as there is a year and date.
  12536. */
  12537. static int parseDateOrTime(
  12538. sqlite3_context *context,
  12539. const char *zDate,
  12540. DateTime *p
  12541. ){
  12542. double r;
  12543. if( parseYyyyMmDd(zDate,p)==0 ){
  12544. return 0;
  12545. }else if( parseHhMmSs(zDate, p)==0 ){
  12546. return 0;
  12547. }else if( sqlite3StrICmp(zDate,"now")==0){
  12548. setDateTimeToCurrent(context, p);
  12549. return 0;
  12550. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  12551. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  12552. p->validJD = 1;
  12553. return 0;
  12554. }
  12555. return 1;
  12556. }
  12557. /*
  12558. ** Compute the Year, Month, and Day from the julian day number.
  12559. */
  12560. static void computeYMD(DateTime *p){
  12561. int Z, A, B, C, D, E, X1;
  12562. if( p->validYMD ) return;
  12563. if( !p->validJD ){
  12564. p->Y = 2000;
  12565. p->M = 1;
  12566. p->D = 1;
  12567. }else{
  12568. Z = (int)((p->iJD + 43200000)/86400000);
  12569. A = (int)((Z - 1867216.25)/36524.25);
  12570. A = Z + 1 + A - (A/4);
  12571. B = A + 1524;
  12572. C = (int)((B - 122.1)/365.25);
  12573. D = (36525*C)/100;
  12574. E = (int)((B-D)/30.6001);
  12575. X1 = (int)(30.6001*E);
  12576. p->D = B - D - X1;
  12577. p->M = E<14 ? E-1 : E-13;
  12578. p->Y = p->M>2 ? C - 4716 : C - 4715;
  12579. }
  12580. p->validYMD = 1;
  12581. }
  12582. /*
  12583. ** Compute the Hour, Minute, and Seconds from the julian day number.
  12584. */
  12585. static void computeHMS(DateTime *p){
  12586. int s;
  12587. if( p->validHMS ) return;
  12588. computeJD(p);
  12589. s = (int)((p->iJD + 43200000) % 86400000);
  12590. p->s = s/1000.0;
  12591. s = (int)p->s;
  12592. p->s -= s;
  12593. p->h = s/3600;
  12594. s -= p->h*3600;
  12595. p->m = s/60;
  12596. p->s += s - p->m*60;
  12597. p->validHMS = 1;
  12598. }
  12599. /*
  12600. ** Compute both YMD and HMS
  12601. */
  12602. static void computeYMD_HMS(DateTime *p){
  12603. computeYMD(p);
  12604. computeHMS(p);
  12605. }
  12606. /*
  12607. ** Clear the YMD and HMS and the TZ
  12608. */
  12609. static void clearYMD_HMS_TZ(DateTime *p){
  12610. p->validYMD = 0;
  12611. p->validHMS = 0;
  12612. p->validTZ = 0;
  12613. }
  12614. #ifndef SQLITE_OMIT_LOCALTIME
  12615. /*
  12616. ** Compute the difference (in milliseconds)
  12617. ** between localtime and UTC (a.k.a. GMT)
  12618. ** for the time value p where p is in UTC.
  12619. */
  12620. static sqlite3_int64 localtimeOffset(DateTime *p){
  12621. DateTime x, y;
  12622. time_t t;
  12623. x = *p;
  12624. computeYMD_HMS(&x);
  12625. if( x.Y<1971 || x.Y>=2038 ){
  12626. x.Y = 2000;
  12627. x.M = 1;
  12628. x.D = 1;
  12629. x.h = 0;
  12630. x.m = 0;
  12631. x.s = 0.0;
  12632. } else {
  12633. int s = (int)(x.s + 0.5);
  12634. x.s = s;
  12635. }
  12636. x.tz = 0;
  12637. x.validJD = 0;
  12638. computeJD(&x);
  12639. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  12640. #ifdef HAVE_LOCALTIME_R
  12641. {
  12642. struct tm sLocal;
  12643. localtime_r(&t, &sLocal);
  12644. y.Y = sLocal.tm_year + 1900;
  12645. y.M = sLocal.tm_mon + 1;
  12646. y.D = sLocal.tm_mday;
  12647. y.h = sLocal.tm_hour;
  12648. y.m = sLocal.tm_min;
  12649. y.s = sLocal.tm_sec;
  12650. }
  12651. #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
  12652. {
  12653. struct tm sLocal;
  12654. localtime_s(&sLocal, &t);
  12655. y.Y = sLocal.tm_year + 1900;
  12656. y.M = sLocal.tm_mon + 1;
  12657. y.D = sLocal.tm_mday;
  12658. y.h = sLocal.tm_hour;
  12659. y.m = sLocal.tm_min;
  12660. y.s = sLocal.tm_sec;
  12661. }
  12662. #else
  12663. {
  12664. struct tm *pTm;
  12665. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  12666. pTm = localtime(&t);
  12667. y.Y = pTm->tm_year + 1900;
  12668. y.M = pTm->tm_mon + 1;
  12669. y.D = pTm->tm_mday;
  12670. y.h = pTm->tm_hour;
  12671. y.m = pTm->tm_min;
  12672. y.s = pTm->tm_sec;
  12673. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  12674. }
  12675. #endif
  12676. y.validYMD = 1;
  12677. y.validHMS = 1;
  12678. y.validJD = 0;
  12679. y.validTZ = 0;
  12680. computeJD(&y);
  12681. return y.iJD - x.iJD;
  12682. }
  12683. #endif /* SQLITE_OMIT_LOCALTIME */
  12684. /*
  12685. ** Process a modifier to a date-time stamp. The modifiers are
  12686. ** as follows:
  12687. **
  12688. ** NNN days
  12689. ** NNN hours
  12690. ** NNN minutes
  12691. ** NNN.NNNN seconds
  12692. ** NNN months
  12693. ** NNN years
  12694. ** start of month
  12695. ** start of year
  12696. ** start of week
  12697. ** start of day
  12698. ** weekday N
  12699. ** unixepoch
  12700. ** localtime
  12701. ** utc
  12702. **
  12703. ** Return 0 on success and 1 if there is any kind of error.
  12704. */
  12705. static int parseModifier(const char *zMod, DateTime *p){
  12706. int rc = 1;
  12707. int n;
  12708. double r;
  12709. char *z, zBuf[30];
  12710. z = zBuf;
  12711. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  12712. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  12713. }
  12714. z[n] = 0;
  12715. switch( z[0] ){
  12716. #ifndef SQLITE_OMIT_LOCALTIME
  12717. case 'l': {
  12718. /* localtime
  12719. **
  12720. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  12721. ** show local time.
  12722. */
  12723. if( strcmp(z, "localtime")==0 ){
  12724. computeJD(p);
  12725. p->iJD += localtimeOffset(p);
  12726. clearYMD_HMS_TZ(p);
  12727. rc = 0;
  12728. }
  12729. break;
  12730. }
  12731. #endif
  12732. case 'u': {
  12733. /*
  12734. ** unixepoch
  12735. **
  12736. ** Treat the current value of p->iJD as the number of
  12737. ** seconds since 1970. Convert to a real julian day number.
  12738. */
  12739. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  12740. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  12741. clearYMD_HMS_TZ(p);
  12742. rc = 0;
  12743. }
  12744. #ifndef SQLITE_OMIT_LOCALTIME
  12745. else if( strcmp(z, "utc")==0 ){
  12746. sqlite3_int64 c1;
  12747. computeJD(p);
  12748. c1 = localtimeOffset(p);
  12749. p->iJD -= c1;
  12750. clearYMD_HMS_TZ(p);
  12751. p->iJD += c1 - localtimeOffset(p);
  12752. rc = 0;
  12753. }
  12754. #endif
  12755. break;
  12756. }
  12757. case 'w': {
  12758. /*
  12759. ** weekday N
  12760. **
  12761. ** Move the date to the same time on the next occurrence of
  12762. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  12763. ** date is already on the appropriate weekday, this is a no-op.
  12764. */
  12765. if( strncmp(z, "weekday ", 8)==0
  12766. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  12767. && (n=(int)r)==r && n>=0 && r<7 ){
  12768. sqlite3_int64 Z;
  12769. computeYMD_HMS(p);
  12770. p->validTZ = 0;
  12771. p->validJD = 0;
  12772. computeJD(p);
  12773. Z = ((p->iJD + 129600000)/86400000) % 7;
  12774. if( Z>n ) Z -= 7;
  12775. p->iJD += (n - Z)*86400000;
  12776. clearYMD_HMS_TZ(p);
  12777. rc = 0;
  12778. }
  12779. break;
  12780. }
  12781. case 's': {
  12782. /*
  12783. ** start of TTTTT
  12784. **
  12785. ** Move the date backwards to the beginning of the current day,
  12786. ** or month or year.
  12787. */
  12788. if( strncmp(z, "start of ", 9)!=0 ) break;
  12789. z += 9;
  12790. computeYMD(p);
  12791. p->validHMS = 1;
  12792. p->h = p->m = 0;
  12793. p->s = 0.0;
  12794. p->validTZ = 0;
  12795. p->validJD = 0;
  12796. if( strcmp(z,"month")==0 ){
  12797. p->D = 1;
  12798. rc = 0;
  12799. }else if( strcmp(z,"year")==0 ){
  12800. computeYMD(p);
  12801. p->M = 1;
  12802. p->D = 1;
  12803. rc = 0;
  12804. }else if( strcmp(z,"day")==0 ){
  12805. rc = 0;
  12806. }
  12807. break;
  12808. }
  12809. case '+':
  12810. case '-':
  12811. case '0':
  12812. case '1':
  12813. case '2':
  12814. case '3':
  12815. case '4':
  12816. case '5':
  12817. case '6':
  12818. case '7':
  12819. case '8':
  12820. case '9': {
  12821. double rRounder;
  12822. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  12823. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  12824. rc = 1;
  12825. break;
  12826. }
  12827. if( z[n]==':' ){
  12828. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  12829. ** specified number of hours, minutes, seconds, and fractional seconds
  12830. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  12831. ** omitted.
  12832. */
  12833. const char *z2 = z;
  12834. DateTime tx;
  12835. sqlite3_int64 day;
  12836. if( !sqlite3Isdigit(*z2) ) z2++;
  12837. memset(&tx, 0, sizeof(tx));
  12838. if( parseHhMmSs(z2, &tx) ) break;
  12839. computeJD(&tx);
  12840. tx.iJD -= 43200000;
  12841. day = tx.iJD/86400000;
  12842. tx.iJD -= day*86400000;
  12843. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  12844. computeJD(p);
  12845. clearYMD_HMS_TZ(p);
  12846. p->iJD += tx.iJD;
  12847. rc = 0;
  12848. break;
  12849. }
  12850. z += n;
  12851. while( sqlite3Isspace(*z) ) z++;
  12852. n = sqlite3Strlen30(z);
  12853. if( n>10 || n<3 ) break;
  12854. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  12855. computeJD(p);
  12856. rc = 0;
  12857. rRounder = r<0 ? -0.5 : +0.5;
  12858. if( n==3 && strcmp(z,"day")==0 ){
  12859. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  12860. }else if( n==4 && strcmp(z,"hour")==0 ){
  12861. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  12862. }else if( n==6 && strcmp(z,"minute")==0 ){
  12863. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  12864. }else if( n==6 && strcmp(z,"second")==0 ){
  12865. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  12866. }else if( n==5 && strcmp(z,"month")==0 ){
  12867. int x, y;
  12868. computeYMD_HMS(p);
  12869. p->M += (int)r;
  12870. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  12871. p->Y += x;
  12872. p->M -= x*12;
  12873. p->validJD = 0;
  12874. computeJD(p);
  12875. y = (int)r;
  12876. if( y!=r ){
  12877. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  12878. }
  12879. }else if( n==4 && strcmp(z,"year")==0 ){
  12880. int y = (int)r;
  12881. computeYMD_HMS(p);
  12882. p->Y += y;
  12883. p->validJD = 0;
  12884. computeJD(p);
  12885. if( y!=r ){
  12886. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  12887. }
  12888. }else{
  12889. rc = 1;
  12890. }
  12891. clearYMD_HMS_TZ(p);
  12892. break;
  12893. }
  12894. default: {
  12895. break;
  12896. }
  12897. }
  12898. return rc;
  12899. }
  12900. /*
  12901. ** Process time function arguments. argv[0] is a date-time stamp.
  12902. ** argv[1] and following are modifiers. Parse them all and write
  12903. ** the resulting time into the DateTime structure p. Return 0
  12904. ** on success and 1 if there are any errors.
  12905. **
  12906. ** If there are zero parameters (if even argv[0] is undefined)
  12907. ** then assume a default value of "now" for argv[0].
  12908. */
  12909. static int isDate(
  12910. sqlite3_context *context,
  12911. int argc,
  12912. sqlite3_value **argv,
  12913. DateTime *p
  12914. ){
  12915. int i;
  12916. const unsigned char *z;
  12917. int eType;
  12918. memset(p, 0, sizeof(*p));
  12919. if( argc==0 ){
  12920. setDateTimeToCurrent(context, p);
  12921. }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  12922. || eType==SQLITE_INTEGER ){
  12923. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  12924. p->validJD = 1;
  12925. }else{
  12926. z = sqlite3_value_text(argv[0]);
  12927. if( !z || parseDateOrTime(context, (char*)z, p) ){
  12928. return 1;
  12929. }
  12930. }
  12931. for(i=1; i<argc; i++){
  12932. if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
  12933. return 1;
  12934. }
  12935. }
  12936. return 0;
  12937. }
  12938. /*
  12939. ** The following routines implement the various date and time functions
  12940. ** of SQLite.
  12941. */
  12942. /*
  12943. ** julianday( TIMESTRING, MOD, MOD, ...)
  12944. **
  12945. ** Return the julian day number of the date specified in the arguments
  12946. */
  12947. static void juliandayFunc(
  12948. sqlite3_context *context,
  12949. int argc,
  12950. sqlite3_value **argv
  12951. ){
  12952. DateTime x;
  12953. if( isDate(context, argc, argv, &x)==0 ){
  12954. computeJD(&x);
  12955. sqlite3_result_double(context, x.iJD/86400000.0);
  12956. }
  12957. }
  12958. /*
  12959. ** datetime( TIMESTRING, MOD, MOD, ...)
  12960. **
  12961. ** Return YYYY-MM-DD HH:MM:SS
  12962. */
  12963. static void datetimeFunc(
  12964. sqlite3_context *context,
  12965. int argc,
  12966. sqlite3_value **argv
  12967. ){
  12968. DateTime x;
  12969. if( isDate(context, argc, argv, &x)==0 ){
  12970. char zBuf[100];
  12971. computeYMD_HMS(&x);
  12972. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  12973. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  12974. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  12975. }
  12976. }
  12977. /*
  12978. ** time( TIMESTRING, MOD, MOD, ...)
  12979. **
  12980. ** Return HH:MM:SS
  12981. */
  12982. static void timeFunc(
  12983. sqlite3_context *context,
  12984. int argc,
  12985. sqlite3_value **argv
  12986. ){
  12987. DateTime x;
  12988. if( isDate(context, argc, argv, &x)==0 ){
  12989. char zBuf[100];
  12990. computeHMS(&x);
  12991. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  12992. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  12993. }
  12994. }
  12995. /*
  12996. ** date( TIMESTRING, MOD, MOD, ...)
  12997. **
  12998. ** Return YYYY-MM-DD
  12999. */
  13000. static void dateFunc(
  13001. sqlite3_context *context,
  13002. int argc,
  13003. sqlite3_value **argv
  13004. ){
  13005. DateTime x;
  13006. if( isDate(context, argc, argv, &x)==0 ){
  13007. char zBuf[100];
  13008. computeYMD(&x);
  13009. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  13010. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13011. }
  13012. }
  13013. /*
  13014. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  13015. **
  13016. ** Return a string described by FORMAT. Conversions as follows:
  13017. **
  13018. ** %d day of month
  13019. ** %f ** fractional seconds SS.SSS
  13020. ** %H hour 00-24
  13021. ** %j day of year 000-366
  13022. ** %J ** Julian day number
  13023. ** %m month 01-12
  13024. ** %M minute 00-59
  13025. ** %s seconds since 1970-01-01
  13026. ** %S seconds 00-59
  13027. ** %w day of week 0-6 sunday==0
  13028. ** %W week of year 00-53
  13029. ** %Y year 0000-9999
  13030. ** %% %
  13031. */
  13032. static void strftimeFunc(
  13033. sqlite3_context *context,
  13034. int argc,
  13035. sqlite3_value **argv
  13036. ){
  13037. DateTime x;
  13038. u64 n;
  13039. size_t i,j;
  13040. char *z;
  13041. sqlite3 *db;
  13042. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  13043. char zBuf[100];
  13044. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  13045. db = sqlite3_context_db_handle(context);
  13046. for(i=0, n=1; zFmt[i]; i++, n++){
  13047. if( zFmt[i]=='%' ){
  13048. switch( zFmt[i+1] ){
  13049. case 'd':
  13050. case 'H':
  13051. case 'm':
  13052. case 'M':
  13053. case 'S':
  13054. case 'W':
  13055. n++;
  13056. /* fall thru */
  13057. case 'w':
  13058. case '%':
  13059. break;
  13060. case 'f':
  13061. n += 8;
  13062. break;
  13063. case 'j':
  13064. n += 3;
  13065. break;
  13066. case 'Y':
  13067. n += 8;
  13068. break;
  13069. case 's':
  13070. case 'J':
  13071. n += 50;
  13072. break;
  13073. default:
  13074. return; /* ERROR. return a NULL */
  13075. }
  13076. i++;
  13077. }
  13078. }
  13079. testcase( n==sizeof(zBuf)-1 );
  13080. testcase( n==sizeof(zBuf) );
  13081. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  13082. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  13083. if( n<sizeof(zBuf) ){
  13084. z = zBuf;
  13085. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  13086. sqlite3_result_error_toobig(context);
  13087. return;
  13088. }else{
  13089. z = sqlite3DbMallocRaw(db, (int)n);
  13090. if( z==0 ){
  13091. sqlite3_result_error_nomem(context);
  13092. return;
  13093. }
  13094. }
  13095. computeJD(&x);
  13096. computeYMD_HMS(&x);
  13097. for(i=j=0; zFmt[i]; i++){
  13098. if( zFmt[i]!='%' ){
  13099. z[j++] = zFmt[i];
  13100. }else{
  13101. i++;
  13102. switch( zFmt[i] ){
  13103. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  13104. case 'f': {
  13105. double s = x.s;
  13106. if( s>59.999 ) s = 59.999;
  13107. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  13108. j += sqlite3Strlen30(&z[j]);
  13109. break;
  13110. }
  13111. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  13112. case 'W': /* Fall thru */
  13113. case 'j': {
  13114. int nDay; /* Number of days since 1st day of year */
  13115. DateTime y = x;
  13116. y.validJD = 0;
  13117. y.M = 1;
  13118. y.D = 1;
  13119. computeJD(&y);
  13120. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  13121. if( zFmt[i]=='W' ){
  13122. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  13123. wd = (int)(((x.iJD+43200000)/86400000)%7);
  13124. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  13125. j += 2;
  13126. }else{
  13127. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  13128. j += 3;
  13129. }
  13130. break;
  13131. }
  13132. case 'J': {
  13133. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  13134. j+=sqlite3Strlen30(&z[j]);
  13135. break;
  13136. }
  13137. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  13138. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  13139. case 's': {
  13140. sqlite3_snprintf(30,&z[j],"%lld",
  13141. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  13142. j += sqlite3Strlen30(&z[j]);
  13143. break;
  13144. }
  13145. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  13146. case 'w': {
  13147. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  13148. break;
  13149. }
  13150. case 'Y': {
  13151. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  13152. break;
  13153. }
  13154. default: z[j++] = '%'; break;
  13155. }
  13156. }
  13157. }
  13158. z[j] = 0;
  13159. sqlite3_result_text(context, z, -1,
  13160. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  13161. }
  13162. /*
  13163. ** current_time()
  13164. **
  13165. ** This function returns the same value as time('now').
  13166. */
  13167. static void ctimeFunc(
  13168. sqlite3_context *context,
  13169. int NotUsed,
  13170. sqlite3_value **NotUsed2
  13171. ){
  13172. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  13173. timeFunc(context, 0, 0);
  13174. }
  13175. /*
  13176. ** current_date()
  13177. **
  13178. ** This function returns the same value as date('now').
  13179. */
  13180. static void cdateFunc(
  13181. sqlite3_context *context,
  13182. int NotUsed,
  13183. sqlite3_value **NotUsed2
  13184. ){
  13185. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  13186. dateFunc(context, 0, 0);
  13187. }
  13188. /*
  13189. ** current_timestamp()
  13190. **
  13191. ** This function returns the same value as datetime('now').
  13192. */
  13193. static void ctimestampFunc(
  13194. sqlite3_context *context,
  13195. int NotUsed,
  13196. sqlite3_value **NotUsed2
  13197. ){
  13198. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  13199. datetimeFunc(context, 0, 0);
  13200. }
  13201. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  13202. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  13203. /*
  13204. ** If the library is compiled to omit the full-scale date and time
  13205. ** handling (to get a smaller binary), the following minimal version
  13206. ** of the functions current_time(), current_date() and current_timestamp()
  13207. ** are included instead. This is to support column declarations that
  13208. ** include "DEFAULT CURRENT_TIME" etc.
  13209. **
  13210. ** This function uses the C-library functions time(), gmtime()
  13211. ** and strftime(). The format string to pass to strftime() is supplied
  13212. ** as the user-data for the function.
  13213. */
  13214. static void currentTimeFunc(
  13215. sqlite3_context *context,
  13216. int argc,
  13217. sqlite3_value **argv
  13218. ){
  13219. time_t t;
  13220. char *zFormat = (char *)sqlite3_user_data(context);
  13221. sqlite3 *db;
  13222. sqlite3_int64 iT;
  13223. char zBuf[20];
  13224. UNUSED_PARAMETER(argc);
  13225. UNUSED_PARAMETER(argv);
  13226. db = sqlite3_context_db_handle(context);
  13227. sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
  13228. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  13229. #ifdef HAVE_GMTIME_R
  13230. {
  13231. struct tm sNow;
  13232. gmtime_r(&t, &sNow);
  13233. strftime(zBuf, 20, zFormat, &sNow);
  13234. }
  13235. #else
  13236. {
  13237. struct tm *pTm;
  13238. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  13239. pTm = gmtime(&t);
  13240. strftime(zBuf, 20, zFormat, pTm);
  13241. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  13242. }
  13243. #endif
  13244. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  13245. }
  13246. #endif
  13247. /*
  13248. ** This function registered all of the above C functions as SQL
  13249. ** functions. This should be the only routine in this file with
  13250. ** external linkage.
  13251. */
  13252. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  13253. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  13254. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  13255. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  13256. FUNCTION(date, -1, 0, 0, dateFunc ),
  13257. FUNCTION(time, -1, 0, 0, timeFunc ),
  13258. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  13259. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  13260. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  13261. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  13262. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  13263. #else
  13264. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  13265. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  13266. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  13267. #endif
  13268. };
  13269. int i;
  13270. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  13271. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  13272. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  13273. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  13274. }
  13275. }
  13276. /************** End of date.c ************************************************/
  13277. /************** Begin file os.c **********************************************/
  13278. /*
  13279. ** 2005 November 29
  13280. **
  13281. ** The author disclaims copyright to this source code. In place of
  13282. ** a legal notice, here is a blessing:
  13283. **
  13284. ** May you do good and not evil.
  13285. ** May you find forgiveness for yourself and forgive others.
  13286. ** May you share freely, never taking more than you give.
  13287. **
  13288. ******************************************************************************
  13289. **
  13290. ** This file contains OS interface code that is common to all
  13291. ** architectures.
  13292. */
  13293. #define _SQLITE_OS_C_ 1
  13294. #undef _SQLITE_OS_C_
  13295. /*
  13296. ** The default SQLite sqlite3_vfs implementations do not allocate
  13297. ** memory (actually, os_unix.c allocates a small amount of memory
  13298. ** from within OsOpen()), but some third-party implementations may.
  13299. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  13300. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  13301. **
  13302. ** The following functions are instrumented for malloc() failure
  13303. ** testing:
  13304. **
  13305. ** sqlite3OsOpen()
  13306. ** sqlite3OsRead()
  13307. ** sqlite3OsWrite()
  13308. ** sqlite3OsSync()
  13309. ** sqlite3OsLock()
  13310. **
  13311. */
  13312. #if defined(SQLITE_TEST)
  13313. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  13314. #define DO_OS_MALLOC_TEST(x) \
  13315. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  13316. void *pTstAlloc = sqlite3Malloc(10); \
  13317. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  13318. sqlite3_free(pTstAlloc); \
  13319. }
  13320. #else
  13321. #define DO_OS_MALLOC_TEST(x)
  13322. #endif
  13323. /*
  13324. ** The following routines are convenience wrappers around methods
  13325. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  13326. ** of this would be completely automatic if SQLite were coded using
  13327. ** C++ instead of plain old C.
  13328. */
  13329. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  13330. int rc = SQLITE_OK;
  13331. if( pId->pMethods ){
  13332. rc = pId->pMethods->xClose(pId);
  13333. pId->pMethods = 0;
  13334. }
  13335. return rc;
  13336. }
  13337. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  13338. DO_OS_MALLOC_TEST(id);
  13339. return id->pMethods->xRead(id, pBuf, amt, offset);
  13340. }
  13341. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  13342. DO_OS_MALLOC_TEST(id);
  13343. return id->pMethods->xWrite(id, pBuf, amt, offset);
  13344. }
  13345. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  13346. return id->pMethods->xTruncate(id, size);
  13347. }
  13348. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  13349. DO_OS_MALLOC_TEST(id);
  13350. return id->pMethods->xSync(id, flags);
  13351. }
  13352. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  13353. DO_OS_MALLOC_TEST(id);
  13354. return id->pMethods->xFileSize(id, pSize);
  13355. }
  13356. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  13357. DO_OS_MALLOC_TEST(id);
  13358. return id->pMethods->xLock(id, lockType);
  13359. }
  13360. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  13361. return id->pMethods->xUnlock(id, lockType);
  13362. }
  13363. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  13364. DO_OS_MALLOC_TEST(id);
  13365. return id->pMethods->xCheckReservedLock(id, pResOut);
  13366. }
  13367. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  13368. return id->pMethods->xFileControl(id, op, pArg);
  13369. }
  13370. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  13371. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  13372. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  13373. }
  13374. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  13375. return id->pMethods->xDeviceCharacteristics(id);
  13376. }
  13377. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  13378. return id->pMethods->xShmLock(id, offset, n, flags);
  13379. }
  13380. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  13381. id->pMethods->xShmBarrier(id);
  13382. }
  13383. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  13384. return id->pMethods->xShmUnmap(id, deleteFlag);
  13385. }
  13386. SQLITE_PRIVATE int sqlite3OsShmMap(
  13387. sqlite3_file *id, /* Database file handle */
  13388. int iPage,
  13389. int pgsz,
  13390. int bExtend, /* True to extend file if necessary */
  13391. void volatile **pp /* OUT: Pointer to mapping */
  13392. ){
  13393. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  13394. }
  13395. /*
  13396. ** The next group of routines are convenience wrappers around the
  13397. ** VFS methods.
  13398. */
  13399. SQLITE_PRIVATE int sqlite3OsOpen(
  13400. sqlite3_vfs *pVfs,
  13401. const char *zPath,
  13402. sqlite3_file *pFile,
  13403. int flags,
  13404. int *pFlagsOut
  13405. ){
  13406. int rc;
  13407. DO_OS_MALLOC_TEST(0);
  13408. /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  13409. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  13410. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  13411. ** reaching the VFS. */
  13412. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
  13413. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  13414. return rc;
  13415. }
  13416. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  13417. return pVfs->xDelete(pVfs, zPath, dirSync);
  13418. }
  13419. SQLITE_PRIVATE int sqlite3OsAccess(
  13420. sqlite3_vfs *pVfs,
  13421. const char *zPath,
  13422. int flags,
  13423. int *pResOut
  13424. ){
  13425. DO_OS_MALLOC_TEST(0);
  13426. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  13427. }
  13428. SQLITE_PRIVATE int sqlite3OsFullPathname(
  13429. sqlite3_vfs *pVfs,
  13430. const char *zPath,
  13431. int nPathOut,
  13432. char *zPathOut
  13433. ){
  13434. zPathOut[0] = 0;
  13435. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  13436. }
  13437. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  13438. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  13439. return pVfs->xDlOpen(pVfs, zPath);
  13440. }
  13441. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  13442. pVfs->xDlError(pVfs, nByte, zBufOut);
  13443. }
  13444. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  13445. return pVfs->xDlSym(pVfs, pHdle, zSym);
  13446. }
  13447. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  13448. pVfs->xDlClose(pVfs, pHandle);
  13449. }
  13450. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  13451. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  13452. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  13453. }
  13454. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  13455. return pVfs->xSleep(pVfs, nMicro);
  13456. }
  13457. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  13458. int rc;
  13459. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  13460. ** method to get the current date and time if that method is available
  13461. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  13462. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  13463. ** unavailable.
  13464. */
  13465. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  13466. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  13467. }else{
  13468. double r;
  13469. rc = pVfs->xCurrentTime(pVfs, &r);
  13470. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  13471. }
  13472. return rc;
  13473. }
  13474. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  13475. sqlite3_vfs *pVfs,
  13476. const char *zFile,
  13477. sqlite3_file **ppFile,
  13478. int flags,
  13479. int *pOutFlags
  13480. ){
  13481. int rc = SQLITE_NOMEM;
  13482. sqlite3_file *pFile;
  13483. pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
  13484. if( pFile ){
  13485. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  13486. if( rc!=SQLITE_OK ){
  13487. sqlite3_free(pFile);
  13488. }else{
  13489. *ppFile = pFile;
  13490. }
  13491. }
  13492. return rc;
  13493. }
  13494. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  13495. int rc = SQLITE_OK;
  13496. assert( pFile );
  13497. rc = sqlite3OsClose(pFile);
  13498. sqlite3_free(pFile);
  13499. return rc;
  13500. }
  13501. /*
  13502. ** This function is a wrapper around the OS specific implementation of
  13503. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  13504. ** ability to simulate a malloc failure, so that the handling of an
  13505. ** error in sqlite3_os_init() by the upper layers can be tested.
  13506. */
  13507. SQLITE_PRIVATE int sqlite3OsInit(void){
  13508. void *p = sqlite3_malloc(10);
  13509. if( p==0 ) return SQLITE_NOMEM;
  13510. sqlite3_free(p);
  13511. return sqlite3_os_init();
  13512. }
  13513. /*
  13514. ** The list of all registered VFS implementations.
  13515. */
  13516. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  13517. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  13518. /*
  13519. ** Locate a VFS by name. If no name is given, simply return the
  13520. ** first VFS on the list.
  13521. */
  13522. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  13523. sqlite3_vfs *pVfs = 0;
  13524. #if SQLITE_THREADSAFE
  13525. sqlite3_mutex *mutex;
  13526. #endif
  13527. #ifndef SQLITE_OMIT_AUTOINIT
  13528. int rc = sqlite3_initialize();
  13529. if( rc ) return 0;
  13530. #endif
  13531. #if SQLITE_THREADSAFE
  13532. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13533. #endif
  13534. sqlite3_mutex_enter(mutex);
  13535. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  13536. if( zVfs==0 ) break;
  13537. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  13538. }
  13539. sqlite3_mutex_leave(mutex);
  13540. return pVfs;
  13541. }
  13542. /*
  13543. ** Unlink a VFS from the linked list
  13544. */
  13545. static void vfsUnlink(sqlite3_vfs *pVfs){
  13546. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  13547. if( pVfs==0 ){
  13548. /* No-op */
  13549. }else if( vfsList==pVfs ){
  13550. vfsList = pVfs->pNext;
  13551. }else if( vfsList ){
  13552. sqlite3_vfs *p = vfsList;
  13553. while( p->pNext && p->pNext!=pVfs ){
  13554. p = p->pNext;
  13555. }
  13556. if( p->pNext==pVfs ){
  13557. p->pNext = pVfs->pNext;
  13558. }
  13559. }
  13560. }
  13561. /*
  13562. ** Register a VFS with the system. It is harmless to register the same
  13563. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  13564. ** true.
  13565. */
  13566. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  13567. sqlite3_mutex *mutex = 0;
  13568. #ifndef SQLITE_OMIT_AUTOINIT
  13569. int rc = sqlite3_initialize();
  13570. if( rc ) return rc;
  13571. #endif
  13572. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13573. sqlite3_mutex_enter(mutex);
  13574. vfsUnlink(pVfs);
  13575. if( makeDflt || vfsList==0 ){
  13576. pVfs->pNext = vfsList;
  13577. vfsList = pVfs;
  13578. }else{
  13579. pVfs->pNext = vfsList->pNext;
  13580. vfsList->pNext = pVfs;
  13581. }
  13582. assert(vfsList);
  13583. sqlite3_mutex_leave(mutex);
  13584. return SQLITE_OK;
  13585. }
  13586. /*
  13587. ** Unregister a VFS so that it is no longer accessible.
  13588. */
  13589. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  13590. #if SQLITE_THREADSAFE
  13591. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13592. #endif
  13593. sqlite3_mutex_enter(mutex);
  13594. vfsUnlink(pVfs);
  13595. sqlite3_mutex_leave(mutex);
  13596. return SQLITE_OK;
  13597. }
  13598. /************** End of os.c **************************************************/
  13599. /************** Begin file fault.c *******************************************/
  13600. /*
  13601. ** 2008 Jan 22
  13602. **
  13603. ** The author disclaims copyright to this source code. In place of
  13604. ** a legal notice, here is a blessing:
  13605. **
  13606. ** May you do good and not evil.
  13607. ** May you find forgiveness for yourself and forgive others.
  13608. ** May you share freely, never taking more than you give.
  13609. **
  13610. *************************************************************************
  13611. **
  13612. ** This file contains code to support the concept of "benign"
  13613. ** malloc failures (when the xMalloc() or xRealloc() method of the
  13614. ** sqlite3_mem_methods structure fails to allocate a block of memory
  13615. ** and returns 0).
  13616. **
  13617. ** Most malloc failures are non-benign. After they occur, SQLite
  13618. ** abandons the current operation and returns an error code (usually
  13619. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  13620. ** fatal. For example, if a malloc fails while resizing a hash table, this
  13621. ** is completely recoverable simply by not carrying out the resize. The
  13622. ** hash table will continue to function normally. So a malloc failure
  13623. ** during a hash table resize is a benign fault.
  13624. */
  13625. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13626. /*
  13627. ** Global variables.
  13628. */
  13629. typedef struct BenignMallocHooks BenignMallocHooks;
  13630. static SQLITE_WSD struct BenignMallocHooks {
  13631. void (*xBenignBegin)(void);
  13632. void (*xBenignEnd)(void);
  13633. } sqlite3Hooks = { 0, 0 };
  13634. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  13635. ** structure. If writable static data is unsupported on the target,
  13636. ** we have to locate the state vector at run-time. In the more common
  13637. ** case where writable static data is supported, wsdHooks can refer directly
  13638. ** to the "sqlite3Hooks" state vector declared above.
  13639. */
  13640. #ifdef SQLITE_OMIT_WSD
  13641. # define wsdHooksInit \
  13642. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  13643. # define wsdHooks x[0]
  13644. #else
  13645. # define wsdHooksInit
  13646. # define wsdHooks sqlite3Hooks
  13647. #endif
  13648. /*
  13649. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  13650. ** sqlite3EndBenignMalloc() are called, respectively.
  13651. */
  13652. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  13653. void (*xBenignBegin)(void),
  13654. void (*xBenignEnd)(void)
  13655. ){
  13656. wsdHooksInit;
  13657. wsdHooks.xBenignBegin = xBenignBegin;
  13658. wsdHooks.xBenignEnd = xBenignEnd;
  13659. }
  13660. /*
  13661. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  13662. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  13663. ** indicates that subsequent malloc failures are non-benign.
  13664. */
  13665. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  13666. wsdHooksInit;
  13667. if( wsdHooks.xBenignBegin ){
  13668. wsdHooks.xBenignBegin();
  13669. }
  13670. }
  13671. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  13672. wsdHooksInit;
  13673. if( wsdHooks.xBenignEnd ){
  13674. wsdHooks.xBenignEnd();
  13675. }
  13676. }
  13677. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  13678. /************** End of fault.c ***********************************************/
  13679. /************** Begin file mem0.c ********************************************/
  13680. /*
  13681. ** 2008 October 28
  13682. **
  13683. ** The author disclaims copyright to this source code. In place of
  13684. ** a legal notice, here is a blessing:
  13685. **
  13686. ** May you do good and not evil.
  13687. ** May you find forgiveness for yourself and forgive others.
  13688. ** May you share freely, never taking more than you give.
  13689. **
  13690. *************************************************************************
  13691. **
  13692. ** This file contains a no-op memory allocation drivers for use when
  13693. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  13694. ** here always fail. SQLite will not operate with these drivers. These
  13695. ** are merely placeholders. Real drivers must be substituted using
  13696. ** sqlite3_config() before SQLite will operate.
  13697. */
  13698. /*
  13699. ** This version of the memory allocator is the default. It is
  13700. ** used when no other memory allocator is specified using compile-time
  13701. ** macros.
  13702. */
  13703. #ifdef SQLITE_ZERO_MALLOC
  13704. /*
  13705. ** No-op versions of all memory allocation routines
  13706. */
  13707. static void *sqlite3MemMalloc(int nByte){ return 0; }
  13708. static void sqlite3MemFree(void *pPrior){ return; }
  13709. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  13710. static int sqlite3MemSize(void *pPrior){ return 0; }
  13711. static int sqlite3MemRoundup(int n){ return n; }
  13712. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  13713. static void sqlite3MemShutdown(void *NotUsed){ return; }
  13714. /*
  13715. ** This routine is the only routine in this file with external linkage.
  13716. **
  13717. ** Populate the low-level memory allocation function pointers in
  13718. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  13719. */
  13720. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  13721. static const sqlite3_mem_methods defaultMethods = {
  13722. sqlite3MemMalloc,
  13723. sqlite3MemFree,
  13724. sqlite3MemRealloc,
  13725. sqlite3MemSize,
  13726. sqlite3MemRoundup,
  13727. sqlite3MemInit,
  13728. sqlite3MemShutdown,
  13729. 0
  13730. };
  13731. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  13732. }
  13733. #endif /* SQLITE_ZERO_MALLOC */
  13734. /************** End of mem0.c ************************************************/
  13735. /************** Begin file mem1.c ********************************************/
  13736. /*
  13737. ** 2007 August 14
  13738. **
  13739. ** The author disclaims copyright to this source code. In place of
  13740. ** a legal notice, here is a blessing:
  13741. **
  13742. ** May you do good and not evil.
  13743. ** May you find forgiveness for yourself and forgive others.
  13744. ** May you share freely, never taking more than you give.
  13745. **
  13746. *************************************************************************
  13747. **
  13748. ** This file contains low-level memory allocation drivers for when
  13749. ** SQLite will use the standard C-library malloc/realloc/free interface
  13750. ** to obtain the memory it needs.
  13751. **
  13752. ** This file contains implementations of the low-level memory allocation
  13753. ** routines specified in the sqlite3_mem_methods object.
  13754. */
  13755. /*
  13756. ** This version of the memory allocator is the default. It is
  13757. ** used when no other memory allocator is specified using compile-time
  13758. ** macros.
  13759. */
  13760. #ifdef SQLITE_SYSTEM_MALLOC
  13761. /*
  13762. ** Like malloc(), but remember the size of the allocation
  13763. ** so that we can find it later using sqlite3MemSize().
  13764. **
  13765. ** For this low-level routine, we are guaranteed that nByte>0 because
  13766. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  13767. ** routines.
  13768. */
  13769. static void *sqlite3MemMalloc(int nByte){
  13770. sqlite3_int64 *p;
  13771. assert( nByte>0 );
  13772. nByte = ROUND8(nByte);
  13773. p = malloc( nByte+8 );
  13774. if( p ){
  13775. p[0] = nByte;
  13776. p++;
  13777. }else{
  13778. testcase( sqlite3GlobalConfig.xLog!=0 );
  13779. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  13780. }
  13781. return (void *)p;
  13782. }
  13783. /*
  13784. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  13785. ** or sqlite3MemRealloc().
  13786. **
  13787. ** For this low-level routine, we already know that pPrior!=0 since
  13788. ** cases where pPrior==0 will have been intecepted and dealt with
  13789. ** by higher-level routines.
  13790. */
  13791. static void sqlite3MemFree(void *pPrior){
  13792. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  13793. assert( pPrior!=0 );
  13794. p--;
  13795. free(p);
  13796. }
  13797. /*
  13798. ** Report the allocated size of a prior return from xMalloc()
  13799. ** or xRealloc().
  13800. */
  13801. static int sqlite3MemSize(void *pPrior){
  13802. sqlite3_int64 *p;
  13803. if( pPrior==0 ) return 0;
  13804. p = (sqlite3_int64*)pPrior;
  13805. p--;
  13806. return (int)p[0];
  13807. }
  13808. /*
  13809. ** Like realloc(). Resize an allocation previously obtained from
  13810. ** sqlite3MemMalloc().
  13811. **
  13812. ** For this low-level interface, we know that pPrior!=0. Cases where
  13813. ** pPrior==0 while have been intercepted by higher-level routine and
  13814. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  13815. ** cases where nByte<=0 will have been intercepted by higher-level
  13816. ** routines and redirected to xFree.
  13817. */
  13818. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  13819. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  13820. assert( pPrior!=0 && nByte>0 );
  13821. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  13822. p--;
  13823. p = realloc(p, nByte+8 );
  13824. if( p ){
  13825. p[0] = nByte;
  13826. p++;
  13827. }else{
  13828. testcase( sqlite3GlobalConfig.xLog!=0 );
  13829. sqlite3_log(SQLITE_NOMEM,
  13830. "failed memory resize %u to %u bytes",
  13831. sqlite3MemSize(pPrior), nByte);
  13832. }
  13833. return (void*)p;
  13834. }
  13835. /*
  13836. ** Round up a request size to the next valid allocation size.
  13837. */
  13838. static int sqlite3MemRoundup(int n){
  13839. return ROUND8(n);
  13840. }
  13841. /*
  13842. ** Initialize this module.
  13843. */
  13844. static int sqlite3MemInit(void *NotUsed){
  13845. UNUSED_PARAMETER(NotUsed);
  13846. return SQLITE_OK;
  13847. }
  13848. /*
  13849. ** Deinitialize this module.
  13850. */
  13851. static void sqlite3MemShutdown(void *NotUsed){
  13852. UNUSED_PARAMETER(NotUsed);
  13853. return;
  13854. }
  13855. /*
  13856. ** This routine is the only routine in this file with external linkage.
  13857. **
  13858. ** Populate the low-level memory allocation function pointers in
  13859. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  13860. */
  13861. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  13862. static const sqlite3_mem_methods defaultMethods = {
  13863. sqlite3MemMalloc,
  13864. sqlite3MemFree,
  13865. sqlite3MemRealloc,
  13866. sqlite3MemSize,
  13867. sqlite3MemRoundup,
  13868. sqlite3MemInit,
  13869. sqlite3MemShutdown,
  13870. 0
  13871. };
  13872. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  13873. }
  13874. #endif /* SQLITE_SYSTEM_MALLOC */
  13875. /************** End of mem1.c ************************************************/
  13876. /************** Begin file mem2.c ********************************************/
  13877. /*
  13878. ** 2007 August 15
  13879. **
  13880. ** The author disclaims copyright to this source code. In place of
  13881. ** a legal notice, here is a blessing:
  13882. **
  13883. ** May you do good and not evil.
  13884. ** May you find forgiveness for yourself and forgive others.
  13885. ** May you share freely, never taking more than you give.
  13886. **
  13887. *************************************************************************
  13888. **
  13889. ** This file contains low-level memory allocation drivers for when
  13890. ** SQLite will use the standard C-library malloc/realloc/free interface
  13891. ** to obtain the memory it needs while adding lots of additional debugging
  13892. ** information to each allocation in order to help detect and fix memory
  13893. ** leaks and memory usage errors.
  13894. **
  13895. ** This file contains implementations of the low-level memory allocation
  13896. ** routines specified in the sqlite3_mem_methods object.
  13897. */
  13898. /*
  13899. ** This version of the memory allocator is used only if the
  13900. ** SQLITE_MEMDEBUG macro is defined
  13901. */
  13902. #ifdef SQLITE_MEMDEBUG
  13903. /*
  13904. ** The backtrace functionality is only available with GLIBC
  13905. */
  13906. #ifdef __GLIBC__
  13907. extern int backtrace(void**,int);
  13908. extern void backtrace_symbols_fd(void*const*,int,int);
  13909. #else
  13910. # define backtrace(A,B) 1
  13911. # define backtrace_symbols_fd(A,B,C)
  13912. #endif
  13913. /*
  13914. ** Each memory allocation looks like this:
  13915. **
  13916. ** ------------------------------------------------------------------------
  13917. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  13918. ** ------------------------------------------------------------------------
  13919. **
  13920. ** The application code sees only a pointer to the allocation. We have
  13921. ** to back up from the allocation pointer to find the MemBlockHdr. The
  13922. ** MemBlockHdr tells us the size of the allocation and the number of
  13923. ** backtrace pointers. There is also a guard word at the end of the
  13924. ** MemBlockHdr.
  13925. */
  13926. struct MemBlockHdr {
  13927. i64 iSize; /* Size of this allocation */
  13928. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  13929. char nBacktrace; /* Number of backtraces on this alloc */
  13930. char nBacktraceSlots; /* Available backtrace slots */
  13931. u8 nTitle; /* Bytes of title; includes '\0' */
  13932. u8 eType; /* Allocation type code */
  13933. int iForeGuard; /* Guard word for sanity */
  13934. };
  13935. /*
  13936. ** Guard words
  13937. */
  13938. #define FOREGUARD 0x80F5E153
  13939. #define REARGUARD 0xE4676B53
  13940. /*
  13941. ** Number of malloc size increments to track.
  13942. */
  13943. #define NCSIZE 1000
  13944. /*
  13945. ** All of the static variables used by this module are collected
  13946. ** into a single structure named "mem". This is to keep the
  13947. ** static variables organized and to reduce namespace pollution
  13948. ** when this module is combined with other in the amalgamation.
  13949. */
  13950. static struct {
  13951. /*
  13952. ** Mutex to control access to the memory allocation subsystem.
  13953. */
  13954. sqlite3_mutex *mutex;
  13955. /*
  13956. ** Head and tail of a linked list of all outstanding allocations
  13957. */
  13958. struct MemBlockHdr *pFirst;
  13959. struct MemBlockHdr *pLast;
  13960. /*
  13961. ** The number of levels of backtrace to save in new allocations.
  13962. */
  13963. int nBacktrace;
  13964. void (*xBacktrace)(int, int, void **);
  13965. /*
  13966. ** Title text to insert in front of each block
  13967. */
  13968. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  13969. char zTitle[100]; /* The title text */
  13970. /*
  13971. ** sqlite3MallocDisallow() increments the following counter.
  13972. ** sqlite3MallocAllow() decrements it.
  13973. */
  13974. int disallow; /* Do not allow memory allocation */
  13975. /*
  13976. ** Gather statistics on the sizes of memory allocations.
  13977. ** nAlloc[i] is the number of allocation attempts of i*8
  13978. ** bytes. i==NCSIZE is the number of allocation attempts for
  13979. ** sizes more than NCSIZE*8 bytes.
  13980. */
  13981. int nAlloc[NCSIZE]; /* Total number of allocations */
  13982. int nCurrent[NCSIZE]; /* Current number of allocations */
  13983. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  13984. } mem;
  13985. /*
  13986. ** Adjust memory usage statistics
  13987. */
  13988. static void adjustStats(int iSize, int increment){
  13989. int i = ROUND8(iSize)/8;
  13990. if( i>NCSIZE-1 ){
  13991. i = NCSIZE - 1;
  13992. }
  13993. if( increment>0 ){
  13994. mem.nAlloc[i]++;
  13995. mem.nCurrent[i]++;
  13996. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  13997. mem.mxCurrent[i] = mem.nCurrent[i];
  13998. }
  13999. }else{
  14000. mem.nCurrent[i]--;
  14001. assert( mem.nCurrent[i]>=0 );
  14002. }
  14003. }
  14004. /*
  14005. ** Given an allocation, find the MemBlockHdr for that allocation.
  14006. **
  14007. ** This routine checks the guards at either end of the allocation and
  14008. ** if they are incorrect it asserts.
  14009. */
  14010. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  14011. struct MemBlockHdr *p;
  14012. int *pInt;
  14013. u8 *pU8;
  14014. int nReserve;
  14015. p = (struct MemBlockHdr*)pAllocation;
  14016. p--;
  14017. assert( p->iForeGuard==(int)FOREGUARD );
  14018. nReserve = ROUND8(p->iSize);
  14019. pInt = (int*)pAllocation;
  14020. pU8 = (u8*)pAllocation;
  14021. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  14022. /* This checks any of the "extra" bytes allocated due
  14023. ** to rounding up to an 8 byte boundary to ensure
  14024. ** they haven't been overwritten.
  14025. */
  14026. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  14027. return p;
  14028. }
  14029. /*
  14030. ** Return the number of bytes currently allocated at address p.
  14031. */
  14032. static int sqlite3MemSize(void *p){
  14033. struct MemBlockHdr *pHdr;
  14034. if( !p ){
  14035. return 0;
  14036. }
  14037. pHdr = sqlite3MemsysGetHeader(p);
  14038. return pHdr->iSize;
  14039. }
  14040. /*
  14041. ** Initialize the memory allocation subsystem.
  14042. */
  14043. static int sqlite3MemInit(void *NotUsed){
  14044. UNUSED_PARAMETER(NotUsed);
  14045. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  14046. if( !sqlite3GlobalConfig.bMemstat ){
  14047. /* If memory status is enabled, then the malloc.c wrapper will already
  14048. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  14049. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  14050. }
  14051. return SQLITE_OK;
  14052. }
  14053. /*
  14054. ** Deinitialize the memory allocation subsystem.
  14055. */
  14056. static void sqlite3MemShutdown(void *NotUsed){
  14057. UNUSED_PARAMETER(NotUsed);
  14058. mem.mutex = 0;
  14059. }
  14060. /*
  14061. ** Round up a request size to the next valid allocation size.
  14062. */
  14063. static int sqlite3MemRoundup(int n){
  14064. return ROUND8(n);
  14065. }
  14066. /*
  14067. ** Fill a buffer with pseudo-random bytes. This is used to preset
  14068. ** the content of a new memory allocation to unpredictable values and
  14069. ** to clear the content of a freed allocation to unpredictable values.
  14070. */
  14071. static void randomFill(char *pBuf, int nByte){
  14072. unsigned int x, y, r;
  14073. x = SQLITE_PTR_TO_INT(pBuf);
  14074. y = nByte | 1;
  14075. while( nByte >= 4 ){
  14076. x = (x>>1) ^ (-(x&1) & 0xd0000001);
  14077. y = y*1103515245 + 12345;
  14078. r = x ^ y;
  14079. *(int*)pBuf = r;
  14080. pBuf += 4;
  14081. nByte -= 4;
  14082. }
  14083. while( nByte-- > 0 ){
  14084. x = (x>>1) ^ (-(x&1) & 0xd0000001);
  14085. y = y*1103515245 + 12345;
  14086. r = x ^ y;
  14087. *(pBuf++) = r & 0xff;
  14088. }
  14089. }
  14090. /*
  14091. ** Allocate nByte bytes of memory.
  14092. */
  14093. static void *sqlite3MemMalloc(int nByte){
  14094. struct MemBlockHdr *pHdr;
  14095. void **pBt;
  14096. char *z;
  14097. int *pInt;
  14098. void *p = 0;
  14099. int totalSize;
  14100. int nReserve;
  14101. sqlite3_mutex_enter(mem.mutex);
  14102. assert( mem.disallow==0 );
  14103. nReserve = ROUND8(nByte);
  14104. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  14105. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  14106. p = malloc(totalSize);
  14107. if( p ){
  14108. z = p;
  14109. pBt = (void**)&z[mem.nTitle];
  14110. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  14111. pHdr->pNext = 0;
  14112. pHdr->pPrev = mem.pLast;
  14113. if( mem.pLast ){
  14114. mem.pLast->pNext = pHdr;
  14115. }else{
  14116. mem.pFirst = pHdr;
  14117. }
  14118. mem.pLast = pHdr;
  14119. pHdr->iForeGuard = FOREGUARD;
  14120. pHdr->eType = MEMTYPE_HEAP;
  14121. pHdr->nBacktraceSlots = mem.nBacktrace;
  14122. pHdr->nTitle = mem.nTitle;
  14123. if( mem.nBacktrace ){
  14124. void *aAddr[40];
  14125. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  14126. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  14127. assert(pBt[0]);
  14128. if( mem.xBacktrace ){
  14129. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  14130. }
  14131. }else{
  14132. pHdr->nBacktrace = 0;
  14133. }
  14134. if( mem.nTitle ){
  14135. memcpy(z, mem.zTitle, mem.nTitle);
  14136. }
  14137. pHdr->iSize = nByte;
  14138. adjustStats(nByte, +1);
  14139. pInt = (int*)&pHdr[1];
  14140. pInt[nReserve/sizeof(int)] = REARGUARD;
  14141. randomFill((char*)pInt, nByte);
  14142. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  14143. p = (void*)pInt;
  14144. }
  14145. sqlite3_mutex_leave(mem.mutex);
  14146. return p;
  14147. }
  14148. /*
  14149. ** Free memory.
  14150. */
  14151. static void sqlite3MemFree(void *pPrior){
  14152. struct MemBlockHdr *pHdr;
  14153. void **pBt;
  14154. char *z;
  14155. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  14156. || mem.mutex!=0 );
  14157. pHdr = sqlite3MemsysGetHeader(pPrior);
  14158. pBt = (void**)pHdr;
  14159. pBt -= pHdr->nBacktraceSlots;
  14160. sqlite3_mutex_enter(mem.mutex);
  14161. if( pHdr->pPrev ){
  14162. assert( pHdr->pPrev->pNext==pHdr );
  14163. pHdr->pPrev->pNext = pHdr->pNext;
  14164. }else{
  14165. assert( mem.pFirst==pHdr );
  14166. mem.pFirst = pHdr->pNext;
  14167. }
  14168. if( pHdr->pNext ){
  14169. assert( pHdr->pNext->pPrev==pHdr );
  14170. pHdr->pNext->pPrev = pHdr->pPrev;
  14171. }else{
  14172. assert( mem.pLast==pHdr );
  14173. mem.pLast = pHdr->pPrev;
  14174. }
  14175. z = (char*)pBt;
  14176. z -= pHdr->nTitle;
  14177. adjustStats(pHdr->iSize, -1);
  14178. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  14179. pHdr->iSize + sizeof(int) + pHdr->nTitle);
  14180. free(z);
  14181. sqlite3_mutex_leave(mem.mutex);
  14182. }
  14183. /*
  14184. ** Change the size of an existing memory allocation.
  14185. **
  14186. ** For this debugging implementation, we *always* make a copy of the
  14187. ** allocation into a new place in memory. In this way, if the
  14188. ** higher level code is using pointer to the old allocation, it is
  14189. ** much more likely to break and we are much more liking to find
  14190. ** the error.
  14191. */
  14192. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  14193. struct MemBlockHdr *pOldHdr;
  14194. void *pNew;
  14195. assert( mem.disallow==0 );
  14196. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  14197. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  14198. pNew = sqlite3MemMalloc(nByte);
  14199. if( pNew ){
  14200. memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
  14201. if( nByte>pOldHdr->iSize ){
  14202. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
  14203. }
  14204. sqlite3MemFree(pPrior);
  14205. }
  14206. return pNew;
  14207. }
  14208. /*
  14209. ** Populate the low-level memory allocation function pointers in
  14210. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14211. */
  14212. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14213. static const sqlite3_mem_methods defaultMethods = {
  14214. sqlite3MemMalloc,
  14215. sqlite3MemFree,
  14216. sqlite3MemRealloc,
  14217. sqlite3MemSize,
  14218. sqlite3MemRoundup,
  14219. sqlite3MemInit,
  14220. sqlite3MemShutdown,
  14221. 0
  14222. };
  14223. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14224. }
  14225. /*
  14226. ** Set the "type" of an allocation.
  14227. */
  14228. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  14229. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  14230. struct MemBlockHdr *pHdr;
  14231. pHdr = sqlite3MemsysGetHeader(p);
  14232. assert( pHdr->iForeGuard==FOREGUARD );
  14233. pHdr->eType = eType;
  14234. }
  14235. }
  14236. /*
  14237. ** Return TRUE if the mask of type in eType matches the type of the
  14238. ** allocation p. Also return true if p==NULL.
  14239. **
  14240. ** This routine is designed for use within an assert() statement, to
  14241. ** verify the type of an allocation. For example:
  14242. **
  14243. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  14244. */
  14245. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  14246. int rc = 1;
  14247. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  14248. struct MemBlockHdr *pHdr;
  14249. pHdr = sqlite3MemsysGetHeader(p);
  14250. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  14251. if( (pHdr->eType&eType)==0 ){
  14252. rc = 0;
  14253. }
  14254. }
  14255. return rc;
  14256. }
  14257. /*
  14258. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  14259. ** allocation p. Also return true if p==NULL.
  14260. **
  14261. ** This routine is designed for use within an assert() statement, to
  14262. ** verify the type of an allocation. For example:
  14263. **
  14264. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  14265. */
  14266. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  14267. int rc = 1;
  14268. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  14269. struct MemBlockHdr *pHdr;
  14270. pHdr = sqlite3MemsysGetHeader(p);
  14271. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  14272. if( (pHdr->eType&eType)!=0 ){
  14273. rc = 0;
  14274. }
  14275. }
  14276. return rc;
  14277. }
  14278. /*
  14279. ** Set the number of backtrace levels kept for each allocation.
  14280. ** A value of zero turns off backtracing. The number is always rounded
  14281. ** up to a multiple of 2.
  14282. */
  14283. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  14284. if( depth<0 ){ depth = 0; }
  14285. if( depth>20 ){ depth = 20; }
  14286. depth = (depth+1)&0xfe;
  14287. mem.nBacktrace = depth;
  14288. }
  14289. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  14290. mem.xBacktrace = xBacktrace;
  14291. }
  14292. /*
  14293. ** Set the title string for subsequent allocations.
  14294. */
  14295. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  14296. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  14297. sqlite3_mutex_enter(mem.mutex);
  14298. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  14299. memcpy(mem.zTitle, zTitle, n);
  14300. mem.zTitle[n] = 0;
  14301. mem.nTitle = ROUND8(n);
  14302. sqlite3_mutex_leave(mem.mutex);
  14303. }
  14304. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  14305. struct MemBlockHdr *pHdr;
  14306. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  14307. void **pBt = (void**)pHdr;
  14308. pBt -= pHdr->nBacktraceSlots;
  14309. mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  14310. }
  14311. }
  14312. /*
  14313. ** Open the file indicated and write a log of all unfreed memory
  14314. ** allocations into that log.
  14315. */
  14316. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  14317. FILE *out;
  14318. struct MemBlockHdr *pHdr;
  14319. void **pBt;
  14320. int i;
  14321. out = fopen(zFilename, "w");
  14322. if( out==0 ){
  14323. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  14324. zFilename);
  14325. return;
  14326. }
  14327. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  14328. char *z = (char*)pHdr;
  14329. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  14330. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  14331. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  14332. if( pHdr->nBacktrace ){
  14333. fflush(out);
  14334. pBt = (void**)pHdr;
  14335. pBt -= pHdr->nBacktraceSlots;
  14336. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  14337. fprintf(out, "\n");
  14338. }
  14339. }
  14340. fprintf(out, "COUNTS:\n");
  14341. for(i=0; i<NCSIZE-1; i++){
  14342. if( mem.nAlloc[i] ){
  14343. fprintf(out, " %5d: %10d %10d %10d\n",
  14344. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  14345. }
  14346. }
  14347. if( mem.nAlloc[NCSIZE-1] ){
  14348. fprintf(out, " %5d: %10d %10d %10d\n",
  14349. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  14350. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  14351. }
  14352. fclose(out);
  14353. }
  14354. /*
  14355. ** Return the number of times sqlite3MemMalloc() has been called.
  14356. */
  14357. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  14358. int i;
  14359. int nTotal = 0;
  14360. for(i=0; i<NCSIZE; i++){
  14361. nTotal += mem.nAlloc[i];
  14362. }
  14363. return nTotal;
  14364. }
  14365. #endif /* SQLITE_MEMDEBUG */
  14366. /************** End of mem2.c ************************************************/
  14367. /************** Begin file mem3.c ********************************************/
  14368. /*
  14369. ** 2007 October 14
  14370. **
  14371. ** The author disclaims copyright to this source code. In place of
  14372. ** a legal notice, here is a blessing:
  14373. **
  14374. ** May you do good and not evil.
  14375. ** May you find forgiveness for yourself and forgive others.
  14376. ** May you share freely, never taking more than you give.
  14377. **
  14378. *************************************************************************
  14379. ** This file contains the C functions that implement a memory
  14380. ** allocation subsystem for use by SQLite.
  14381. **
  14382. ** This version of the memory allocation subsystem omits all
  14383. ** use of malloc(). The SQLite user supplies a block of memory
  14384. ** before calling sqlite3_initialize() from which allocations
  14385. ** are made and returned by the xMalloc() and xRealloc()
  14386. ** implementations. Once sqlite3_initialize() has been called,
  14387. ** the amount of memory available to SQLite is fixed and cannot
  14388. ** be changed.
  14389. **
  14390. ** This version of the memory allocation subsystem is included
  14391. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  14392. */
  14393. /*
  14394. ** This version of the memory allocator is only built into the library
  14395. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  14396. ** mean that the library will use a memory-pool by default, just that
  14397. ** it is available. The mempool allocator is activated by calling
  14398. ** sqlite3_config().
  14399. */
  14400. #ifdef SQLITE_ENABLE_MEMSYS3
  14401. /*
  14402. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  14403. */
  14404. #define MX_SMALL 10
  14405. /*
  14406. ** Number of freelist hash slots
  14407. */
  14408. #define N_HASH 61
  14409. /*
  14410. ** A memory allocation (also called a "chunk") consists of two or
  14411. ** more blocks where each block is 8 bytes. The first 8 bytes are
  14412. ** a header that is not returned to the user.
  14413. **
  14414. ** A chunk is two or more blocks that is either checked out or
  14415. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  14416. ** size of the allocation in blocks if the allocation is free.
  14417. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  14418. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  14419. ** is true if the previous chunk is checked out and false if the
  14420. ** previous chunk is free. The u.hdr.prevSize field is the size of
  14421. ** the previous chunk in blocks if the previous chunk is on the
  14422. ** freelist. If the previous chunk is checked out, then
  14423. ** u.hdr.prevSize can be part of the data for that chunk and should
  14424. ** not be read or written.
  14425. **
  14426. ** We often identify a chunk by its index in mem3.aPool[]. When
  14427. ** this is done, the chunk index refers to the second block of
  14428. ** the chunk. In this way, the first chunk has an index of 1.
  14429. ** A chunk index of 0 means "no such chunk" and is the equivalent
  14430. ** of a NULL pointer.
  14431. **
  14432. ** The second block of free chunks is of the form u.list. The
  14433. ** two fields form a double-linked list of chunks of related sizes.
  14434. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  14435. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  14436. **
  14437. ** The second block of a chunk is user data if the chunk is checked
  14438. ** out. If a chunk is checked out, the user data may extend into
  14439. ** the u.hdr.prevSize value of the following chunk.
  14440. */
  14441. typedef struct Mem3Block Mem3Block;
  14442. struct Mem3Block {
  14443. union {
  14444. struct {
  14445. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  14446. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  14447. } hdr;
  14448. struct {
  14449. u32 next; /* Index in mem3.aPool[] of next free chunk */
  14450. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  14451. } list;
  14452. } u;
  14453. };
  14454. /*
  14455. ** All of the static variables used by this module are collected
  14456. ** into a single structure named "mem3". This is to keep the
  14457. ** static variables organized and to reduce namespace pollution
  14458. ** when this module is combined with other in the amalgamation.
  14459. */
  14460. static SQLITE_WSD struct Mem3Global {
  14461. /*
  14462. ** Memory available for allocation. nPool is the size of the array
  14463. ** (in Mem3Blocks) pointed to by aPool less 2.
  14464. */
  14465. u32 nPool;
  14466. Mem3Block *aPool;
  14467. /*
  14468. ** True if we are evaluating an out-of-memory callback.
  14469. */
  14470. int alarmBusy;
  14471. /*
  14472. ** Mutex to control access to the memory allocation subsystem.
  14473. */
  14474. sqlite3_mutex *mutex;
  14475. /*
  14476. ** The minimum amount of free space that we have seen.
  14477. */
  14478. u32 mnMaster;
  14479. /*
  14480. ** iMaster is the index of the master chunk. Most new allocations
  14481. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  14482. ** of the current master. iMaster is 0 if there is not master chunk.
  14483. ** The master chunk is not in either the aiHash[] or aiSmall[].
  14484. */
  14485. u32 iMaster;
  14486. u32 szMaster;
  14487. /*
  14488. ** Array of lists of free blocks according to the block size
  14489. ** for smaller chunks, or a hash on the block size for larger
  14490. ** chunks.
  14491. */
  14492. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  14493. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  14494. } mem3 = { 97535575 };
  14495. #define mem3 GLOBAL(struct Mem3Global, mem3)
  14496. /*
  14497. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  14498. ** on. *pRoot is the list that i is a member of.
  14499. */
  14500. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  14501. u32 next = mem3.aPool[i].u.list.next;
  14502. u32 prev = mem3.aPool[i].u.list.prev;
  14503. assert( sqlite3_mutex_held(mem3.mutex) );
  14504. if( prev==0 ){
  14505. *pRoot = next;
  14506. }else{
  14507. mem3.aPool[prev].u.list.next = next;
  14508. }
  14509. if( next ){
  14510. mem3.aPool[next].u.list.prev = prev;
  14511. }
  14512. mem3.aPool[i].u.list.next = 0;
  14513. mem3.aPool[i].u.list.prev = 0;
  14514. }
  14515. /*
  14516. ** Unlink the chunk at index i from
  14517. ** whatever list is currently a member of.
  14518. */
  14519. static void memsys3Unlink(u32 i){
  14520. u32 size, hash;
  14521. assert( sqlite3_mutex_held(mem3.mutex) );
  14522. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  14523. assert( i>=1 );
  14524. size = mem3.aPool[i-1].u.hdr.size4x/4;
  14525. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  14526. assert( size>=2 );
  14527. if( size <= MX_SMALL ){
  14528. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  14529. }else{
  14530. hash = size % N_HASH;
  14531. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  14532. }
  14533. }
  14534. /*
  14535. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  14536. ** at *pRoot.
  14537. */
  14538. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  14539. assert( sqlite3_mutex_held(mem3.mutex) );
  14540. mem3.aPool[i].u.list.next = *pRoot;
  14541. mem3.aPool[i].u.list.prev = 0;
  14542. if( *pRoot ){
  14543. mem3.aPool[*pRoot].u.list.prev = i;
  14544. }
  14545. *pRoot = i;
  14546. }
  14547. /*
  14548. ** Link the chunk at index i into either the appropriate
  14549. ** small chunk list, or into the large chunk hash table.
  14550. */
  14551. static void memsys3Link(u32 i){
  14552. u32 size, hash;
  14553. assert( sqlite3_mutex_held(mem3.mutex) );
  14554. assert( i>=1 );
  14555. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  14556. size = mem3.aPool[i-1].u.hdr.size4x/4;
  14557. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  14558. assert( size>=2 );
  14559. if( size <= MX_SMALL ){
  14560. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  14561. }else{
  14562. hash = size % N_HASH;
  14563. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  14564. }
  14565. }
  14566. /*
  14567. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  14568. ** will already be held (obtained by code in malloc.c) if
  14569. ** sqlite3GlobalConfig.bMemStat is true.
  14570. */
  14571. static void memsys3Enter(void){
  14572. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  14573. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  14574. }
  14575. sqlite3_mutex_enter(mem3.mutex);
  14576. }
  14577. static void memsys3Leave(void){
  14578. sqlite3_mutex_leave(mem3.mutex);
  14579. }
  14580. /*
  14581. ** Called when we are unable to satisfy an allocation of nBytes.
  14582. */
  14583. static void memsys3OutOfMemory(int nByte){
  14584. if( !mem3.alarmBusy ){
  14585. mem3.alarmBusy = 1;
  14586. assert( sqlite3_mutex_held(mem3.mutex) );
  14587. sqlite3_mutex_leave(mem3.mutex);
  14588. sqlite3_release_memory(nByte);
  14589. sqlite3_mutex_enter(mem3.mutex);
  14590. mem3.alarmBusy = 0;
  14591. }
  14592. }
  14593. /*
  14594. ** Chunk i is a free chunk that has been unlinked. Adjust its
  14595. ** size parameters for check-out and return a pointer to the
  14596. ** user portion of the chunk.
  14597. */
  14598. static void *memsys3Checkout(u32 i, u32 nBlock){
  14599. u32 x;
  14600. assert( sqlite3_mutex_held(mem3.mutex) );
  14601. assert( i>=1 );
  14602. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  14603. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  14604. x = mem3.aPool[i-1].u.hdr.size4x;
  14605. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  14606. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  14607. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  14608. return &mem3.aPool[i];
  14609. }
  14610. /*
  14611. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  14612. ** Return a pointer to the new allocation. Or, if the master chunk
  14613. ** is not large enough, return 0.
  14614. */
  14615. static void *memsys3FromMaster(u32 nBlock){
  14616. assert( sqlite3_mutex_held(mem3.mutex) );
  14617. assert( mem3.szMaster>=nBlock );
  14618. if( nBlock>=mem3.szMaster-1 ){
  14619. /* Use the entire master */
  14620. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  14621. mem3.iMaster = 0;
  14622. mem3.szMaster = 0;
  14623. mem3.mnMaster = 0;
  14624. return p;
  14625. }else{
  14626. /* Split the master block. Return the tail. */
  14627. u32 newi, x;
  14628. newi = mem3.iMaster + mem3.szMaster - nBlock;
  14629. assert( newi > mem3.iMaster+1 );
  14630. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  14631. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  14632. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  14633. mem3.szMaster -= nBlock;
  14634. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  14635. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  14636. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  14637. if( mem3.szMaster < mem3.mnMaster ){
  14638. mem3.mnMaster = mem3.szMaster;
  14639. }
  14640. return (void*)&mem3.aPool[newi];
  14641. }
  14642. }
  14643. /*
  14644. ** *pRoot is the head of a list of free chunks of the same size
  14645. ** or same size hash. In other words, *pRoot is an entry in either
  14646. ** mem3.aiSmall[] or mem3.aiHash[].
  14647. **
  14648. ** This routine examines all entries on the given list and tries
  14649. ** to coalesce each entries with adjacent free chunks.
  14650. **
  14651. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  14652. ** the current mem3.iMaster with the new larger chunk. In order for
  14653. ** this mem3.iMaster replacement to work, the master chunk must be
  14654. ** linked into the hash tables. That is not the normal state of
  14655. ** affairs, of course. The calling routine must link the master
  14656. ** chunk before invoking this routine, then must unlink the (possibly
  14657. ** changed) master chunk once this routine has finished.
  14658. */
  14659. static void memsys3Merge(u32 *pRoot){
  14660. u32 iNext, prev, size, i, x;
  14661. assert( sqlite3_mutex_held(mem3.mutex) );
  14662. for(i=*pRoot; i>0; i=iNext){
  14663. iNext = mem3.aPool[i].u.list.next;
  14664. size = mem3.aPool[i-1].u.hdr.size4x;
  14665. assert( (size&1)==0 );
  14666. if( (size&2)==0 ){
  14667. memsys3UnlinkFromList(i, pRoot);
  14668. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  14669. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  14670. if( prev==iNext ){
  14671. iNext = mem3.aPool[prev].u.list.next;
  14672. }
  14673. memsys3Unlink(prev);
  14674. size = i + size/4 - prev;
  14675. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  14676. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  14677. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  14678. memsys3Link(prev);
  14679. i = prev;
  14680. }else{
  14681. size /= 4;
  14682. }
  14683. if( size>mem3.szMaster ){
  14684. mem3.iMaster = i;
  14685. mem3.szMaster = size;
  14686. }
  14687. }
  14688. }
  14689. /*
  14690. ** Return a block of memory of at least nBytes in size.
  14691. ** Return NULL if unable.
  14692. **
  14693. ** This function assumes that the necessary mutexes, if any, are
  14694. ** already held by the caller. Hence "Unsafe".
  14695. */
  14696. static void *memsys3MallocUnsafe(int nByte){
  14697. u32 i;
  14698. u32 nBlock;
  14699. u32 toFree;
  14700. assert( sqlite3_mutex_held(mem3.mutex) );
  14701. assert( sizeof(Mem3Block)==8 );
  14702. if( nByte<=12 ){
  14703. nBlock = 2;
  14704. }else{
  14705. nBlock = (nByte + 11)/8;
  14706. }
  14707. assert( nBlock>=2 );
  14708. /* STEP 1:
  14709. ** Look for an entry of the correct size in either the small
  14710. ** chunk table or in the large chunk hash table. This is
  14711. ** successful most of the time (about 9 times out of 10).
  14712. */
  14713. if( nBlock <= MX_SMALL ){
  14714. i = mem3.aiSmall[nBlock-2];
  14715. if( i>0 ){
  14716. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  14717. return memsys3Checkout(i, nBlock);
  14718. }
  14719. }else{
  14720. int hash = nBlock % N_HASH;
  14721. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  14722. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  14723. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  14724. return memsys3Checkout(i, nBlock);
  14725. }
  14726. }
  14727. }
  14728. /* STEP 2:
  14729. ** Try to satisfy the allocation by carving a piece off of the end
  14730. ** of the master chunk. This step usually works if step 1 fails.
  14731. */
  14732. if( mem3.szMaster>=nBlock ){
  14733. return memsys3FromMaster(nBlock);
  14734. }
  14735. /* STEP 3:
  14736. ** Loop through the entire memory pool. Coalesce adjacent free
  14737. ** chunks. Recompute the master chunk as the largest free chunk.
  14738. ** Then try again to satisfy the allocation by carving a piece off
  14739. ** of the end of the master chunk. This step happens very
  14740. ** rarely (we hope!)
  14741. */
  14742. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  14743. memsys3OutOfMemory(toFree);
  14744. if( mem3.iMaster ){
  14745. memsys3Link(mem3.iMaster);
  14746. mem3.iMaster = 0;
  14747. mem3.szMaster = 0;
  14748. }
  14749. for(i=0; i<N_HASH; i++){
  14750. memsys3Merge(&mem3.aiHash[i]);
  14751. }
  14752. for(i=0; i<MX_SMALL-1; i++){
  14753. memsys3Merge(&mem3.aiSmall[i]);
  14754. }
  14755. if( mem3.szMaster ){
  14756. memsys3Unlink(mem3.iMaster);
  14757. if( mem3.szMaster>=nBlock ){
  14758. return memsys3FromMaster(nBlock);
  14759. }
  14760. }
  14761. }
  14762. /* If none of the above worked, then we fail. */
  14763. return 0;
  14764. }
  14765. /*
  14766. ** Free an outstanding memory allocation.
  14767. **
  14768. ** This function assumes that the necessary mutexes, if any, are
  14769. ** already held by the caller. Hence "Unsafe".
  14770. */
  14771. void memsys3FreeUnsafe(void *pOld){
  14772. Mem3Block *p = (Mem3Block*)pOld;
  14773. int i;
  14774. u32 size, x;
  14775. assert( sqlite3_mutex_held(mem3.mutex) );
  14776. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  14777. i = p - mem3.aPool;
  14778. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  14779. size = mem3.aPool[i-1].u.hdr.size4x/4;
  14780. assert( i+size<=mem3.nPool+1 );
  14781. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  14782. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  14783. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  14784. memsys3Link(i);
  14785. /* Try to expand the master using the newly freed chunk */
  14786. if( mem3.iMaster ){
  14787. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  14788. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  14789. mem3.iMaster -= size;
  14790. mem3.szMaster += size;
  14791. memsys3Unlink(mem3.iMaster);
  14792. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  14793. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  14794. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  14795. }
  14796. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  14797. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  14798. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  14799. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  14800. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  14801. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  14802. }
  14803. }
  14804. }
  14805. /*
  14806. ** Return the size of an outstanding allocation, in bytes. The
  14807. ** size returned omits the 8-byte header overhead. This only
  14808. ** works for chunks that are currently checked out.
  14809. */
  14810. static int memsys3Size(void *p){
  14811. Mem3Block *pBlock;
  14812. if( p==0 ) return 0;
  14813. pBlock = (Mem3Block*)p;
  14814. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  14815. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  14816. }
  14817. /*
  14818. ** Round up a request size to the next valid allocation size.
  14819. */
  14820. static int memsys3Roundup(int n){
  14821. if( n<=12 ){
  14822. return 12;
  14823. }else{
  14824. return ((n+11)&~7) - 4;
  14825. }
  14826. }
  14827. /*
  14828. ** Allocate nBytes of memory.
  14829. */
  14830. static void *memsys3Malloc(int nBytes){
  14831. sqlite3_int64 *p;
  14832. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  14833. memsys3Enter();
  14834. p = memsys3MallocUnsafe(nBytes);
  14835. memsys3Leave();
  14836. return (void*)p;
  14837. }
  14838. /*
  14839. ** Free memory.
  14840. */
  14841. void memsys3Free(void *pPrior){
  14842. assert( pPrior );
  14843. memsys3Enter();
  14844. memsys3FreeUnsafe(pPrior);
  14845. memsys3Leave();
  14846. }
  14847. /*
  14848. ** Change the size of an existing memory allocation
  14849. */
  14850. void *memsys3Realloc(void *pPrior, int nBytes){
  14851. int nOld;
  14852. void *p;
  14853. if( pPrior==0 ){
  14854. return sqlite3_malloc(nBytes);
  14855. }
  14856. if( nBytes<=0 ){
  14857. sqlite3_free(pPrior);
  14858. return 0;
  14859. }
  14860. nOld = memsys3Size(pPrior);
  14861. if( nBytes<=nOld && nBytes>=nOld-128 ){
  14862. return pPrior;
  14863. }
  14864. memsys3Enter();
  14865. p = memsys3MallocUnsafe(nBytes);
  14866. if( p ){
  14867. if( nOld<nBytes ){
  14868. memcpy(p, pPrior, nOld);
  14869. }else{
  14870. memcpy(p, pPrior, nBytes);
  14871. }
  14872. memsys3FreeUnsafe(pPrior);
  14873. }
  14874. memsys3Leave();
  14875. return p;
  14876. }
  14877. /*
  14878. ** Initialize this module.
  14879. */
  14880. static int memsys3Init(void *NotUsed){
  14881. UNUSED_PARAMETER(NotUsed);
  14882. if( !sqlite3GlobalConfig.pHeap ){
  14883. return SQLITE_ERROR;
  14884. }
  14885. /* Store a pointer to the memory block in global structure mem3. */
  14886. assert( sizeof(Mem3Block)==8 );
  14887. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  14888. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  14889. /* Initialize the master block. */
  14890. mem3.szMaster = mem3.nPool;
  14891. mem3.mnMaster = mem3.szMaster;
  14892. mem3.iMaster = 1;
  14893. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  14894. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  14895. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  14896. return SQLITE_OK;
  14897. }
  14898. /*
  14899. ** Deinitialize this module.
  14900. */
  14901. static void memsys3Shutdown(void *NotUsed){
  14902. UNUSED_PARAMETER(NotUsed);
  14903. mem3.mutex = 0;
  14904. return;
  14905. }
  14906. /*
  14907. ** Open the file indicated and write a log of all unfreed memory
  14908. ** allocations into that log.
  14909. */
  14910. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  14911. #ifdef SQLITE_DEBUG
  14912. FILE *out;
  14913. u32 i, j;
  14914. u32 size;
  14915. if( zFilename==0 || zFilename[0]==0 ){
  14916. out = stdout;
  14917. }else{
  14918. out = fopen(zFilename, "w");
  14919. if( out==0 ){
  14920. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  14921. zFilename);
  14922. return;
  14923. }
  14924. }
  14925. memsys3Enter();
  14926. fprintf(out, "CHUNKS:\n");
  14927. for(i=1; i<=mem3.nPool; i+=size/4){
  14928. size = mem3.aPool[i-1].u.hdr.size4x;
  14929. if( size/4<=1 ){
  14930. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  14931. assert( 0 );
  14932. break;
  14933. }
  14934. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  14935. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  14936. assert( 0 );
  14937. break;
  14938. }
  14939. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  14940. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  14941. assert( 0 );
  14942. break;
  14943. }
  14944. if( size&1 ){
  14945. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  14946. }else{
  14947. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  14948. i==mem3.iMaster ? " **master**" : "");
  14949. }
  14950. }
  14951. for(i=0; i<MX_SMALL-1; i++){
  14952. if( mem3.aiSmall[i]==0 ) continue;
  14953. fprintf(out, "small(%2d):", i);
  14954. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  14955. fprintf(out, " %p(%d)", &mem3.aPool[j],
  14956. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  14957. }
  14958. fprintf(out, "\n");
  14959. }
  14960. for(i=0; i<N_HASH; i++){
  14961. if( mem3.aiHash[i]==0 ) continue;
  14962. fprintf(out, "hash(%2d):", i);
  14963. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  14964. fprintf(out, " %p(%d)", &mem3.aPool[j],
  14965. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  14966. }
  14967. fprintf(out, "\n");
  14968. }
  14969. fprintf(out, "master=%d\n", mem3.iMaster);
  14970. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  14971. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  14972. sqlite3_mutex_leave(mem3.mutex);
  14973. if( out==stdout ){
  14974. fflush(stdout);
  14975. }else{
  14976. fclose(out);
  14977. }
  14978. #else
  14979. UNUSED_PARAMETER(zFilename);
  14980. #endif
  14981. }
  14982. /*
  14983. ** This routine is the only routine in this file with external
  14984. ** linkage.
  14985. **
  14986. ** Populate the low-level memory allocation function pointers in
  14987. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  14988. ** arguments specify the block of memory to manage.
  14989. **
  14990. ** This routine is only called by sqlite3_config(), and therefore
  14991. ** is not required to be threadsafe (it is not).
  14992. */
  14993. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  14994. static const sqlite3_mem_methods mempoolMethods = {
  14995. memsys3Malloc,
  14996. memsys3Free,
  14997. memsys3Realloc,
  14998. memsys3Size,
  14999. memsys3Roundup,
  15000. memsys3Init,
  15001. memsys3Shutdown,
  15002. 0
  15003. };
  15004. return &mempoolMethods;
  15005. }
  15006. #endif /* SQLITE_ENABLE_MEMSYS3 */
  15007. /************** End of mem3.c ************************************************/
  15008. /************** Begin file mem5.c ********************************************/
  15009. /*
  15010. ** 2007 October 14
  15011. **
  15012. ** The author disclaims copyright to this source code. In place of
  15013. ** a legal notice, here is a blessing:
  15014. **
  15015. ** May you do good and not evil.
  15016. ** May you find forgiveness for yourself and forgive others.
  15017. ** May you share freely, never taking more than you give.
  15018. **
  15019. *************************************************************************
  15020. ** This file contains the C functions that implement a memory
  15021. ** allocation subsystem for use by SQLite.
  15022. **
  15023. ** This version of the memory allocation subsystem omits all
  15024. ** use of malloc(). The application gives SQLite a block of memory
  15025. ** before calling sqlite3_initialize() from which allocations
  15026. ** are made and returned by the xMalloc() and xRealloc()
  15027. ** implementations. Once sqlite3_initialize() has been called,
  15028. ** the amount of memory available to SQLite is fixed and cannot
  15029. ** be changed.
  15030. **
  15031. ** This version of the memory allocation subsystem is included
  15032. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  15033. **
  15034. ** This memory allocator uses the following algorithm:
  15035. **
  15036. ** 1. All memory allocations sizes are rounded up to a power of 2.
  15037. **
  15038. ** 2. If two adjacent free blocks are the halves of a larger block,
  15039. ** then the two blocks are coalesed into the single larger block.
  15040. **
  15041. ** 3. New memory is allocated from the first available free block.
  15042. **
  15043. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  15044. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  15045. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  15046. **
  15047. ** Let n be the size of the largest allocation divided by the minimum
  15048. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  15049. ** be the maximum amount of memory ever outstanding at one time. Let
  15050. ** N be the total amount of memory available for allocation. Robson
  15051. ** proved that this memory allocator will never breakdown due to
  15052. ** fragmentation as long as the following constraint holds:
  15053. **
  15054. ** N >= M*(1 + log2(n)/2) - n + 1
  15055. **
  15056. ** The sqlite3_status() logic tracks the maximum values of n and M so
  15057. ** that an application can, at any time, verify this constraint.
  15058. */
  15059. /*
  15060. ** This version of the memory allocator is used only when
  15061. ** SQLITE_ENABLE_MEMSYS5 is defined.
  15062. */
  15063. #ifdef SQLITE_ENABLE_MEMSYS5
  15064. /*
  15065. ** A minimum allocation is an instance of the following structure.
  15066. ** Larger allocations are an array of these structures where the
  15067. ** size of the array is a power of 2.
  15068. **
  15069. ** The size of this object must be a power of two. That fact is
  15070. ** verified in memsys5Init().
  15071. */
  15072. typedef struct Mem5Link Mem5Link;
  15073. struct Mem5Link {
  15074. int next; /* Index of next free chunk */
  15075. int prev; /* Index of previous free chunk */
  15076. };
  15077. /*
  15078. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  15079. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  15080. ** it is not actually possible to reach this limit.
  15081. */
  15082. #define LOGMAX 30
  15083. /*
  15084. ** Masks used for mem5.aCtrl[] elements.
  15085. */
  15086. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  15087. #define CTRL_FREE 0x20 /* True if not checked out */
  15088. /*
  15089. ** All of the static variables used by this module are collected
  15090. ** into a single structure named "mem5". This is to keep the
  15091. ** static variables organized and to reduce namespace pollution
  15092. ** when this module is combined with other in the amalgamation.
  15093. */
  15094. static SQLITE_WSD struct Mem5Global {
  15095. /*
  15096. ** Memory available for allocation
  15097. */
  15098. int szAtom; /* Smallest possible allocation in bytes */
  15099. int nBlock; /* Number of szAtom sized blocks in zPool */
  15100. u8 *zPool; /* Memory available to be allocated */
  15101. /*
  15102. ** Mutex to control access to the memory allocation subsystem.
  15103. */
  15104. sqlite3_mutex *mutex;
  15105. /*
  15106. ** Performance statistics
  15107. */
  15108. u64 nAlloc; /* Total number of calls to malloc */
  15109. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  15110. u64 totalExcess; /* Total internal fragmentation */
  15111. u32 currentOut; /* Current checkout, including internal fragmentation */
  15112. u32 currentCount; /* Current number of distinct checkouts */
  15113. u32 maxOut; /* Maximum instantaneous currentOut */
  15114. u32 maxCount; /* Maximum instantaneous currentCount */
  15115. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  15116. /*
  15117. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  15118. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  15119. ** and so forth.
  15120. */
  15121. int aiFreelist[LOGMAX+1];
  15122. /*
  15123. ** Space for tracking which blocks are checked out and the size
  15124. ** of each block. One byte per block.
  15125. */
  15126. u8 *aCtrl;
  15127. } mem5;
  15128. /*
  15129. ** Access the static variable through a macro for SQLITE_OMIT_WSD
  15130. */
  15131. #define mem5 GLOBAL(struct Mem5Global, mem5)
  15132. /*
  15133. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  15134. ** structures, return a pointer to the idx-th such lik.
  15135. */
  15136. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  15137. /*
  15138. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  15139. ** on. It should be found on mem5.aiFreelist[iLogsize].
  15140. */
  15141. static void memsys5Unlink(int i, int iLogsize){
  15142. int next, prev;
  15143. assert( i>=0 && i<mem5.nBlock );
  15144. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  15145. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  15146. next = MEM5LINK(i)->next;
  15147. prev = MEM5LINK(i)->prev;
  15148. if( prev<0 ){
  15149. mem5.aiFreelist[iLogsize] = next;
  15150. }else{
  15151. MEM5LINK(prev)->next = next;
  15152. }
  15153. if( next>=0 ){
  15154. MEM5LINK(next)->prev = prev;
  15155. }
  15156. }
  15157. /*
  15158. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  15159. ** free list.
  15160. */
  15161. static void memsys5Link(int i, int iLogsize){
  15162. int x;
  15163. assert( sqlite3_mutex_held(mem5.mutex) );
  15164. assert( i>=0 && i<mem5.nBlock );
  15165. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  15166. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  15167. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  15168. MEM5LINK(i)->prev = -1;
  15169. if( x>=0 ){
  15170. assert( x<mem5.nBlock );
  15171. MEM5LINK(x)->prev = i;
  15172. }
  15173. mem5.aiFreelist[iLogsize] = i;
  15174. }
  15175. /*
  15176. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15177. ** will already be held (obtained by code in malloc.c) if
  15178. ** sqlite3GlobalConfig.bMemStat is true.
  15179. */
  15180. static void memsys5Enter(void){
  15181. sqlite3_mutex_enter(mem5.mutex);
  15182. }
  15183. static void memsys5Leave(void){
  15184. sqlite3_mutex_leave(mem5.mutex);
  15185. }
  15186. /*
  15187. ** Return the size of an outstanding allocation, in bytes. The
  15188. ** size returned omits the 8-byte header overhead. This only
  15189. ** works for chunks that are currently checked out.
  15190. */
  15191. static int memsys5Size(void *p){
  15192. int iSize = 0;
  15193. if( p ){
  15194. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  15195. assert( i>=0 && i<mem5.nBlock );
  15196. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  15197. }
  15198. return iSize;
  15199. }
  15200. /*
  15201. ** Find the first entry on the freelist iLogsize. Unlink that
  15202. ** entry and return its index.
  15203. */
  15204. static int memsys5UnlinkFirst(int iLogsize){
  15205. int i;
  15206. int iFirst;
  15207. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  15208. i = iFirst = mem5.aiFreelist[iLogsize];
  15209. assert( iFirst>=0 );
  15210. while( i>0 ){
  15211. if( i<iFirst ) iFirst = i;
  15212. i = MEM5LINK(i)->next;
  15213. }
  15214. memsys5Unlink(iFirst, iLogsize);
  15215. return iFirst;
  15216. }
  15217. /*
  15218. ** Return a block of memory of at least nBytes in size.
  15219. ** Return NULL if unable. Return NULL if nBytes==0.
  15220. **
  15221. ** The caller guarantees that nByte positive.
  15222. **
  15223. ** The caller has obtained a mutex prior to invoking this
  15224. ** routine so there is never any chance that two or more
  15225. ** threads can be in this routine at the same time.
  15226. */
  15227. static void *memsys5MallocUnsafe(int nByte){
  15228. int i; /* Index of a mem5.aPool[] slot */
  15229. int iBin; /* Index into mem5.aiFreelist[] */
  15230. int iFullSz; /* Size of allocation rounded up to power of 2 */
  15231. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  15232. /* nByte must be a positive */
  15233. assert( nByte>0 );
  15234. /* Keep track of the maximum allocation request. Even unfulfilled
  15235. ** requests are counted */
  15236. if( (u32)nByte>mem5.maxRequest ){
  15237. mem5.maxRequest = nByte;
  15238. }
  15239. /* Abort if the requested allocation size is larger than the largest
  15240. ** power of two that we can represent using 32-bit signed integers.
  15241. */
  15242. if( nByte > 0x40000000 ){
  15243. return 0;
  15244. }
  15245. /* Round nByte up to the next valid power of two */
  15246. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  15247. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  15248. ** block. If not, then split a block of the next larger power of
  15249. ** two in order to create a new free block of size iLogsize.
  15250. */
  15251. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  15252. if( iBin>LOGMAX ){
  15253. testcase( sqlite3GlobalConfig.xLog!=0 );
  15254. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  15255. return 0;
  15256. }
  15257. i = memsys5UnlinkFirst(iBin);
  15258. while( iBin>iLogsize ){
  15259. int newSize;
  15260. iBin--;
  15261. newSize = 1 << iBin;
  15262. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  15263. memsys5Link(i+newSize, iBin);
  15264. }
  15265. mem5.aCtrl[i] = iLogsize;
  15266. /* Update allocator performance statistics. */
  15267. mem5.nAlloc++;
  15268. mem5.totalAlloc += iFullSz;
  15269. mem5.totalExcess += iFullSz - nByte;
  15270. mem5.currentCount++;
  15271. mem5.currentOut += iFullSz;
  15272. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  15273. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  15274. /* Return a pointer to the allocated memory. */
  15275. return (void*)&mem5.zPool[i*mem5.szAtom];
  15276. }
  15277. /*
  15278. ** Free an outstanding memory allocation.
  15279. */
  15280. static void memsys5FreeUnsafe(void *pOld){
  15281. u32 size, iLogsize;
  15282. int iBlock;
  15283. /* Set iBlock to the index of the block pointed to by pOld in
  15284. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  15285. */
  15286. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  15287. /* Check that the pointer pOld points to a valid, non-free block. */
  15288. assert( iBlock>=0 && iBlock<mem5.nBlock );
  15289. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  15290. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  15291. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  15292. size = 1<<iLogsize;
  15293. assert( iBlock+size-1<(u32)mem5.nBlock );
  15294. mem5.aCtrl[iBlock] |= CTRL_FREE;
  15295. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  15296. assert( mem5.currentCount>0 );
  15297. assert( mem5.currentOut>=(size*mem5.szAtom) );
  15298. mem5.currentCount--;
  15299. mem5.currentOut -= size*mem5.szAtom;
  15300. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  15301. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  15302. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  15303. while( ALWAYS(iLogsize<LOGMAX) ){
  15304. int iBuddy;
  15305. if( (iBlock>>iLogsize) & 1 ){
  15306. iBuddy = iBlock - size;
  15307. }else{
  15308. iBuddy = iBlock + size;
  15309. }
  15310. assert( iBuddy>=0 );
  15311. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  15312. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  15313. memsys5Unlink(iBuddy, iLogsize);
  15314. iLogsize++;
  15315. if( iBuddy<iBlock ){
  15316. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  15317. mem5.aCtrl[iBlock] = 0;
  15318. iBlock = iBuddy;
  15319. }else{
  15320. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  15321. mem5.aCtrl[iBuddy] = 0;
  15322. }
  15323. size *= 2;
  15324. }
  15325. memsys5Link(iBlock, iLogsize);
  15326. }
  15327. /*
  15328. ** Allocate nBytes of memory
  15329. */
  15330. static void *memsys5Malloc(int nBytes){
  15331. sqlite3_int64 *p = 0;
  15332. if( nBytes>0 ){
  15333. memsys5Enter();
  15334. p = memsys5MallocUnsafe(nBytes);
  15335. memsys5Leave();
  15336. }
  15337. return (void*)p;
  15338. }
  15339. /*
  15340. ** Free memory.
  15341. **
  15342. ** The outer layer memory allocator prevents this routine from
  15343. ** being called with pPrior==0.
  15344. */
  15345. static void memsys5Free(void *pPrior){
  15346. assert( pPrior!=0 );
  15347. memsys5Enter();
  15348. memsys5FreeUnsafe(pPrior);
  15349. memsys5Leave();
  15350. }
  15351. /*
  15352. ** Change the size of an existing memory allocation.
  15353. **
  15354. ** The outer layer memory allocator prevents this routine from
  15355. ** being called with pPrior==0.
  15356. **
  15357. ** nBytes is always a value obtained from a prior call to
  15358. ** memsys5Round(). Hence nBytes is always a non-negative power
  15359. ** of two. If nBytes==0 that means that an oversize allocation
  15360. ** (an allocation larger than 0x40000000) was requested and this
  15361. ** routine should return 0 without freeing pPrior.
  15362. */
  15363. static void *memsys5Realloc(void *pPrior, int nBytes){
  15364. int nOld;
  15365. void *p;
  15366. assert( pPrior!=0 );
  15367. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  15368. assert( nBytes>=0 );
  15369. if( nBytes==0 ){
  15370. return 0;
  15371. }
  15372. nOld = memsys5Size(pPrior);
  15373. if( nBytes<=nOld ){
  15374. return pPrior;
  15375. }
  15376. memsys5Enter();
  15377. p = memsys5MallocUnsafe(nBytes);
  15378. if( p ){
  15379. memcpy(p, pPrior, nOld);
  15380. memsys5FreeUnsafe(pPrior);
  15381. }
  15382. memsys5Leave();
  15383. return p;
  15384. }
  15385. /*
  15386. ** Round up a request size to the next valid allocation size. If
  15387. ** the allocation is too large to be handled by this allocation system,
  15388. ** return 0.
  15389. **
  15390. ** All allocations must be a power of two and must be expressed by a
  15391. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  15392. ** or 1073741824 bytes.
  15393. */
  15394. static int memsys5Roundup(int n){
  15395. int iFullSz;
  15396. if( n > 0x40000000 ) return 0;
  15397. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  15398. return iFullSz;
  15399. }
  15400. /*
  15401. ** Return the ceiling of the logarithm base 2 of iValue.
  15402. **
  15403. ** Examples: memsys5Log(1) -> 0
  15404. ** memsys5Log(2) -> 1
  15405. ** memsys5Log(4) -> 2
  15406. ** memsys5Log(5) -> 3
  15407. ** memsys5Log(8) -> 3
  15408. ** memsys5Log(9) -> 4
  15409. */
  15410. static int memsys5Log(int iValue){
  15411. int iLog;
  15412. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  15413. return iLog;
  15414. }
  15415. /*
  15416. ** Initialize the memory allocator.
  15417. **
  15418. ** This routine is not threadsafe. The caller must be holding a mutex
  15419. ** to prevent multiple threads from entering at the same time.
  15420. */
  15421. static int memsys5Init(void *NotUsed){
  15422. int ii; /* Loop counter */
  15423. int nByte; /* Number of bytes of memory available to this allocator */
  15424. u8 *zByte; /* Memory usable by this allocator */
  15425. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  15426. int iOffset; /* An offset into mem5.aCtrl[] */
  15427. UNUSED_PARAMETER(NotUsed);
  15428. /* For the purposes of this routine, disable the mutex */
  15429. mem5.mutex = 0;
  15430. /* The size of a Mem5Link object must be a power of two. Verify that
  15431. ** this is case.
  15432. */
  15433. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  15434. nByte = sqlite3GlobalConfig.nHeap;
  15435. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  15436. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  15437. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  15438. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  15439. mem5.szAtom = (1<<nMinLog);
  15440. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  15441. mem5.szAtom = mem5.szAtom << 1;
  15442. }
  15443. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  15444. mem5.zPool = zByte;
  15445. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  15446. for(ii=0; ii<=LOGMAX; ii++){
  15447. mem5.aiFreelist[ii] = -1;
  15448. }
  15449. iOffset = 0;
  15450. for(ii=LOGMAX; ii>=0; ii--){
  15451. int nAlloc = (1<<ii);
  15452. if( (iOffset+nAlloc)<=mem5.nBlock ){
  15453. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  15454. memsys5Link(iOffset, ii);
  15455. iOffset += nAlloc;
  15456. }
  15457. assert((iOffset+nAlloc)>mem5.nBlock);
  15458. }
  15459. /* If a mutex is required for normal operation, allocate one */
  15460. if( sqlite3GlobalConfig.bMemstat==0 ){
  15461. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15462. }
  15463. return SQLITE_OK;
  15464. }
  15465. /*
  15466. ** Deinitialize this module.
  15467. */
  15468. static void memsys5Shutdown(void *NotUsed){
  15469. UNUSED_PARAMETER(NotUsed);
  15470. mem5.mutex = 0;
  15471. return;
  15472. }
  15473. #ifdef SQLITE_TEST
  15474. /*
  15475. ** Open the file indicated and write a log of all unfreed memory
  15476. ** allocations into that log.
  15477. */
  15478. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  15479. FILE *out;
  15480. int i, j, n;
  15481. int nMinLog;
  15482. if( zFilename==0 || zFilename[0]==0 ){
  15483. out = stdout;
  15484. }else{
  15485. out = fopen(zFilename, "w");
  15486. if( out==0 ){
  15487. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15488. zFilename);
  15489. return;
  15490. }
  15491. }
  15492. memsys5Enter();
  15493. nMinLog = memsys5Log(mem5.szAtom);
  15494. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  15495. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  15496. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  15497. }
  15498. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  15499. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  15500. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  15501. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  15502. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  15503. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  15504. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  15505. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  15506. memsys5Leave();
  15507. if( out==stdout ){
  15508. fflush(stdout);
  15509. }else{
  15510. fclose(out);
  15511. }
  15512. }
  15513. #endif
  15514. /*
  15515. ** This routine is the only routine in this file with external
  15516. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  15517. ** struct populated with the memsys5 methods.
  15518. */
  15519. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  15520. static const sqlite3_mem_methods memsys5Methods = {
  15521. memsys5Malloc,
  15522. memsys5Free,
  15523. memsys5Realloc,
  15524. memsys5Size,
  15525. memsys5Roundup,
  15526. memsys5Init,
  15527. memsys5Shutdown,
  15528. 0
  15529. };
  15530. return &memsys5Methods;
  15531. }
  15532. #endif /* SQLITE_ENABLE_MEMSYS5 */
  15533. /************** End of mem5.c ************************************************/
  15534. /************** Begin file mutex.c *******************************************/
  15535. /*
  15536. ** 2007 August 14
  15537. **
  15538. ** The author disclaims copyright to this source code. In place of
  15539. ** a legal notice, here is a blessing:
  15540. **
  15541. ** May you do good and not evil.
  15542. ** May you find forgiveness for yourself and forgive others.
  15543. ** May you share freely, never taking more than you give.
  15544. **
  15545. *************************************************************************
  15546. ** This file contains the C functions that implement mutexes.
  15547. **
  15548. ** This file contains code that is common across all mutex implementations.
  15549. */
  15550. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  15551. /*
  15552. ** For debugging purposes, record when the mutex subsystem is initialized
  15553. ** and uninitialized so that we can assert() if there is an attempt to
  15554. ** allocate a mutex while the system is uninitialized.
  15555. */
  15556. static SQLITE_WSD int mutexIsInit = 0;
  15557. #endif /* SQLITE_DEBUG */
  15558. #ifndef SQLITE_MUTEX_OMIT
  15559. /*
  15560. ** Initialize the mutex system.
  15561. */
  15562. SQLITE_PRIVATE int sqlite3MutexInit(void){
  15563. int rc = SQLITE_OK;
  15564. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  15565. /* If the xMutexAlloc method has not been set, then the user did not
  15566. ** install a mutex implementation via sqlite3_config() prior to
  15567. ** sqlite3_initialize() being called. This block copies pointers to
  15568. ** the default implementation into the sqlite3GlobalConfig structure.
  15569. */
  15570. sqlite3_mutex_methods const *pFrom;
  15571. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  15572. if( sqlite3GlobalConfig.bCoreMutex ){
  15573. pFrom = sqlite3DefaultMutex();
  15574. }else{
  15575. pFrom = sqlite3NoopMutex();
  15576. }
  15577. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  15578. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  15579. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  15580. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  15581. }
  15582. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  15583. #ifdef SQLITE_DEBUG
  15584. GLOBAL(int, mutexIsInit) = 1;
  15585. #endif
  15586. return rc;
  15587. }
  15588. /*
  15589. ** Shutdown the mutex system. This call frees resources allocated by
  15590. ** sqlite3MutexInit().
  15591. */
  15592. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  15593. int rc = SQLITE_OK;
  15594. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  15595. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  15596. }
  15597. #ifdef SQLITE_DEBUG
  15598. GLOBAL(int, mutexIsInit) = 0;
  15599. #endif
  15600. return rc;
  15601. }
  15602. /*
  15603. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  15604. */
  15605. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  15606. #ifndef SQLITE_OMIT_AUTOINIT
  15607. if( sqlite3_initialize() ) return 0;
  15608. #endif
  15609. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  15610. }
  15611. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  15612. if( !sqlite3GlobalConfig.bCoreMutex ){
  15613. return 0;
  15614. }
  15615. assert( GLOBAL(int, mutexIsInit) );
  15616. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  15617. }
  15618. /*
  15619. ** Free a dynamic mutex.
  15620. */
  15621. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  15622. if( p ){
  15623. sqlite3GlobalConfig.mutex.xMutexFree(p);
  15624. }
  15625. }
  15626. /*
  15627. ** Obtain the mutex p. If some other thread already has the mutex, block
  15628. ** until it can be obtained.
  15629. */
  15630. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  15631. if( p ){
  15632. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  15633. }
  15634. }
  15635. /*
  15636. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  15637. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  15638. */
  15639. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  15640. int rc = SQLITE_OK;
  15641. if( p ){
  15642. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  15643. }
  15644. return rc;
  15645. }
  15646. /*
  15647. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  15648. ** entered by the same thread. The behavior is undefined if the mutex
  15649. ** is not currently entered. If a NULL pointer is passed as an argument
  15650. ** this function is a no-op.
  15651. */
  15652. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  15653. if( p ){
  15654. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  15655. }
  15656. }
  15657. #ifndef NDEBUG
  15658. /*
  15659. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  15660. ** intended for use inside assert() statements.
  15661. */
  15662. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  15663. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  15664. }
  15665. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  15666. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  15667. }
  15668. #endif
  15669. #endif /* SQLITE_MUTEX_OMIT */
  15670. /************** End of mutex.c ***********************************************/
  15671. /************** Begin file mutex_noop.c **************************************/
  15672. /*
  15673. ** 2008 October 07
  15674. **
  15675. ** The author disclaims copyright to this source code. In place of
  15676. ** a legal notice, here is a blessing:
  15677. **
  15678. ** May you do good and not evil.
  15679. ** May you find forgiveness for yourself and forgive others.
  15680. ** May you share freely, never taking more than you give.
  15681. **
  15682. *************************************************************************
  15683. ** This file contains the C functions that implement mutexes.
  15684. **
  15685. ** This implementation in this file does not provide any mutual
  15686. ** exclusion and is thus suitable for use only in applications
  15687. ** that use SQLite in a single thread. The routines defined
  15688. ** here are place-holders. Applications can substitute working
  15689. ** mutex routines at start-time using the
  15690. **
  15691. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  15692. **
  15693. ** interface.
  15694. **
  15695. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  15696. ** that does error checking on mutexes to make sure they are being
  15697. ** called correctly.
  15698. */
  15699. #ifndef SQLITE_MUTEX_OMIT
  15700. #ifndef SQLITE_DEBUG
  15701. /*
  15702. ** Stub routines for all mutex methods.
  15703. **
  15704. ** This routines provide no mutual exclusion or error checking.
  15705. */
  15706. static int noopMutexInit(void){ return SQLITE_OK; }
  15707. static int noopMutexEnd(void){ return SQLITE_OK; }
  15708. static sqlite3_mutex *noopMutexAlloc(int id){
  15709. UNUSED_PARAMETER(id);
  15710. return (sqlite3_mutex*)8;
  15711. }
  15712. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  15713. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  15714. static int noopMutexTry(sqlite3_mutex *p){
  15715. UNUSED_PARAMETER(p);
  15716. return SQLITE_OK;
  15717. }
  15718. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  15719. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  15720. static const sqlite3_mutex_methods sMutex = {
  15721. noopMutexInit,
  15722. noopMutexEnd,
  15723. noopMutexAlloc,
  15724. noopMutexFree,
  15725. noopMutexEnter,
  15726. noopMutexTry,
  15727. noopMutexLeave,
  15728. 0,
  15729. 0,
  15730. };
  15731. return &sMutex;
  15732. }
  15733. #endif /* !SQLITE_DEBUG */
  15734. #ifdef SQLITE_DEBUG
  15735. /*
  15736. ** In this implementation, error checking is provided for testing
  15737. ** and debugging purposes. The mutexes still do not provide any
  15738. ** mutual exclusion.
  15739. */
  15740. /*
  15741. ** The mutex object
  15742. */
  15743. typedef struct sqlite3_debug_mutex {
  15744. int id; /* The mutex type */
  15745. int cnt; /* Number of entries without a matching leave */
  15746. } sqlite3_debug_mutex;
  15747. /*
  15748. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  15749. ** intended for use inside assert() statements.
  15750. */
  15751. static int debugMutexHeld(sqlite3_mutex *pX){
  15752. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  15753. return p==0 || p->cnt>0;
  15754. }
  15755. static int debugMutexNotheld(sqlite3_mutex *pX){
  15756. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  15757. return p==0 || p->cnt==0;
  15758. }
  15759. /*
  15760. ** Initialize and deinitialize the mutex subsystem.
  15761. */
  15762. static int debugMutexInit(void){ return SQLITE_OK; }
  15763. static int debugMutexEnd(void){ return SQLITE_OK; }
  15764. /*
  15765. ** The sqlite3_mutex_alloc() routine allocates a new
  15766. ** mutex and returns a pointer to it. If it returns NULL
  15767. ** that means that a mutex could not be allocated.
  15768. */
  15769. static sqlite3_mutex *debugMutexAlloc(int id){
  15770. static sqlite3_debug_mutex aStatic[6];
  15771. sqlite3_debug_mutex *pNew = 0;
  15772. switch( id ){
  15773. case SQLITE_MUTEX_FAST:
  15774. case SQLITE_MUTEX_RECURSIVE: {
  15775. pNew = sqlite3Malloc(sizeof(*pNew));
  15776. if( pNew ){
  15777. pNew->id = id;
  15778. pNew->cnt = 0;
  15779. }
  15780. break;
  15781. }
  15782. default: {
  15783. assert( id-2 >= 0 );
  15784. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  15785. pNew = &aStatic[id-2];
  15786. pNew->id = id;
  15787. break;
  15788. }
  15789. }
  15790. return (sqlite3_mutex*)pNew;
  15791. }
  15792. /*
  15793. ** This routine deallocates a previously allocated mutex.
  15794. */
  15795. static void debugMutexFree(sqlite3_mutex *pX){
  15796. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  15797. assert( p->cnt==0 );
  15798. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  15799. sqlite3_free(p);
  15800. }
  15801. /*
  15802. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  15803. ** to enter a mutex. If another thread is already within the mutex,
  15804. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  15805. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  15806. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  15807. ** be entered multiple times by the same thread. In such cases the,
  15808. ** mutex must be exited an equal number of times before another thread
  15809. ** can enter. If the same thread tries to enter any other kind of mutex
  15810. ** more than once, the behavior is undefined.
  15811. */
  15812. static void debugMutexEnter(sqlite3_mutex *pX){
  15813. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  15814. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  15815. p->cnt++;
  15816. }
  15817. static int debugMutexTry(sqlite3_mutex *pX){
  15818. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  15819. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  15820. p->cnt++;
  15821. return SQLITE_OK;
  15822. }
  15823. /*
  15824. ** The sqlite3_mutex_leave() routine exits a mutex that was
  15825. ** previously entered by the same thread. The behavior
  15826. ** is undefined if the mutex is not currently entered or
  15827. ** is not currently allocated. SQLite will never do either.
  15828. */
  15829. static void debugMutexLeave(sqlite3_mutex *pX){
  15830. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  15831. assert( debugMutexHeld(pX) );
  15832. p->cnt--;
  15833. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  15834. }
  15835. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  15836. static const sqlite3_mutex_methods sMutex = {
  15837. debugMutexInit,
  15838. debugMutexEnd,
  15839. debugMutexAlloc,
  15840. debugMutexFree,
  15841. debugMutexEnter,
  15842. debugMutexTry,
  15843. debugMutexLeave,
  15844. debugMutexHeld,
  15845. debugMutexNotheld
  15846. };
  15847. return &sMutex;
  15848. }
  15849. #endif /* SQLITE_DEBUG */
  15850. /*
  15851. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  15852. ** is used regardless of the run-time threadsafety setting.
  15853. */
  15854. #ifdef SQLITE_MUTEX_NOOP
  15855. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  15856. return sqlite3NoopMutex();
  15857. }
  15858. #endif /* SQLITE_MUTEX_NOOP */
  15859. #endif /* SQLITE_MUTEX_OMIT */
  15860. /************** End of mutex_noop.c ******************************************/
  15861. /************** Begin file mutex_os2.c ***************************************/
  15862. /*
  15863. ** 2007 August 28
  15864. **
  15865. ** The author disclaims copyright to this source code. In place of
  15866. ** a legal notice, here is a blessing:
  15867. **
  15868. ** May you do good and not evil.
  15869. ** May you find forgiveness for yourself and forgive others.
  15870. ** May you share freely, never taking more than you give.
  15871. **
  15872. *************************************************************************
  15873. ** This file contains the C functions that implement mutexes for OS/2
  15874. */
  15875. /*
  15876. ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
  15877. ** See the mutex.h file for details.
  15878. */
  15879. #ifdef SQLITE_MUTEX_OS2
  15880. /********************** OS/2 Mutex Implementation **********************
  15881. **
  15882. ** This implementation of mutexes is built using the OS/2 API.
  15883. */
  15884. /*
  15885. ** The mutex object
  15886. ** Each recursive mutex is an instance of the following structure.
  15887. */
  15888. struct sqlite3_mutex {
  15889. HMTX mutex; /* Mutex controlling the lock */
  15890. int id; /* Mutex type */
  15891. #ifdef SQLITE_DEBUG
  15892. int trace; /* True to trace changes */
  15893. #endif
  15894. };
  15895. #ifdef SQLITE_DEBUG
  15896. #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
  15897. #else
  15898. #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
  15899. #endif
  15900. /*
  15901. ** Initialize and deinitialize the mutex subsystem.
  15902. */
  15903. static int os2MutexInit(void){ return SQLITE_OK; }
  15904. static int os2MutexEnd(void){ return SQLITE_OK; }
  15905. /*
  15906. ** The sqlite3_mutex_alloc() routine allocates a new
  15907. ** mutex and returns a pointer to it. If it returns NULL
  15908. ** that means that a mutex could not be allocated.
  15909. ** SQLite will unwind its stack and return an error. The argument
  15910. ** to sqlite3_mutex_alloc() is one of these integer constants:
  15911. **
  15912. ** <ul>
  15913. ** <li> SQLITE_MUTEX_FAST
  15914. ** <li> SQLITE_MUTEX_RECURSIVE
  15915. ** <li> SQLITE_MUTEX_STATIC_MASTER
  15916. ** <li> SQLITE_MUTEX_STATIC_MEM
  15917. ** <li> SQLITE_MUTEX_STATIC_MEM2
  15918. ** <li> SQLITE_MUTEX_STATIC_PRNG
  15919. ** <li> SQLITE_MUTEX_STATIC_LRU
  15920. ** <li> SQLITE_MUTEX_STATIC_LRU2
  15921. ** </ul>
  15922. **
  15923. ** The first two constants cause sqlite3_mutex_alloc() to create
  15924. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  15925. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  15926. ** The mutex implementation does not need to make a distinction
  15927. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  15928. ** not want to. But SQLite will only request a recursive mutex in
  15929. ** cases where it really needs one. If a faster non-recursive mutex
  15930. ** implementation is available on the host platform, the mutex subsystem
  15931. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  15932. **
  15933. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  15934. ** a pointer to a static preexisting mutex. Six static mutexes are
  15935. ** used by the current version of SQLite. Future versions of SQLite
  15936. ** may add additional static mutexes. Static mutexes are for internal
  15937. ** use by SQLite only. Applications that use SQLite mutexes should
  15938. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  15939. ** SQLITE_MUTEX_RECURSIVE.
  15940. **
  15941. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  15942. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  15943. ** returns a different mutex on every call. But for the static
  15944. ** mutex types, the same mutex is returned on every call that has
  15945. ** the same type number.
  15946. */
  15947. static sqlite3_mutex *os2MutexAlloc(int iType){
  15948. sqlite3_mutex *p = NULL;
  15949. switch( iType ){
  15950. case SQLITE_MUTEX_FAST:
  15951. case SQLITE_MUTEX_RECURSIVE: {
  15952. p = sqlite3MallocZero( sizeof(*p) );
  15953. if( p ){
  15954. p->id = iType;
  15955. if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
  15956. sqlite3_free( p );
  15957. p = NULL;
  15958. }
  15959. }
  15960. break;
  15961. }
  15962. default: {
  15963. static volatile int isInit = 0;
  15964. static sqlite3_mutex staticMutexes[6] = {
  15965. SQLITE3_MUTEX_INITIALIZER,
  15966. SQLITE3_MUTEX_INITIALIZER,
  15967. SQLITE3_MUTEX_INITIALIZER,
  15968. SQLITE3_MUTEX_INITIALIZER,
  15969. SQLITE3_MUTEX_INITIALIZER,
  15970. SQLITE3_MUTEX_INITIALIZER,
  15971. };
  15972. if ( !isInit ){
  15973. APIRET rc;
  15974. PTIB ptib;
  15975. PPIB ppib;
  15976. HMTX mutex;
  15977. char name[32];
  15978. DosGetInfoBlocks( &ptib, &ppib );
  15979. sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
  15980. ppib->pib_ulpid );
  15981. while( !isInit ){
  15982. mutex = 0;
  15983. rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
  15984. if( rc == NO_ERROR ){
  15985. unsigned int i;
  15986. if( !isInit ){
  15987. for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
  15988. DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
  15989. }
  15990. isInit = 1;
  15991. }
  15992. DosCloseMutexSem( mutex );
  15993. }else if( rc == ERROR_DUPLICATE_NAME ){
  15994. DosSleep( 1 );
  15995. }else{
  15996. return p;
  15997. }
  15998. }
  15999. }
  16000. assert( iType-2 >= 0 );
  16001. assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
  16002. p = &staticMutexes[iType-2];
  16003. p->id = iType;
  16004. break;
  16005. }
  16006. }
  16007. return p;
  16008. }
  16009. /*
  16010. ** This routine deallocates a previously allocated mutex.
  16011. ** SQLite is careful to deallocate every mutex that it allocates.
  16012. */
  16013. static void os2MutexFree(sqlite3_mutex *p){
  16014. #ifdef SQLITE_DEBUG
  16015. TID tid;
  16016. PID pid;
  16017. ULONG ulCount;
  16018. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  16019. assert( ulCount==0 );
  16020. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  16021. #endif
  16022. DosCloseMutexSem( p->mutex );
  16023. sqlite3_free( p );
  16024. }
  16025. #ifdef SQLITE_DEBUG
  16026. /*
  16027. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16028. ** intended for use inside assert() statements.
  16029. */
  16030. static int os2MutexHeld(sqlite3_mutex *p){
  16031. TID tid;
  16032. PID pid;
  16033. ULONG ulCount;
  16034. PTIB ptib;
  16035. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  16036. if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
  16037. return 0;
  16038. DosGetInfoBlocks(&ptib, NULL);
  16039. return tid==ptib->tib_ptib2->tib2_ultid;
  16040. }
  16041. static int os2MutexNotheld(sqlite3_mutex *p){
  16042. TID tid;
  16043. PID pid;
  16044. ULONG ulCount;
  16045. PTIB ptib;
  16046. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  16047. if( ulCount==0 )
  16048. return 1;
  16049. DosGetInfoBlocks(&ptib, NULL);
  16050. return tid!=ptib->tib_ptib2->tib2_ultid;
  16051. }
  16052. static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
  16053. TID tid;
  16054. PID pid;
  16055. ULONG ulCount;
  16056. DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
  16057. printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
  16058. }
  16059. #endif
  16060. /*
  16061. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  16062. ** to enter a mutex. If another thread is already within the mutex,
  16063. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  16064. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  16065. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  16066. ** be entered multiple times by the same thread. In such cases the,
  16067. ** mutex must be exited an equal number of times before another thread
  16068. ** can enter. If the same thread tries to enter any other kind of mutex
  16069. ** more than once, the behavior is undefined.
  16070. */
  16071. static void os2MutexEnter(sqlite3_mutex *p){
  16072. assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  16073. DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
  16074. #ifdef SQLITE_DEBUG
  16075. if( p->trace ) os2MutexTrace(p, "enter");
  16076. #endif
  16077. }
  16078. static int os2MutexTry(sqlite3_mutex *p){
  16079. int rc = SQLITE_BUSY;
  16080. assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
  16081. if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
  16082. rc = SQLITE_OK;
  16083. #ifdef SQLITE_DEBUG
  16084. if( p->trace ) os2MutexTrace(p, "try");
  16085. #endif
  16086. }
  16087. return rc;
  16088. }
  16089. /*
  16090. ** The sqlite3_mutex_leave() routine exits a mutex that was
  16091. ** previously entered by the same thread. The behavior
  16092. ** is undefined if the mutex is not currently entered or
  16093. ** is not currently allocated. SQLite will never do either.
  16094. */
  16095. static void os2MutexLeave(sqlite3_mutex *p){
  16096. assert( os2MutexHeld(p) );
  16097. DosReleaseMutexSem(p->mutex);
  16098. #ifdef SQLITE_DEBUG
  16099. if( p->trace ) os2MutexTrace(p, "leave");
  16100. #endif
  16101. }
  16102. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  16103. static const sqlite3_mutex_methods sMutex = {
  16104. os2MutexInit,
  16105. os2MutexEnd,
  16106. os2MutexAlloc,
  16107. os2MutexFree,
  16108. os2MutexEnter,
  16109. os2MutexTry,
  16110. os2MutexLeave,
  16111. #ifdef SQLITE_DEBUG
  16112. os2MutexHeld,
  16113. os2MutexNotheld
  16114. #else
  16115. 0,
  16116. 0
  16117. #endif
  16118. };
  16119. return &sMutex;
  16120. }
  16121. #endif /* SQLITE_MUTEX_OS2 */
  16122. /************** End of mutex_os2.c *******************************************/
  16123. /************** Begin file mutex_unix.c **************************************/
  16124. /*
  16125. ** 2007 August 28
  16126. **
  16127. ** The author disclaims copyright to this source code. In place of
  16128. ** a legal notice, here is a blessing:
  16129. **
  16130. ** May you do good and not evil.
  16131. ** May you find forgiveness for yourself and forgive others.
  16132. ** May you share freely, never taking more than you give.
  16133. **
  16134. *************************************************************************
  16135. ** This file contains the C functions that implement mutexes for pthreads
  16136. */
  16137. /*
  16138. ** The code in this file is only used if we are compiling threadsafe
  16139. ** under unix with pthreads.
  16140. **
  16141. ** Note that this implementation requires a version of pthreads that
  16142. ** supports recursive mutexes.
  16143. */
  16144. #ifdef SQLITE_MUTEX_PTHREADS
  16145. #include <pthread.h>
  16146. /*
  16147. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  16148. ** are necessary under two condidtions: (1) Debug builds and (2) using
  16149. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  16150. */
  16151. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  16152. # define SQLITE_MUTEX_NREF 1
  16153. #else
  16154. # define SQLITE_MUTEX_NREF 0
  16155. #endif
  16156. /*
  16157. ** Each recursive mutex is an instance of the following structure.
  16158. */
  16159. struct sqlite3_mutex {
  16160. pthread_mutex_t mutex; /* Mutex controlling the lock */
  16161. #if SQLITE_MUTEX_NREF
  16162. int id; /* Mutex type */
  16163. volatile int nRef; /* Number of entrances */
  16164. volatile pthread_t owner; /* Thread that is within this mutex */
  16165. int trace; /* True to trace changes */
  16166. #endif
  16167. };
  16168. #if SQLITE_MUTEX_NREF
  16169. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  16170. #else
  16171. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  16172. #endif
  16173. /*
  16174. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16175. ** intended for use only inside assert() statements. On some platforms,
  16176. ** there might be race conditions that can cause these routines to
  16177. ** deliver incorrect results. In particular, if pthread_equal() is
  16178. ** not an atomic operation, then these routines might delivery
  16179. ** incorrect results. On most platforms, pthread_equal() is a
  16180. ** comparison of two integers and is therefore atomic. But we are
  16181. ** told that HPUX is not such a platform. If so, then these routines
  16182. ** will not always work correctly on HPUX.
  16183. **
  16184. ** On those platforms where pthread_equal() is not atomic, SQLite
  16185. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  16186. ** make sure no assert() statements are evaluated and hence these
  16187. ** routines are never called.
  16188. */
  16189. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  16190. static int pthreadMutexHeld(sqlite3_mutex *p){
  16191. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  16192. }
  16193. static int pthreadMutexNotheld(sqlite3_mutex *p){
  16194. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  16195. }
  16196. #endif
  16197. /*
  16198. ** Initialize and deinitialize the mutex subsystem.
  16199. */
  16200. static int pthreadMutexInit(void){ return SQLITE_OK; }
  16201. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  16202. /*
  16203. ** The sqlite3_mutex_alloc() routine allocates a new
  16204. ** mutex and returns a pointer to it. If it returns NULL
  16205. ** that means that a mutex could not be allocated. SQLite
  16206. ** will unwind its stack and return an error. The argument
  16207. ** to sqlite3_mutex_alloc() is one of these integer constants:
  16208. **
  16209. ** <ul>
  16210. ** <li> SQLITE_MUTEX_FAST
  16211. ** <li> SQLITE_MUTEX_RECURSIVE
  16212. ** <li> SQLITE_MUTEX_STATIC_MASTER
  16213. ** <li> SQLITE_MUTEX_STATIC_MEM
  16214. ** <li> SQLITE_MUTEX_STATIC_MEM2
  16215. ** <li> SQLITE_MUTEX_STATIC_PRNG
  16216. ** <li> SQLITE_MUTEX_STATIC_LRU
  16217. ** <li> SQLITE_MUTEX_STATIC_PMEM
  16218. ** </ul>
  16219. **
  16220. ** The first two constants cause sqlite3_mutex_alloc() to create
  16221. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  16222. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  16223. ** The mutex implementation does not need to make a distinction
  16224. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  16225. ** not want to. But SQLite will only request a recursive mutex in
  16226. ** cases where it really needs one. If a faster non-recursive mutex
  16227. ** implementation is available on the host platform, the mutex subsystem
  16228. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  16229. **
  16230. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  16231. ** a pointer to a static preexisting mutex. Six static mutexes are
  16232. ** used by the current version of SQLite. Future versions of SQLite
  16233. ** may add additional static mutexes. Static mutexes are for internal
  16234. ** use by SQLite only. Applications that use SQLite mutexes should
  16235. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  16236. ** SQLITE_MUTEX_RECURSIVE.
  16237. **
  16238. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  16239. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  16240. ** returns a different mutex on every call. But for the static
  16241. ** mutex types, the same mutex is returned on every call that has
  16242. ** the same type number.
  16243. */
  16244. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  16245. static sqlite3_mutex staticMutexes[] = {
  16246. SQLITE3_MUTEX_INITIALIZER,
  16247. SQLITE3_MUTEX_INITIALIZER,
  16248. SQLITE3_MUTEX_INITIALIZER,
  16249. SQLITE3_MUTEX_INITIALIZER,
  16250. SQLITE3_MUTEX_INITIALIZER,
  16251. SQLITE3_MUTEX_INITIALIZER
  16252. };
  16253. sqlite3_mutex *p;
  16254. switch( iType ){
  16255. case SQLITE_MUTEX_RECURSIVE: {
  16256. p = sqlite3MallocZero( sizeof(*p) );
  16257. if( p ){
  16258. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  16259. /* If recursive mutexes are not available, we will have to
  16260. ** build our own. See below. */
  16261. pthread_mutex_init(&p->mutex, 0);
  16262. #else
  16263. /* Use a recursive mutex if it is available */
  16264. pthread_mutexattr_t recursiveAttr;
  16265. pthread_mutexattr_init(&recursiveAttr);
  16266. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  16267. pthread_mutex_init(&p->mutex, &recursiveAttr);
  16268. pthread_mutexattr_destroy(&recursiveAttr);
  16269. #endif
  16270. #if SQLITE_MUTEX_NREF
  16271. p->id = iType;
  16272. #endif
  16273. }
  16274. break;
  16275. }
  16276. case SQLITE_MUTEX_FAST: {
  16277. p = sqlite3MallocZero( sizeof(*p) );
  16278. if( p ){
  16279. #if SQLITE_MUTEX_NREF
  16280. p->id = iType;
  16281. #endif
  16282. pthread_mutex_init(&p->mutex, 0);
  16283. }
  16284. break;
  16285. }
  16286. default: {
  16287. assert( iType-2 >= 0 );
  16288. assert( iType-2 < ArraySize(staticMutexes) );
  16289. p = &staticMutexes[iType-2];
  16290. #if SQLITE_MUTEX_NREF
  16291. p->id = iType;
  16292. #endif
  16293. break;
  16294. }
  16295. }
  16296. return p;
  16297. }
  16298. /*
  16299. ** This routine deallocates a previously
  16300. ** allocated mutex. SQLite is careful to deallocate every
  16301. ** mutex that it allocates.
  16302. */
  16303. static void pthreadMutexFree(sqlite3_mutex *p){
  16304. assert( p->nRef==0 );
  16305. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  16306. pthread_mutex_destroy(&p->mutex);
  16307. sqlite3_free(p);
  16308. }
  16309. /*
  16310. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  16311. ** to enter a mutex. If another thread is already within the mutex,
  16312. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  16313. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  16314. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  16315. ** be entered multiple times by the same thread. In such cases the,
  16316. ** mutex must be exited an equal number of times before another thread
  16317. ** can enter. If the same thread tries to enter any other kind of mutex
  16318. ** more than once, the behavior is undefined.
  16319. */
  16320. static void pthreadMutexEnter(sqlite3_mutex *p){
  16321. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  16322. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  16323. /* If recursive mutexes are not available, then we have to grow
  16324. ** our own. This implementation assumes that pthread_equal()
  16325. ** is atomic - that it cannot be deceived into thinking self
  16326. ** and p->owner are equal if p->owner changes between two values
  16327. ** that are not equal to self while the comparison is taking place.
  16328. ** This implementation also assumes a coherent cache - that
  16329. ** separate processes cannot read different values from the same
  16330. ** address at the same time. If either of these two conditions
  16331. ** are not met, then the mutexes will fail and problems will result.
  16332. */
  16333. {
  16334. pthread_t self = pthread_self();
  16335. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  16336. p->nRef++;
  16337. }else{
  16338. pthread_mutex_lock(&p->mutex);
  16339. assert( p->nRef==0 );
  16340. p->owner = self;
  16341. p->nRef = 1;
  16342. }
  16343. }
  16344. #else
  16345. /* Use the built-in recursive mutexes if they are available.
  16346. */
  16347. pthread_mutex_lock(&p->mutex);
  16348. #if SQLITE_MUTEX_NREF
  16349. assert( p->nRef>0 || p->owner==0 );
  16350. p->owner = pthread_self();
  16351. p->nRef++;
  16352. #endif
  16353. #endif
  16354. #ifdef SQLITE_DEBUG
  16355. if( p->trace ){
  16356. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  16357. }
  16358. #endif
  16359. }
  16360. static int pthreadMutexTry(sqlite3_mutex *p){
  16361. int rc;
  16362. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  16363. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  16364. /* If recursive mutexes are not available, then we have to grow
  16365. ** our own. This implementation assumes that pthread_equal()
  16366. ** is atomic - that it cannot be deceived into thinking self
  16367. ** and p->owner are equal if p->owner changes between two values
  16368. ** that are not equal to self while the comparison is taking place.
  16369. ** This implementation also assumes a coherent cache - that
  16370. ** separate processes cannot read different values from the same
  16371. ** address at the same time. If either of these two conditions
  16372. ** are not met, then the mutexes will fail and problems will result.
  16373. */
  16374. {
  16375. pthread_t self = pthread_self();
  16376. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  16377. p->nRef++;
  16378. rc = SQLITE_OK;
  16379. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  16380. assert( p->nRef==0 );
  16381. p->owner = self;
  16382. p->nRef = 1;
  16383. rc = SQLITE_OK;
  16384. }else{
  16385. rc = SQLITE_BUSY;
  16386. }
  16387. }
  16388. #else
  16389. /* Use the built-in recursive mutexes if they are available.
  16390. */
  16391. if( pthread_mutex_trylock(&p->mutex)==0 ){
  16392. #if SQLITE_MUTEX_NREF
  16393. p->owner = pthread_self();
  16394. p->nRef++;
  16395. #endif
  16396. rc = SQLITE_OK;
  16397. }else{
  16398. rc = SQLITE_BUSY;
  16399. }
  16400. #endif
  16401. #ifdef SQLITE_DEBUG
  16402. if( rc==SQLITE_OK && p->trace ){
  16403. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  16404. }
  16405. #endif
  16406. return rc;
  16407. }
  16408. /*
  16409. ** The sqlite3_mutex_leave() routine exits a mutex that was
  16410. ** previously entered by the same thread. The behavior
  16411. ** is undefined if the mutex is not currently entered or
  16412. ** is not currently allocated. SQLite will never do either.
  16413. */
  16414. static void pthreadMutexLeave(sqlite3_mutex *p){
  16415. assert( pthreadMutexHeld(p) );
  16416. #if SQLITE_MUTEX_NREF
  16417. p->nRef--;
  16418. if( p->nRef==0 ) p->owner = 0;
  16419. #endif
  16420. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  16421. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  16422. if( p->nRef==0 ){
  16423. pthread_mutex_unlock(&p->mutex);
  16424. }
  16425. #else
  16426. pthread_mutex_unlock(&p->mutex);
  16427. #endif
  16428. #ifdef SQLITE_DEBUG
  16429. if( p->trace ){
  16430. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  16431. }
  16432. #endif
  16433. }
  16434. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  16435. static const sqlite3_mutex_methods sMutex = {
  16436. pthreadMutexInit,
  16437. pthreadMutexEnd,
  16438. pthreadMutexAlloc,
  16439. pthreadMutexFree,
  16440. pthreadMutexEnter,
  16441. pthreadMutexTry,
  16442. pthreadMutexLeave,
  16443. #ifdef SQLITE_DEBUG
  16444. pthreadMutexHeld,
  16445. pthreadMutexNotheld
  16446. #else
  16447. 0,
  16448. 0
  16449. #endif
  16450. };
  16451. return &sMutex;
  16452. }
  16453. #endif /* SQLITE_MUTEX_PTHREAD */
  16454. /************** End of mutex_unix.c ******************************************/
  16455. /************** Begin file mutex_w32.c ***************************************/
  16456. /*
  16457. ** 2007 August 14
  16458. **
  16459. ** The author disclaims copyright to this source code. In place of
  16460. ** a legal notice, here is a blessing:
  16461. **
  16462. ** May you do good and not evil.
  16463. ** May you find forgiveness for yourself and forgive others.
  16464. ** May you share freely, never taking more than you give.
  16465. **
  16466. *************************************************************************
  16467. ** This file contains the C functions that implement mutexes for win32
  16468. */
  16469. /*
  16470. ** The code in this file is only used if we are compiling multithreaded
  16471. ** on a win32 system.
  16472. */
  16473. #ifdef SQLITE_MUTEX_W32
  16474. /*
  16475. ** Each recursive mutex is an instance of the following structure.
  16476. */
  16477. struct sqlite3_mutex {
  16478. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  16479. int id; /* Mutex type */
  16480. #ifdef SQLITE_DEBUG
  16481. volatile int nRef; /* Number of enterances */
  16482. volatile DWORD owner; /* Thread holding this mutex */
  16483. int trace; /* True to trace changes */
  16484. #endif
  16485. };
  16486. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  16487. #ifdef SQLITE_DEBUG
  16488. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
  16489. #else
  16490. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  16491. #endif
  16492. /*
  16493. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  16494. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  16495. **
  16496. ** Here is an interesting observation: Win95, Win98, and WinME lack
  16497. ** the LockFileEx() API. But we can still statically link against that
  16498. ** API as long as we don't call it win running Win95/98/ME. A call to
  16499. ** this routine is used to determine if the host is Win95/98/ME or
  16500. ** WinNT/2K/XP so that we will know whether or not we can safely call
  16501. ** the LockFileEx() API.
  16502. **
  16503. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  16504. ** which is only available if your application was compiled with
  16505. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  16506. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  16507. ** this out as well.
  16508. */
  16509. #if 0
  16510. #if SQLITE_OS_WINCE
  16511. # define mutexIsNT() (1)
  16512. #else
  16513. static int mutexIsNT(void){
  16514. static int osType = 0;
  16515. if( osType==0 ){
  16516. OSVERSIONINFO sInfo;
  16517. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  16518. GetVersionEx(&sInfo);
  16519. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  16520. }
  16521. return osType==2;
  16522. }
  16523. #endif /* SQLITE_OS_WINCE */
  16524. #endif
  16525. #ifdef SQLITE_DEBUG
  16526. /*
  16527. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  16528. ** intended for use only inside assert() statements.
  16529. */
  16530. static int winMutexHeld(sqlite3_mutex *p){
  16531. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  16532. }
  16533. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  16534. return p->nRef==0 || p->owner!=tid;
  16535. }
  16536. static int winMutexNotheld(sqlite3_mutex *p){
  16537. DWORD tid = GetCurrentThreadId();
  16538. return winMutexNotheld2(p, tid);
  16539. }
  16540. #endif
  16541. /*
  16542. ** Initialize and deinitialize the mutex subsystem.
  16543. */
  16544. static sqlite3_mutex winMutex_staticMutexes[6] = {
  16545. SQLITE3_MUTEX_INITIALIZER,
  16546. SQLITE3_MUTEX_INITIALIZER,
  16547. SQLITE3_MUTEX_INITIALIZER,
  16548. SQLITE3_MUTEX_INITIALIZER,
  16549. SQLITE3_MUTEX_INITIALIZER,
  16550. SQLITE3_MUTEX_INITIALIZER
  16551. };
  16552. static int winMutex_isInit = 0;
  16553. /* As winMutexInit() and winMutexEnd() are called as part
  16554. ** of the sqlite3_initialize and sqlite3_shutdown()
  16555. ** processing, the "interlocked" magic is probably not
  16556. ** strictly necessary.
  16557. */
  16558. static long winMutex_lock = 0;
  16559. static int winMutexInit(void){
  16560. /* The first to increment to 1 does actual initialization */
  16561. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  16562. int i;
  16563. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  16564. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  16565. }
  16566. winMutex_isInit = 1;
  16567. }else{
  16568. /* Someone else is in the process of initing the static mutexes */
  16569. while( !winMutex_isInit ){
  16570. Sleep(1);
  16571. }
  16572. }
  16573. return SQLITE_OK;
  16574. }
  16575. static int winMutexEnd(void){
  16576. /* The first to decrement to 0 does actual shutdown
  16577. ** (which should be the last to shutdown.) */
  16578. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  16579. if( winMutex_isInit==1 ){
  16580. int i;
  16581. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  16582. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  16583. }
  16584. winMutex_isInit = 0;
  16585. }
  16586. }
  16587. return SQLITE_OK;
  16588. }
  16589. /*
  16590. ** The sqlite3_mutex_alloc() routine allocates a new
  16591. ** mutex and returns a pointer to it. If it returns NULL
  16592. ** that means that a mutex could not be allocated. SQLite
  16593. ** will unwind its stack and return an error. The argument
  16594. ** to sqlite3_mutex_alloc() is one of these integer constants:
  16595. **
  16596. ** <ul>
  16597. ** <li> SQLITE_MUTEX_FAST
  16598. ** <li> SQLITE_MUTEX_RECURSIVE
  16599. ** <li> SQLITE_MUTEX_STATIC_MASTER
  16600. ** <li> SQLITE_MUTEX_STATIC_MEM
  16601. ** <li> SQLITE_MUTEX_STATIC_MEM2
  16602. ** <li> SQLITE_MUTEX_STATIC_PRNG
  16603. ** <li> SQLITE_MUTEX_STATIC_LRU
  16604. ** <li> SQLITE_MUTEX_STATIC_PMEM
  16605. ** </ul>
  16606. **
  16607. ** The first two constants cause sqlite3_mutex_alloc() to create
  16608. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  16609. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  16610. ** The mutex implementation does not need to make a distinction
  16611. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  16612. ** not want to. But SQLite will only request a recursive mutex in
  16613. ** cases where it really needs one. If a faster non-recursive mutex
  16614. ** implementation is available on the host platform, the mutex subsystem
  16615. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  16616. **
  16617. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  16618. ** a pointer to a static preexisting mutex. Six static mutexes are
  16619. ** used by the current version of SQLite. Future versions of SQLite
  16620. ** may add additional static mutexes. Static mutexes are for internal
  16621. ** use by SQLite only. Applications that use SQLite mutexes should
  16622. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  16623. ** SQLITE_MUTEX_RECURSIVE.
  16624. **
  16625. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  16626. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  16627. ** returns a different mutex on every call. But for the static
  16628. ** mutex types, the same mutex is returned on every call that has
  16629. ** the same type number.
  16630. */
  16631. static sqlite3_mutex *winMutexAlloc(int iType){
  16632. sqlite3_mutex *p;
  16633. switch( iType ){
  16634. case SQLITE_MUTEX_FAST:
  16635. case SQLITE_MUTEX_RECURSIVE: {
  16636. p = sqlite3MallocZero( sizeof(*p) );
  16637. if( p ){
  16638. #ifdef SQLITE_DEBUG
  16639. p->id = iType;
  16640. #endif
  16641. InitializeCriticalSection(&p->mutex);
  16642. }
  16643. break;
  16644. }
  16645. default: {
  16646. assert( winMutex_isInit==1 );
  16647. assert( iType-2 >= 0 );
  16648. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  16649. p = &winMutex_staticMutexes[iType-2];
  16650. #ifdef SQLITE_DEBUG
  16651. p->id = iType;
  16652. #endif
  16653. break;
  16654. }
  16655. }
  16656. return p;
  16657. }
  16658. /*
  16659. ** This routine deallocates a previously
  16660. ** allocated mutex. SQLite is careful to deallocate every
  16661. ** mutex that it allocates.
  16662. */
  16663. static void winMutexFree(sqlite3_mutex *p){
  16664. assert( p );
  16665. assert( p->nRef==0 && p->owner==0 );
  16666. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  16667. DeleteCriticalSection(&p->mutex);
  16668. sqlite3_free(p);
  16669. }
  16670. /*
  16671. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  16672. ** to enter a mutex. If another thread is already within the mutex,
  16673. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  16674. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  16675. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  16676. ** be entered multiple times by the same thread. In such cases the,
  16677. ** mutex must be exited an equal number of times before another thread
  16678. ** can enter. If the same thread tries to enter any other kind of mutex
  16679. ** more than once, the behavior is undefined.
  16680. */
  16681. static void winMutexEnter(sqlite3_mutex *p){
  16682. #ifdef SQLITE_DEBUG
  16683. DWORD tid = GetCurrentThreadId();
  16684. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  16685. #endif
  16686. EnterCriticalSection(&p->mutex);
  16687. #ifdef SQLITE_DEBUG
  16688. assert( p->nRef>0 || p->owner==0 );
  16689. p->owner = tid;
  16690. p->nRef++;
  16691. if( p->trace ){
  16692. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  16693. }
  16694. #endif
  16695. }
  16696. static int winMutexTry(sqlite3_mutex *p){
  16697. #ifndef NDEBUG
  16698. DWORD tid = GetCurrentThreadId();
  16699. #endif
  16700. int rc = SQLITE_BUSY;
  16701. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  16702. /*
  16703. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  16704. ** is used it is merely an optimization. So it is OK for it to always
  16705. ** fail.
  16706. **
  16707. ** The TryEnterCriticalSection() interface is only available on WinNT.
  16708. ** And some windows compilers complain if you try to use it without
  16709. ** first doing some #defines that prevent SQLite from building on Win98.
  16710. ** For that reason, we will omit this optimization for now. See
  16711. ** ticket #2685.
  16712. */
  16713. #if 0
  16714. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  16715. p->owner = tid;
  16716. p->nRef++;
  16717. rc = SQLITE_OK;
  16718. }
  16719. #else
  16720. UNUSED_PARAMETER(p);
  16721. #endif
  16722. #ifdef SQLITE_DEBUG
  16723. if( rc==SQLITE_OK && p->trace ){
  16724. printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  16725. }
  16726. #endif
  16727. return rc;
  16728. }
  16729. /*
  16730. ** The sqlite3_mutex_leave() routine exits a mutex that was
  16731. ** previously entered by the same thread. The behavior
  16732. ** is undefined if the mutex is not currently entered or
  16733. ** is not currently allocated. SQLite will never do either.
  16734. */
  16735. static void winMutexLeave(sqlite3_mutex *p){
  16736. #ifndef NDEBUG
  16737. DWORD tid = GetCurrentThreadId();
  16738. assert( p->nRef>0 );
  16739. assert( p->owner==tid );
  16740. p->nRef--;
  16741. if( p->nRef==0 ) p->owner = 0;
  16742. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  16743. #endif
  16744. LeaveCriticalSection(&p->mutex);
  16745. #ifdef SQLITE_DEBUG
  16746. if( p->trace ){
  16747. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  16748. }
  16749. #endif
  16750. }
  16751. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  16752. static const sqlite3_mutex_methods sMutex = {
  16753. winMutexInit,
  16754. winMutexEnd,
  16755. winMutexAlloc,
  16756. winMutexFree,
  16757. winMutexEnter,
  16758. winMutexTry,
  16759. winMutexLeave,
  16760. #ifdef SQLITE_DEBUG
  16761. winMutexHeld,
  16762. winMutexNotheld
  16763. #else
  16764. 0,
  16765. 0
  16766. #endif
  16767. };
  16768. return &sMutex;
  16769. }
  16770. #endif /* SQLITE_MUTEX_W32 */
  16771. /************** End of mutex_w32.c *******************************************/
  16772. /************** Begin file malloc.c ******************************************/
  16773. /*
  16774. ** 2001 September 15
  16775. **
  16776. ** The author disclaims copyright to this source code. In place of
  16777. ** a legal notice, here is a blessing:
  16778. **
  16779. ** May you do good and not evil.
  16780. ** May you find forgiveness for yourself and forgive others.
  16781. ** May you share freely, never taking more than you give.
  16782. **
  16783. *************************************************************************
  16784. **
  16785. ** Memory allocation functions used throughout sqlite.
  16786. */
  16787. /*
  16788. ** Attempt to release up to n bytes of non-essential memory currently
  16789. ** held by SQLite. An example of non-essential memory is memory used to
  16790. ** cache database pages that are not currently in use.
  16791. */
  16792. SQLITE_API int sqlite3_release_memory(int n){
  16793. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  16794. return sqlite3PcacheReleaseMemory(n);
  16795. #else
  16796. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  16797. ** is a no-op returning zero if SQLite is not compiled with
  16798. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  16799. UNUSED_PARAMETER(n);
  16800. return 0;
  16801. #endif
  16802. }
  16803. /*
  16804. ** An instance of the following object records the location of
  16805. ** each unused scratch buffer.
  16806. */
  16807. typedef struct ScratchFreeslot {
  16808. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  16809. } ScratchFreeslot;
  16810. /*
  16811. ** State information local to the memory allocation subsystem.
  16812. */
  16813. static SQLITE_WSD struct Mem0Global {
  16814. sqlite3_mutex *mutex; /* Mutex to serialize access */
  16815. /*
  16816. ** The alarm callback and its arguments. The mem0.mutex lock will
  16817. ** be held while the callback is running. Recursive calls into
  16818. ** the memory subsystem are allowed, but no new callbacks will be
  16819. ** issued.
  16820. */
  16821. sqlite3_int64 alarmThreshold;
  16822. void (*alarmCallback)(void*, sqlite3_int64,int);
  16823. void *alarmArg;
  16824. /*
  16825. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  16826. ** (so that a range test can be used to determine if an allocation
  16827. ** being freed came from pScratch) and a pointer to the list of
  16828. ** unused scratch allocations.
  16829. */
  16830. void *pScratchEnd;
  16831. ScratchFreeslot *pScratchFree;
  16832. u32 nScratchFree;
  16833. /*
  16834. ** True if heap is nearly "full" where "full" is defined by the
  16835. ** sqlite3_soft_heap_limit() setting.
  16836. */
  16837. int nearlyFull;
  16838. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  16839. #define mem0 GLOBAL(struct Mem0Global, mem0)
  16840. /*
  16841. ** This routine runs when the memory allocator sees that the
  16842. ** total memory allocation is about to exceed the soft heap
  16843. ** limit.
  16844. */
  16845. static void softHeapLimitEnforcer(
  16846. void *NotUsed,
  16847. sqlite3_int64 NotUsed2,
  16848. int allocSize
  16849. ){
  16850. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  16851. sqlite3_release_memory(allocSize);
  16852. }
  16853. /*
  16854. ** Change the alarm callback
  16855. */
  16856. static int sqlite3MemoryAlarm(
  16857. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  16858. void *pArg,
  16859. sqlite3_int64 iThreshold
  16860. ){
  16861. int nUsed;
  16862. sqlite3_mutex_enter(mem0.mutex);
  16863. mem0.alarmCallback = xCallback;
  16864. mem0.alarmArg = pArg;
  16865. mem0.alarmThreshold = iThreshold;
  16866. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  16867. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  16868. sqlite3_mutex_leave(mem0.mutex);
  16869. return SQLITE_OK;
  16870. }
  16871. #ifndef SQLITE_OMIT_DEPRECATED
  16872. /*
  16873. ** Deprecated external interface. Internal/core SQLite code
  16874. ** should call sqlite3MemoryAlarm.
  16875. */
  16876. SQLITE_API int sqlite3_memory_alarm(
  16877. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  16878. void *pArg,
  16879. sqlite3_int64 iThreshold
  16880. ){
  16881. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  16882. }
  16883. #endif
  16884. /*
  16885. ** Set the soft heap-size limit for the library. Passing a zero or
  16886. ** negative value indicates no limit.
  16887. */
  16888. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  16889. sqlite3_int64 priorLimit;
  16890. sqlite3_int64 excess;
  16891. #ifndef SQLITE_OMIT_AUTOINIT
  16892. sqlite3_initialize();
  16893. #endif
  16894. sqlite3_mutex_enter(mem0.mutex);
  16895. priorLimit = mem0.alarmThreshold;
  16896. sqlite3_mutex_leave(mem0.mutex);
  16897. if( n<0 ) return priorLimit;
  16898. if( n>0 ){
  16899. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  16900. }else{
  16901. sqlite3MemoryAlarm(0, 0, 0);
  16902. }
  16903. excess = sqlite3_memory_used() - n;
  16904. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  16905. return priorLimit;
  16906. }
  16907. SQLITE_API void sqlite3_soft_heap_limit(int n){
  16908. if( n<0 ) n = 0;
  16909. sqlite3_soft_heap_limit64(n);
  16910. }
  16911. /*
  16912. ** Initialize the memory allocation subsystem.
  16913. */
  16914. SQLITE_PRIVATE int sqlite3MallocInit(void){
  16915. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  16916. sqlite3MemSetDefault();
  16917. }
  16918. memset(&mem0, 0, sizeof(mem0));
  16919. if( sqlite3GlobalConfig.bCoreMutex ){
  16920. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16921. }
  16922. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  16923. && sqlite3GlobalConfig.nScratch>0 ){
  16924. int i, n, sz;
  16925. ScratchFreeslot *pSlot;
  16926. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  16927. sqlite3GlobalConfig.szScratch = sz;
  16928. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  16929. n = sqlite3GlobalConfig.nScratch;
  16930. mem0.pScratchFree = pSlot;
  16931. mem0.nScratchFree = n;
  16932. for(i=0; i<n-1; i++){
  16933. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  16934. pSlot = pSlot->pNext;
  16935. }
  16936. pSlot->pNext = 0;
  16937. mem0.pScratchEnd = (void*)&pSlot[1];
  16938. }else{
  16939. mem0.pScratchEnd = 0;
  16940. sqlite3GlobalConfig.pScratch = 0;
  16941. sqlite3GlobalConfig.szScratch = 0;
  16942. sqlite3GlobalConfig.nScratch = 0;
  16943. }
  16944. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  16945. || sqlite3GlobalConfig.nPage<1 ){
  16946. sqlite3GlobalConfig.pPage = 0;
  16947. sqlite3GlobalConfig.szPage = 0;
  16948. sqlite3GlobalConfig.nPage = 0;
  16949. }
  16950. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  16951. }
  16952. /*
  16953. ** Return true if the heap is currently under memory pressure - in other
  16954. ** words if the amount of heap used is close to the limit set by
  16955. ** sqlite3_soft_heap_limit().
  16956. */
  16957. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  16958. return mem0.nearlyFull;
  16959. }
  16960. /*
  16961. ** Deinitialize the memory allocation subsystem.
  16962. */
  16963. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  16964. if( sqlite3GlobalConfig.m.xShutdown ){
  16965. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  16966. }
  16967. memset(&mem0, 0, sizeof(mem0));
  16968. }
  16969. /*
  16970. ** Return the amount of memory currently checked out.
  16971. */
  16972. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  16973. int n, mx;
  16974. sqlite3_int64 res;
  16975. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  16976. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  16977. return res;
  16978. }
  16979. /*
  16980. ** Return the maximum amount of memory that has ever been
  16981. ** checked out since either the beginning of this process
  16982. ** or since the most recent reset.
  16983. */
  16984. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  16985. int n, mx;
  16986. sqlite3_int64 res;
  16987. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  16988. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  16989. return res;
  16990. }
  16991. /*
  16992. ** Trigger the alarm
  16993. */
  16994. static void sqlite3MallocAlarm(int nByte){
  16995. void (*xCallback)(void*,sqlite3_int64,int);
  16996. sqlite3_int64 nowUsed;
  16997. void *pArg;
  16998. if( mem0.alarmCallback==0 ) return;
  16999. xCallback = mem0.alarmCallback;
  17000. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17001. pArg = mem0.alarmArg;
  17002. mem0.alarmCallback = 0;
  17003. sqlite3_mutex_leave(mem0.mutex);
  17004. xCallback(pArg, nowUsed, nByte);
  17005. sqlite3_mutex_enter(mem0.mutex);
  17006. mem0.alarmCallback = xCallback;
  17007. mem0.alarmArg = pArg;
  17008. }
  17009. /*
  17010. ** Do a memory allocation with statistics and alarms. Assume the
  17011. ** lock is already held.
  17012. */
  17013. static int mallocWithAlarm(int n, void **pp){
  17014. int nFull;
  17015. void *p;
  17016. assert( sqlite3_mutex_held(mem0.mutex) );
  17017. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  17018. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  17019. if( mem0.alarmCallback!=0 ){
  17020. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  17021. if( nUsed+nFull >= mem0.alarmThreshold ){
  17022. mem0.nearlyFull = 1;
  17023. sqlite3MallocAlarm(nFull);
  17024. }else{
  17025. mem0.nearlyFull = 0;
  17026. }
  17027. }
  17028. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  17029. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  17030. if( p==0 && mem0.alarmCallback ){
  17031. sqlite3MallocAlarm(nFull);
  17032. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  17033. }
  17034. #endif
  17035. if( p ){
  17036. nFull = sqlite3MallocSize(p);
  17037. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  17038. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  17039. }
  17040. *pp = p;
  17041. return nFull;
  17042. }
  17043. /*
  17044. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  17045. ** assumes the memory subsystem has already been initialized.
  17046. */
  17047. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  17048. void *p;
  17049. if( n<=0 /* IMP: R-65312-04917 */
  17050. || n>=0x7fffff00
  17051. ){
  17052. /* A memory allocation of a number of bytes which is near the maximum
  17053. ** signed integer value might cause an integer overflow inside of the
  17054. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  17055. ** 255 bytes of overhead. SQLite itself will never use anything near
  17056. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  17057. p = 0;
  17058. }else if( sqlite3GlobalConfig.bMemstat ){
  17059. sqlite3_mutex_enter(mem0.mutex);
  17060. mallocWithAlarm(n, &p);
  17061. sqlite3_mutex_leave(mem0.mutex);
  17062. }else{
  17063. p = sqlite3GlobalConfig.m.xMalloc(n);
  17064. }
  17065. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
  17066. return p;
  17067. }
  17068. /*
  17069. ** This version of the memory allocation is for use by the application.
  17070. ** First make sure the memory subsystem is initialized, then do the
  17071. ** allocation.
  17072. */
  17073. SQLITE_API void *sqlite3_malloc(int n){
  17074. #ifndef SQLITE_OMIT_AUTOINIT
  17075. if( sqlite3_initialize() ) return 0;
  17076. #endif
  17077. return sqlite3Malloc(n);
  17078. }
  17079. /*
  17080. ** Each thread may only have a single outstanding allocation from
  17081. ** xScratchMalloc(). We verify this constraint in the single-threaded
  17082. ** case by setting scratchAllocOut to 1 when an allocation
  17083. ** is outstanding clearing it when the allocation is freed.
  17084. */
  17085. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17086. static int scratchAllocOut = 0;
  17087. #endif
  17088. /*
  17089. ** Allocate memory that is to be used and released right away.
  17090. ** This routine is similar to alloca() in that it is not intended
  17091. ** for situations where the memory might be held long-term. This
  17092. ** routine is intended to get memory to old large transient data
  17093. ** structures that would not normally fit on the stack of an
  17094. ** embedded processor.
  17095. */
  17096. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  17097. void *p;
  17098. assert( n>0 );
  17099. sqlite3_mutex_enter(mem0.mutex);
  17100. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  17101. p = mem0.pScratchFree;
  17102. mem0.pScratchFree = mem0.pScratchFree->pNext;
  17103. mem0.nScratchFree--;
  17104. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  17105. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  17106. sqlite3_mutex_leave(mem0.mutex);
  17107. }else{
  17108. if( sqlite3GlobalConfig.bMemstat ){
  17109. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  17110. n = mallocWithAlarm(n, &p);
  17111. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  17112. sqlite3_mutex_leave(mem0.mutex);
  17113. }else{
  17114. sqlite3_mutex_leave(mem0.mutex);
  17115. p = sqlite3GlobalConfig.m.xMalloc(n);
  17116. }
  17117. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  17118. }
  17119. assert( sqlite3_mutex_notheld(mem0.mutex) );
  17120. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17121. /* Verify that no more than two scratch allocations per thread
  17122. ** are outstanding at one time. (This is only checked in the
  17123. ** single-threaded case since checking in the multi-threaded case
  17124. ** would be much more complicated.) */
  17125. assert( scratchAllocOut<=1 );
  17126. if( p ) scratchAllocOut++;
  17127. #endif
  17128. return p;
  17129. }
  17130. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  17131. if( p ){
  17132. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  17133. /* Verify that no more than two scratch allocation per thread
  17134. ** is outstanding at one time. (This is only checked in the
  17135. ** single-threaded case since checking in the multi-threaded case
  17136. ** would be much more complicated.) */
  17137. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  17138. scratchAllocOut--;
  17139. #endif
  17140. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  17141. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  17142. ScratchFreeslot *pSlot;
  17143. pSlot = (ScratchFreeslot*)p;
  17144. sqlite3_mutex_enter(mem0.mutex);
  17145. pSlot->pNext = mem0.pScratchFree;
  17146. mem0.pScratchFree = pSlot;
  17147. mem0.nScratchFree++;
  17148. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  17149. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  17150. sqlite3_mutex_leave(mem0.mutex);
  17151. }else{
  17152. /* Release memory back to the heap */
  17153. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  17154. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  17155. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  17156. if( sqlite3GlobalConfig.bMemstat ){
  17157. int iSize = sqlite3MallocSize(p);
  17158. sqlite3_mutex_enter(mem0.mutex);
  17159. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  17160. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  17161. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  17162. sqlite3GlobalConfig.m.xFree(p);
  17163. sqlite3_mutex_leave(mem0.mutex);
  17164. }else{
  17165. sqlite3GlobalConfig.m.xFree(p);
  17166. }
  17167. }
  17168. }
  17169. }
  17170. /*
  17171. ** TRUE if p is a lookaside memory allocation from db
  17172. */
  17173. #ifndef SQLITE_OMIT_LOOKASIDE
  17174. static int isLookaside(sqlite3 *db, void *p){
  17175. return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  17176. }
  17177. #else
  17178. #define isLookaside(A,B) 0
  17179. #endif
  17180. /*
  17181. ** Return the size of a memory allocation previously obtained from
  17182. ** sqlite3Malloc() or sqlite3_malloc().
  17183. */
  17184. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  17185. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  17186. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  17187. return sqlite3GlobalConfig.m.xSize(p);
  17188. }
  17189. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  17190. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  17191. if( db && isLookaside(db, p) ){
  17192. return db->lookaside.sz;
  17193. }else{
  17194. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  17195. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  17196. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  17197. return sqlite3GlobalConfig.m.xSize(p);
  17198. }
  17199. }
  17200. /*
  17201. ** Free memory previously obtained from sqlite3Malloc().
  17202. */
  17203. SQLITE_API void sqlite3_free(void *p){
  17204. if( p==0 ) return; /* IMP: R-49053-54554 */
  17205. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  17206. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  17207. if( sqlite3GlobalConfig.bMemstat ){
  17208. sqlite3_mutex_enter(mem0.mutex);
  17209. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  17210. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  17211. sqlite3GlobalConfig.m.xFree(p);
  17212. sqlite3_mutex_leave(mem0.mutex);
  17213. }else{
  17214. sqlite3GlobalConfig.m.xFree(p);
  17215. }
  17216. }
  17217. /*
  17218. ** Free memory that might be associated with a particular database
  17219. ** connection.
  17220. */
  17221. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  17222. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  17223. if( db ){
  17224. if( db->pnBytesFreed ){
  17225. *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
  17226. return;
  17227. }
  17228. if( isLookaside(db, p) ){
  17229. LookasideSlot *pBuf = (LookasideSlot*)p;
  17230. pBuf->pNext = db->lookaside.pFree;
  17231. db->lookaside.pFree = pBuf;
  17232. db->lookaside.nOut--;
  17233. return;
  17234. }
  17235. }
  17236. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  17237. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  17238. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  17239. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  17240. sqlite3_free(p);
  17241. }
  17242. /*
  17243. ** Change the size of an existing memory allocation
  17244. */
  17245. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  17246. int nOld, nNew;
  17247. void *pNew;
  17248. if( pOld==0 ){
  17249. return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
  17250. }
  17251. if( nBytes<=0 ){
  17252. sqlite3_free(pOld); /* IMP: R-31593-10574 */
  17253. return 0;
  17254. }
  17255. if( nBytes>=0x7fffff00 ){
  17256. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  17257. return 0;
  17258. }
  17259. nOld = sqlite3MallocSize(pOld);
  17260. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  17261. ** argument to xRealloc is always a value returned by a prior call to
  17262. ** xRoundup. */
  17263. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  17264. if( nOld==nNew ){
  17265. pNew = pOld;
  17266. }else if( sqlite3GlobalConfig.bMemstat ){
  17267. sqlite3_mutex_enter(mem0.mutex);
  17268. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  17269. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
  17270. mem0.alarmThreshold ){
  17271. sqlite3MallocAlarm(nNew-nOld);
  17272. }
  17273. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  17274. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  17275. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  17276. if( pNew==0 && mem0.alarmCallback ){
  17277. sqlite3MallocAlarm(nBytes);
  17278. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  17279. }
  17280. if( pNew ){
  17281. nNew = sqlite3MallocSize(pNew);
  17282. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  17283. }
  17284. sqlite3_mutex_leave(mem0.mutex);
  17285. }else{
  17286. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  17287. }
  17288. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  17289. return pNew;
  17290. }
  17291. /*
  17292. ** The public interface to sqlite3Realloc. Make sure that the memory
  17293. ** subsystem is initialized prior to invoking sqliteRealloc.
  17294. */
  17295. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  17296. #ifndef SQLITE_OMIT_AUTOINIT
  17297. if( sqlite3_initialize() ) return 0;
  17298. #endif
  17299. return sqlite3Realloc(pOld, n);
  17300. }
  17301. /*
  17302. ** Allocate and zero memory.
  17303. */
  17304. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  17305. void *p = sqlite3Malloc(n);
  17306. if( p ){
  17307. memset(p, 0, n);
  17308. }
  17309. return p;
  17310. }
  17311. /*
  17312. ** Allocate and zero memory. If the allocation fails, make
  17313. ** the mallocFailed flag in the connection pointer.
  17314. */
  17315. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  17316. void *p = sqlite3DbMallocRaw(db, n);
  17317. if( p ){
  17318. memset(p, 0, n);
  17319. }
  17320. return p;
  17321. }
  17322. /*
  17323. ** Allocate and zero memory. If the allocation fails, make
  17324. ** the mallocFailed flag in the connection pointer.
  17325. **
  17326. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  17327. ** failure on the same database connection) then always return 0.
  17328. ** Hence for a particular database connection, once malloc starts
  17329. ** failing, it fails consistently until mallocFailed is reset.
  17330. ** This is an important assumption. There are many places in the
  17331. ** code that do things like this:
  17332. **
  17333. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  17334. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  17335. ** if( b ) a[10] = 9;
  17336. **
  17337. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  17338. ** that all prior mallocs (ex: "a") worked too.
  17339. */
  17340. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  17341. void *p;
  17342. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  17343. assert( db==0 || db->pnBytesFreed==0 );
  17344. #ifndef SQLITE_OMIT_LOOKASIDE
  17345. if( db ){
  17346. LookasideSlot *pBuf;
  17347. if( db->mallocFailed ){
  17348. return 0;
  17349. }
  17350. if( db->lookaside.bEnabled ){
  17351. if( n>db->lookaside.sz ){
  17352. db->lookaside.anStat[1]++;
  17353. }else if( (pBuf = db->lookaside.pFree)==0 ){
  17354. db->lookaside.anStat[2]++;
  17355. }else{
  17356. db->lookaside.pFree = pBuf->pNext;
  17357. db->lookaside.nOut++;
  17358. db->lookaside.anStat[0]++;
  17359. if( db->lookaside.nOut>db->lookaside.mxOut ){
  17360. db->lookaside.mxOut = db->lookaside.nOut;
  17361. }
  17362. return (void*)pBuf;
  17363. }
  17364. }
  17365. }
  17366. #else
  17367. if( db && db->mallocFailed ){
  17368. return 0;
  17369. }
  17370. #endif
  17371. p = sqlite3Malloc(n);
  17372. if( !p && db ){
  17373. db->mallocFailed = 1;
  17374. }
  17375. sqlite3MemdebugSetType(p, MEMTYPE_DB |
  17376. ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  17377. return p;
  17378. }
  17379. /*
  17380. ** Resize the block of memory pointed to by p to n bytes. If the
  17381. ** resize fails, set the mallocFailed flag in the connection object.
  17382. */
  17383. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  17384. void *pNew = 0;
  17385. assert( db!=0 );
  17386. assert( sqlite3_mutex_held(db->mutex) );
  17387. if( db->mallocFailed==0 ){
  17388. if( p==0 ){
  17389. return sqlite3DbMallocRaw(db, n);
  17390. }
  17391. if( isLookaside(db, p) ){
  17392. if( n<=db->lookaside.sz ){
  17393. return p;
  17394. }
  17395. pNew = sqlite3DbMallocRaw(db, n);
  17396. if( pNew ){
  17397. memcpy(pNew, p, db->lookaside.sz);
  17398. sqlite3DbFree(db, p);
  17399. }
  17400. }else{
  17401. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  17402. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  17403. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  17404. pNew = sqlite3_realloc(p, n);
  17405. if( !pNew ){
  17406. sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
  17407. db->mallocFailed = 1;
  17408. }
  17409. sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
  17410. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  17411. }
  17412. }
  17413. return pNew;
  17414. }
  17415. /*
  17416. ** Attempt to reallocate p. If the reallocation fails, then free p
  17417. ** and set the mallocFailed flag in the database connection.
  17418. */
  17419. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  17420. void *pNew;
  17421. pNew = sqlite3DbRealloc(db, p, n);
  17422. if( !pNew ){
  17423. sqlite3DbFree(db, p);
  17424. }
  17425. return pNew;
  17426. }
  17427. /*
  17428. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  17429. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  17430. ** is because when memory debugging is turned on, these two functions are
  17431. ** called via macros that record the current file and line number in the
  17432. ** ThreadData structure.
  17433. */
  17434. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  17435. char *zNew;
  17436. size_t n;
  17437. if( z==0 ){
  17438. return 0;
  17439. }
  17440. n = sqlite3Strlen30(z) + 1;
  17441. assert( (n&0x7fffffff)==n );
  17442. zNew = sqlite3DbMallocRaw(db, (int)n);
  17443. if( zNew ){
  17444. memcpy(zNew, z, n);
  17445. }
  17446. return zNew;
  17447. }
  17448. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  17449. char *zNew;
  17450. if( z==0 ){
  17451. return 0;
  17452. }
  17453. assert( (n&0x7fffffff)==n );
  17454. zNew = sqlite3DbMallocRaw(db, n+1);
  17455. if( zNew ){
  17456. memcpy(zNew, z, n);
  17457. zNew[n] = 0;
  17458. }
  17459. return zNew;
  17460. }
  17461. /*
  17462. ** Create a string from the zFromat argument and the va_list that follows.
  17463. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  17464. ** point to that string.
  17465. */
  17466. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  17467. va_list ap;
  17468. char *z;
  17469. va_start(ap, zFormat);
  17470. z = sqlite3VMPrintf(db, zFormat, ap);
  17471. va_end(ap);
  17472. sqlite3DbFree(db, *pz);
  17473. *pz = z;
  17474. }
  17475. /*
  17476. ** This function must be called before exiting any API function (i.e.
  17477. ** returning control to the user) that has called sqlite3_malloc or
  17478. ** sqlite3_realloc.
  17479. **
  17480. ** The returned value is normally a copy of the second argument to this
  17481. ** function. However, if a malloc() failure has occurred since the previous
  17482. ** invocation SQLITE_NOMEM is returned instead.
  17483. **
  17484. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  17485. ** then the connection error-code (the value returned by sqlite3_errcode())
  17486. ** is set to SQLITE_NOMEM.
  17487. */
  17488. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  17489. /* If the db handle is not NULL, then we must hold the connection handle
  17490. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  17491. ** is unsafe, as is the call to sqlite3Error().
  17492. */
  17493. assert( !db || sqlite3_mutex_held(db->mutex) );
  17494. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  17495. sqlite3Error(db, SQLITE_NOMEM, 0);
  17496. db->mallocFailed = 0;
  17497. rc = SQLITE_NOMEM;
  17498. }
  17499. return rc & (db ? db->errMask : 0xff);
  17500. }
  17501. /************** End of malloc.c **********************************************/
  17502. /************** Begin file printf.c ******************************************/
  17503. /*
  17504. ** The "printf" code that follows dates from the 1980's. It is in
  17505. ** the public domain. The original comments are included here for
  17506. ** completeness. They are very out-of-date but might be useful as
  17507. ** an historical reference. Most of the "enhancements" have been backed
  17508. ** out so that the functionality is now the same as standard printf().
  17509. **
  17510. **************************************************************************
  17511. **
  17512. ** The following modules is an enhanced replacement for the "printf" subroutines
  17513. ** found in the standard C library. The following enhancements are
  17514. ** supported:
  17515. **
  17516. ** + Additional functions. The standard set of "printf" functions
  17517. ** includes printf, fprintf, sprintf, vprintf, vfprintf, and
  17518. ** vsprintf. This module adds the following:
  17519. **
  17520. ** * snprintf -- Works like sprintf, but has an extra argument
  17521. ** which is the size of the buffer written to.
  17522. **
  17523. ** * mprintf -- Similar to sprintf. Writes output to memory
  17524. ** obtained from malloc.
  17525. **
  17526. ** * xprintf -- Calls a function to dispose of output.
  17527. **
  17528. ** * nprintf -- No output, but returns the number of characters
  17529. ** that would have been output by printf.
  17530. **
  17531. ** * A v- version (ex: vsnprintf) of every function is also
  17532. ** supplied.
  17533. **
  17534. ** + A few extensions to the formatting notation are supported:
  17535. **
  17536. ** * The "=" flag (similar to "-") causes the output to be
  17537. ** be centered in the appropriately sized field.
  17538. **
  17539. ** * The %b field outputs an integer in binary notation.
  17540. **
  17541. ** * The %c field now accepts a precision. The character output
  17542. ** is repeated by the number of times the precision specifies.
  17543. **
  17544. ** * The %' field works like %c, but takes as its character the
  17545. ** next character of the format string, instead of the next
  17546. ** argument. For example, printf("%.78'-") prints 78 minus
  17547. ** signs, the same as printf("%.78c",'-').
  17548. **
  17549. ** + When compiled using GCC on a SPARC, this version of printf is
  17550. ** faster than the library printf for SUN OS 4.1.
  17551. **
  17552. ** + All functions are fully reentrant.
  17553. **
  17554. */
  17555. /*
  17556. ** Conversion types fall into various categories as defined by the
  17557. ** following enumeration.
  17558. */
  17559. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  17560. #define etFLOAT 2 /* Floating point. %f */
  17561. #define etEXP 3 /* Exponentional notation. %e and %E */
  17562. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  17563. #define etSIZE 5 /* Return number of characters processed so far. %n */
  17564. #define etSTRING 6 /* Strings. %s */
  17565. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  17566. #define etPERCENT 8 /* Percent symbol. %% */
  17567. #define etCHARX 9 /* Characters. %c */
  17568. /* The rest are extensions, not normally found in printf() */
  17569. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  17570. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  17571. NULL pointers replaced by SQL NULL. %Q */
  17572. #define etTOKEN 12 /* a pointer to a Token structure */
  17573. #define etSRCLIST 13 /* a pointer to a SrcList */
  17574. #define etPOINTER 14 /* The %p conversion */
  17575. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  17576. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  17577. #define etINVALID 0 /* Any unrecognized conversion type */
  17578. /*
  17579. ** An "etByte" is an 8-bit unsigned value.
  17580. */
  17581. typedef unsigned char etByte;
  17582. /*
  17583. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  17584. ** by an instance of the following structure
  17585. */
  17586. typedef struct et_info { /* Information about each format field */
  17587. char fmttype; /* The format field code letter */
  17588. etByte base; /* The base for radix conversion */
  17589. etByte flags; /* One or more of FLAG_ constants below */
  17590. etByte type; /* Conversion paradigm */
  17591. etByte charset; /* Offset into aDigits[] of the digits string */
  17592. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  17593. } et_info;
  17594. /*
  17595. ** Allowed values for et_info.flags
  17596. */
  17597. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  17598. #define FLAG_INTERN 2 /* True if for internal use only */
  17599. #define FLAG_STRING 4 /* Allow infinity precision */
  17600. /*
  17601. ** The following table is searched linearly, so it is good to put the
  17602. ** most frequently used conversion types first.
  17603. */
  17604. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  17605. static const char aPrefix[] = "-x0\000X0";
  17606. static const et_info fmtinfo[] = {
  17607. { 'd', 10, 1, etRADIX, 0, 0 },
  17608. { 's', 0, 4, etSTRING, 0, 0 },
  17609. { 'g', 0, 1, etGENERIC, 30, 0 },
  17610. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  17611. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  17612. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  17613. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  17614. { 'c', 0, 0, etCHARX, 0, 0 },
  17615. { 'o', 8, 0, etRADIX, 0, 2 },
  17616. { 'u', 10, 0, etRADIX, 0, 0 },
  17617. { 'x', 16, 0, etRADIX, 16, 1 },
  17618. { 'X', 16, 0, etRADIX, 0, 4 },
  17619. #ifndef SQLITE_OMIT_FLOATING_POINT
  17620. { 'f', 0, 1, etFLOAT, 0, 0 },
  17621. { 'e', 0, 1, etEXP, 30, 0 },
  17622. { 'E', 0, 1, etEXP, 14, 0 },
  17623. { 'G', 0, 1, etGENERIC, 14, 0 },
  17624. #endif
  17625. { 'i', 10, 1, etRADIX, 0, 0 },
  17626. { 'n', 0, 0, etSIZE, 0, 0 },
  17627. { '%', 0, 0, etPERCENT, 0, 0 },
  17628. { 'p', 16, 0, etPOINTER, 0, 1 },
  17629. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  17630. ** use only */
  17631. { 'T', 0, 2, etTOKEN, 0, 0 },
  17632. { 'S', 0, 2, etSRCLIST, 0, 0 },
  17633. { 'r', 10, 3, etORDINAL, 0, 0 },
  17634. };
  17635. /*
  17636. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  17637. ** conversions will work.
  17638. */
  17639. #ifndef SQLITE_OMIT_FLOATING_POINT
  17640. /*
  17641. ** "*val" is a double such that 0.1 <= *val < 10.0
  17642. ** Return the ascii code for the leading digit of *val, then
  17643. ** multiply "*val" by 10.0 to renormalize.
  17644. **
  17645. ** Example:
  17646. ** input: *val = 3.14159
  17647. ** output: *val = 1.4159 function return = '3'
  17648. **
  17649. ** The counter *cnt is incremented each time. After counter exceeds
  17650. ** 16 (the number of significant digits in a 64-bit float) '0' is
  17651. ** always returned.
  17652. */
  17653. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  17654. int digit;
  17655. LONGDOUBLE_TYPE d;
  17656. if( (*cnt)++ >= 16 ) return '0';
  17657. digit = (int)*val;
  17658. d = digit;
  17659. digit += '0';
  17660. *val = (*val - d)*10.0;
  17661. return (char)digit;
  17662. }
  17663. #endif /* SQLITE_OMIT_FLOATING_POINT */
  17664. /*
  17665. ** Append N space characters to the given string buffer.
  17666. */
  17667. static void appendSpace(StrAccum *pAccum, int N){
  17668. static const char zSpaces[] = " ";
  17669. while( N>=(int)sizeof(zSpaces)-1 ){
  17670. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  17671. N -= sizeof(zSpaces)-1;
  17672. }
  17673. if( N>0 ){
  17674. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  17675. }
  17676. }
  17677. /*
  17678. ** On machines with a small stack size, you can redefine the
  17679. ** SQLITE_PRINT_BUF_SIZE to be less than 350.
  17680. */
  17681. #ifndef SQLITE_PRINT_BUF_SIZE
  17682. # if defined(SQLITE_SMALL_STACK)
  17683. # define SQLITE_PRINT_BUF_SIZE 50
  17684. # else
  17685. # define SQLITE_PRINT_BUF_SIZE 350
  17686. # endif
  17687. #endif
  17688. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  17689. /*
  17690. ** The root program. All variations call this core.
  17691. **
  17692. ** INPUTS:
  17693. ** func This is a pointer to a function taking three arguments
  17694. ** 1. A pointer to anything. Same as the "arg" parameter.
  17695. ** 2. A pointer to the list of characters to be output
  17696. ** (Note, this list is NOT null terminated.)
  17697. ** 3. An integer number of characters to be output.
  17698. ** (Note: This number might be zero.)
  17699. **
  17700. ** arg This is the pointer to anything which will be passed as the
  17701. ** first argument to "func". Use it for whatever you like.
  17702. **
  17703. ** fmt This is the format string, as in the usual print.
  17704. **
  17705. ** ap This is a pointer to a list of arguments. Same as in
  17706. ** vfprint.
  17707. **
  17708. ** OUTPUTS:
  17709. ** The return value is the total number of characters sent to
  17710. ** the function "func". Returns -1 on a error.
  17711. **
  17712. ** Note that the order in which automatic variables are declared below
  17713. ** seems to make a big difference in determining how fast this beast
  17714. ** will run.
  17715. */
  17716. SQLITE_PRIVATE void sqlite3VXPrintf(
  17717. StrAccum *pAccum, /* Accumulate results here */
  17718. int useExtended, /* Allow extended %-conversions */
  17719. const char *fmt, /* Format string */
  17720. va_list ap /* arguments */
  17721. ){
  17722. int c; /* Next character in the format string */
  17723. char *bufpt; /* Pointer to the conversion buffer */
  17724. int precision; /* Precision of the current field */
  17725. int length; /* Length of the field */
  17726. int idx; /* A general purpose loop counter */
  17727. int width; /* Width of the current field */
  17728. etByte flag_leftjustify; /* True if "-" flag is present */
  17729. etByte flag_plussign; /* True if "+" flag is present */
  17730. etByte flag_blanksign; /* True if " " flag is present */
  17731. etByte flag_alternateform; /* True if "#" flag is present */
  17732. etByte flag_altform2; /* True if "!" flag is present */
  17733. etByte flag_zeropad; /* True if field width constant starts with zero */
  17734. etByte flag_long; /* True if "l" flag is present */
  17735. etByte flag_longlong; /* True if the "ll" flag is present */
  17736. etByte done; /* Loop termination flag */
  17737. sqlite_uint64 longvalue; /* Value for integer types */
  17738. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  17739. const et_info *infop; /* Pointer to the appropriate info structure */
  17740. char buf[etBUFSIZE]; /* Conversion buffer */
  17741. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  17742. etByte xtype = 0; /* Conversion paradigm */
  17743. char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
  17744. #ifndef SQLITE_OMIT_FLOATING_POINT
  17745. int exp, e2; /* exponent of real numbers */
  17746. double rounder; /* Used for rounding floating point values */
  17747. etByte flag_dp; /* True if decimal point should be shown */
  17748. etByte flag_rtz; /* True if trailing zeros should be removed */
  17749. etByte flag_exp; /* True to force display of the exponent */
  17750. int nsd; /* Number of significant digits returned */
  17751. #endif
  17752. length = 0;
  17753. bufpt = 0;
  17754. for(; (c=(*fmt))!=0; ++fmt){
  17755. if( c!='%' ){
  17756. int amt;
  17757. bufpt = (char *)fmt;
  17758. amt = 1;
  17759. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  17760. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  17761. if( c==0 ) break;
  17762. }
  17763. if( (c=(*++fmt))==0 ){
  17764. sqlite3StrAccumAppend(pAccum, "%", 1);
  17765. break;
  17766. }
  17767. /* Find out what flags are present */
  17768. flag_leftjustify = flag_plussign = flag_blanksign =
  17769. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  17770. done = 0;
  17771. do{
  17772. switch( c ){
  17773. case '-': flag_leftjustify = 1; break;
  17774. case '+': flag_plussign = 1; break;
  17775. case ' ': flag_blanksign = 1; break;
  17776. case '#': flag_alternateform = 1; break;
  17777. case '!': flag_altform2 = 1; break;
  17778. case '0': flag_zeropad = 1; break;
  17779. default: done = 1; break;
  17780. }
  17781. }while( !done && (c=(*++fmt))!=0 );
  17782. /* Get the field width */
  17783. width = 0;
  17784. if( c=='*' ){
  17785. width = va_arg(ap,int);
  17786. if( width<0 ){
  17787. flag_leftjustify = 1;
  17788. width = -width;
  17789. }
  17790. c = *++fmt;
  17791. }else{
  17792. while( c>='0' && c<='9' ){
  17793. width = width*10 + c - '0';
  17794. c = *++fmt;
  17795. }
  17796. }
  17797. if( width > etBUFSIZE-10 ){
  17798. width = etBUFSIZE-10;
  17799. }
  17800. /* Get the precision */
  17801. if( c=='.' ){
  17802. precision = 0;
  17803. c = *++fmt;
  17804. if( c=='*' ){
  17805. precision = va_arg(ap,int);
  17806. if( precision<0 ) precision = -precision;
  17807. c = *++fmt;
  17808. }else{
  17809. while( c>='0' && c<='9' ){
  17810. precision = precision*10 + c - '0';
  17811. c = *++fmt;
  17812. }
  17813. }
  17814. }else{
  17815. precision = -1;
  17816. }
  17817. /* Get the conversion type modifier */
  17818. if( c=='l' ){
  17819. flag_long = 1;
  17820. c = *++fmt;
  17821. if( c=='l' ){
  17822. flag_longlong = 1;
  17823. c = *++fmt;
  17824. }else{
  17825. flag_longlong = 0;
  17826. }
  17827. }else{
  17828. flag_long = flag_longlong = 0;
  17829. }
  17830. /* Fetch the info entry for the field */
  17831. infop = &fmtinfo[0];
  17832. xtype = etINVALID;
  17833. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  17834. if( c==fmtinfo[idx].fmttype ){
  17835. infop = &fmtinfo[idx];
  17836. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  17837. xtype = infop->type;
  17838. }else{
  17839. return;
  17840. }
  17841. break;
  17842. }
  17843. }
  17844. zExtra = 0;
  17845. /* Limit the precision to prevent overflowing buf[] during conversion */
  17846. if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
  17847. precision = etBUFSIZE-40;
  17848. }
  17849. /*
  17850. ** At this point, variables are initialized as follows:
  17851. **
  17852. ** flag_alternateform TRUE if a '#' is present.
  17853. ** flag_altform2 TRUE if a '!' is present.
  17854. ** flag_plussign TRUE if a '+' is present.
  17855. ** flag_leftjustify TRUE if a '-' is present or if the
  17856. ** field width was negative.
  17857. ** flag_zeropad TRUE if the width began with 0.
  17858. ** flag_long TRUE if the letter 'l' (ell) prefixed
  17859. ** the conversion character.
  17860. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  17861. ** the conversion character.
  17862. ** flag_blanksign TRUE if a ' ' is present.
  17863. ** width The specified field width. This is
  17864. ** always non-negative. Zero is the default.
  17865. ** precision The specified precision. The default
  17866. ** is -1.
  17867. ** xtype The class of the conversion.
  17868. ** infop Pointer to the appropriate info struct.
  17869. */
  17870. switch( xtype ){
  17871. case etPOINTER:
  17872. flag_longlong = sizeof(char*)==sizeof(i64);
  17873. flag_long = sizeof(char*)==sizeof(long int);
  17874. /* Fall through into the next case */
  17875. case etORDINAL:
  17876. case etRADIX:
  17877. if( infop->flags & FLAG_SIGNED ){
  17878. i64 v;
  17879. if( flag_longlong ){
  17880. v = va_arg(ap,i64);
  17881. }else if( flag_long ){
  17882. v = va_arg(ap,long int);
  17883. }else{
  17884. v = va_arg(ap,int);
  17885. }
  17886. if( v<0 ){
  17887. if( v==SMALLEST_INT64 ){
  17888. longvalue = ((u64)1)<<63;
  17889. }else{
  17890. longvalue = -v;
  17891. }
  17892. prefix = '-';
  17893. }else{
  17894. longvalue = v;
  17895. if( flag_plussign ) prefix = '+';
  17896. else if( flag_blanksign ) prefix = ' ';
  17897. else prefix = 0;
  17898. }
  17899. }else{
  17900. if( flag_longlong ){
  17901. longvalue = va_arg(ap,u64);
  17902. }else if( flag_long ){
  17903. longvalue = va_arg(ap,unsigned long int);
  17904. }else{
  17905. longvalue = va_arg(ap,unsigned int);
  17906. }
  17907. prefix = 0;
  17908. }
  17909. if( longvalue==0 ) flag_alternateform = 0;
  17910. if( flag_zeropad && precision<width-(prefix!=0) ){
  17911. precision = width-(prefix!=0);
  17912. }
  17913. bufpt = &buf[etBUFSIZE-1];
  17914. if( xtype==etORDINAL ){
  17915. static const char zOrd[] = "thstndrd";
  17916. int x = (int)(longvalue % 10);
  17917. if( x>=4 || (longvalue/10)%10==1 ){
  17918. x = 0;
  17919. }
  17920. buf[etBUFSIZE-3] = zOrd[x*2];
  17921. buf[etBUFSIZE-2] = zOrd[x*2+1];
  17922. bufpt -= 2;
  17923. }
  17924. {
  17925. register const char *cset; /* Use registers for speed */
  17926. register int base;
  17927. cset = &aDigits[infop->charset];
  17928. base = infop->base;
  17929. do{ /* Convert to ascii */
  17930. *(--bufpt) = cset[longvalue%base];
  17931. longvalue = longvalue/base;
  17932. }while( longvalue>0 );
  17933. }
  17934. length = (int)(&buf[etBUFSIZE-1]-bufpt);
  17935. for(idx=precision-length; idx>0; idx--){
  17936. *(--bufpt) = '0'; /* Zero pad */
  17937. }
  17938. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  17939. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  17940. const char *pre;
  17941. char x;
  17942. pre = &aPrefix[infop->prefix];
  17943. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  17944. }
  17945. length = (int)(&buf[etBUFSIZE-1]-bufpt);
  17946. break;
  17947. case etFLOAT:
  17948. case etEXP:
  17949. case etGENERIC:
  17950. realvalue = va_arg(ap,double);
  17951. #ifdef SQLITE_OMIT_FLOATING_POINT
  17952. length = 0;
  17953. #else
  17954. if( precision<0 ) precision = 6; /* Set default precision */
  17955. if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
  17956. if( realvalue<0.0 ){
  17957. realvalue = -realvalue;
  17958. prefix = '-';
  17959. }else{
  17960. if( flag_plussign ) prefix = '+';
  17961. else if( flag_blanksign ) prefix = ' ';
  17962. else prefix = 0;
  17963. }
  17964. if( xtype==etGENERIC && precision>0 ) precision--;
  17965. #if 0
  17966. /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
  17967. for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
  17968. #else
  17969. /* It makes more sense to use 0.5 */
  17970. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  17971. #endif
  17972. if( xtype==etFLOAT ) realvalue += rounder;
  17973. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  17974. exp = 0;
  17975. if( sqlite3IsNaN((double)realvalue) ){
  17976. bufpt = "NaN";
  17977. length = 3;
  17978. break;
  17979. }
  17980. if( realvalue>0.0 ){
  17981. while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
  17982. while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
  17983. while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
  17984. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  17985. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  17986. if( exp>350 ){
  17987. if( prefix=='-' ){
  17988. bufpt = "-Inf";
  17989. }else if( prefix=='+' ){
  17990. bufpt = "+Inf";
  17991. }else{
  17992. bufpt = "Inf";
  17993. }
  17994. length = sqlite3Strlen30(bufpt);
  17995. break;
  17996. }
  17997. }
  17998. bufpt = buf;
  17999. /*
  18000. ** If the field type is etGENERIC, then convert to either etEXP
  18001. ** or etFLOAT, as appropriate.
  18002. */
  18003. flag_exp = xtype==etEXP;
  18004. if( xtype!=etFLOAT ){
  18005. realvalue += rounder;
  18006. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  18007. }
  18008. if( xtype==etGENERIC ){
  18009. flag_rtz = !flag_alternateform;
  18010. if( exp<-4 || exp>precision ){
  18011. xtype = etEXP;
  18012. }else{
  18013. precision = precision - exp;
  18014. xtype = etFLOAT;
  18015. }
  18016. }else{
  18017. flag_rtz = 0;
  18018. }
  18019. if( xtype==etEXP ){
  18020. e2 = 0;
  18021. }else{
  18022. e2 = exp;
  18023. }
  18024. nsd = 0;
  18025. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  18026. /* The sign in front of the number */
  18027. if( prefix ){
  18028. *(bufpt++) = prefix;
  18029. }
  18030. /* Digits prior to the decimal point */
  18031. if( e2<0 ){
  18032. *(bufpt++) = '0';
  18033. }else{
  18034. for(; e2>=0; e2--){
  18035. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  18036. }
  18037. }
  18038. /* The decimal point */
  18039. if( flag_dp ){
  18040. *(bufpt++) = '.';
  18041. }
  18042. /* "0" digits after the decimal point but before the first
  18043. ** significant digit of the number */
  18044. for(e2++; e2<0; precision--, e2++){
  18045. assert( precision>0 );
  18046. *(bufpt++) = '0';
  18047. }
  18048. /* Significant digits after the decimal point */
  18049. while( (precision--)>0 ){
  18050. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  18051. }
  18052. /* Remove trailing zeros and the "." if no digits follow the "." */
  18053. if( flag_rtz && flag_dp ){
  18054. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  18055. assert( bufpt>buf );
  18056. if( bufpt[-1]=='.' ){
  18057. if( flag_altform2 ){
  18058. *(bufpt++) = '0';
  18059. }else{
  18060. *(--bufpt) = 0;
  18061. }
  18062. }
  18063. }
  18064. /* Add the "eNNN" suffix */
  18065. if( flag_exp || xtype==etEXP ){
  18066. *(bufpt++) = aDigits[infop->charset];
  18067. if( exp<0 ){
  18068. *(bufpt++) = '-'; exp = -exp;
  18069. }else{
  18070. *(bufpt++) = '+';
  18071. }
  18072. if( exp>=100 ){
  18073. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  18074. exp %= 100;
  18075. }
  18076. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  18077. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  18078. }
  18079. *bufpt = 0;
  18080. /* The converted number is in buf[] and zero terminated. Output it.
  18081. ** Note that the number is in the usual order, not reversed as with
  18082. ** integer conversions. */
  18083. length = (int)(bufpt-buf);
  18084. bufpt = buf;
  18085. /* Special case: Add leading zeros if the flag_zeropad flag is
  18086. ** set and we are not left justified */
  18087. if( flag_zeropad && !flag_leftjustify && length < width){
  18088. int i;
  18089. int nPad = width - length;
  18090. for(i=width; i>=nPad; i--){
  18091. bufpt[i] = bufpt[i-nPad];
  18092. }
  18093. i = prefix!=0;
  18094. while( nPad-- ) bufpt[i++] = '0';
  18095. length = width;
  18096. }
  18097. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  18098. break;
  18099. case etSIZE:
  18100. *(va_arg(ap,int*)) = pAccum->nChar;
  18101. length = width = 0;
  18102. break;
  18103. case etPERCENT:
  18104. buf[0] = '%';
  18105. bufpt = buf;
  18106. length = 1;
  18107. break;
  18108. case etCHARX:
  18109. c = va_arg(ap,int);
  18110. buf[0] = (char)c;
  18111. if( precision>=0 ){
  18112. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  18113. length = precision;
  18114. }else{
  18115. length =1;
  18116. }
  18117. bufpt = buf;
  18118. break;
  18119. case etSTRING:
  18120. case etDYNSTRING:
  18121. bufpt = va_arg(ap,char*);
  18122. if( bufpt==0 ){
  18123. bufpt = "";
  18124. }else if( xtype==etDYNSTRING ){
  18125. zExtra = bufpt;
  18126. }
  18127. if( precision>=0 ){
  18128. for(length=0; length<precision && bufpt[length]; length++){}
  18129. }else{
  18130. length = sqlite3Strlen30(bufpt);
  18131. }
  18132. break;
  18133. case etSQLESCAPE:
  18134. case etSQLESCAPE2:
  18135. case etSQLESCAPE3: {
  18136. int i, j, k, n, isnull;
  18137. int needQuote;
  18138. char ch;
  18139. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  18140. char *escarg = va_arg(ap,char*);
  18141. isnull = escarg==0;
  18142. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  18143. k = precision;
  18144. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  18145. if( ch==q ) n++;
  18146. }
  18147. needQuote = !isnull && xtype==etSQLESCAPE2;
  18148. n += i + 1 + needQuote*2;
  18149. if( n>etBUFSIZE ){
  18150. bufpt = zExtra = sqlite3Malloc( n );
  18151. if( bufpt==0 ){
  18152. pAccum->mallocFailed = 1;
  18153. return;
  18154. }
  18155. }else{
  18156. bufpt = buf;
  18157. }
  18158. j = 0;
  18159. if( needQuote ) bufpt[j++] = q;
  18160. k = i;
  18161. for(i=0; i<k; i++){
  18162. bufpt[j++] = ch = escarg[i];
  18163. if( ch==q ) bufpt[j++] = ch;
  18164. }
  18165. if( needQuote ) bufpt[j++] = q;
  18166. bufpt[j] = 0;
  18167. length = j;
  18168. /* The precision in %q and %Q means how many input characters to
  18169. ** consume, not the length of the output...
  18170. ** if( precision>=0 && precision<length ) length = precision; */
  18171. break;
  18172. }
  18173. case etTOKEN: {
  18174. Token *pToken = va_arg(ap, Token*);
  18175. if( pToken ){
  18176. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  18177. }
  18178. length = width = 0;
  18179. break;
  18180. }
  18181. case etSRCLIST: {
  18182. SrcList *pSrc = va_arg(ap, SrcList*);
  18183. int k = va_arg(ap, int);
  18184. struct SrcList_item *pItem = &pSrc->a[k];
  18185. assert( k>=0 && k<pSrc->nSrc );
  18186. if( pItem->zDatabase ){
  18187. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  18188. sqlite3StrAccumAppend(pAccum, ".", 1);
  18189. }
  18190. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  18191. length = width = 0;
  18192. break;
  18193. }
  18194. default: {
  18195. assert( xtype==etINVALID );
  18196. return;
  18197. }
  18198. }/* End switch over the format type */
  18199. /*
  18200. ** The text of the conversion is pointed to by "bufpt" and is
  18201. ** "length" characters long. The field width is "width". Do
  18202. ** the output.
  18203. */
  18204. if( !flag_leftjustify ){
  18205. register int nspace;
  18206. nspace = width-length;
  18207. if( nspace>0 ){
  18208. appendSpace(pAccum, nspace);
  18209. }
  18210. }
  18211. if( length>0 ){
  18212. sqlite3StrAccumAppend(pAccum, bufpt, length);
  18213. }
  18214. if( flag_leftjustify ){
  18215. register int nspace;
  18216. nspace = width-length;
  18217. if( nspace>0 ){
  18218. appendSpace(pAccum, nspace);
  18219. }
  18220. }
  18221. if( zExtra ){
  18222. sqlite3_free(zExtra);
  18223. }
  18224. }/* End for loop over the format string */
  18225. } /* End of function */
  18226. /*
  18227. ** Append N bytes of text from z to the StrAccum object.
  18228. */
  18229. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  18230. assert( z!=0 || N==0 );
  18231. if( p->tooBig | p->mallocFailed ){
  18232. testcase(p->tooBig);
  18233. testcase(p->mallocFailed);
  18234. return;
  18235. }
  18236. if( N<0 ){
  18237. N = sqlite3Strlen30(z);
  18238. }
  18239. if( N==0 || NEVER(z==0) ){
  18240. return;
  18241. }
  18242. if( p->nChar+N >= p->nAlloc ){
  18243. char *zNew;
  18244. if( !p->useMalloc ){
  18245. p->tooBig = 1;
  18246. N = p->nAlloc - p->nChar - 1;
  18247. if( N<=0 ){
  18248. return;
  18249. }
  18250. }else{
  18251. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  18252. i64 szNew = p->nChar;
  18253. szNew += N + 1;
  18254. if( szNew > p->mxAlloc ){
  18255. sqlite3StrAccumReset(p);
  18256. p->tooBig = 1;
  18257. return;
  18258. }else{
  18259. p->nAlloc = (int)szNew;
  18260. }
  18261. if( p->useMalloc==1 ){
  18262. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  18263. }else{
  18264. zNew = sqlite3_realloc(zOld, p->nAlloc);
  18265. }
  18266. if( zNew ){
  18267. if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
  18268. p->zText = zNew;
  18269. }else{
  18270. p->mallocFailed = 1;
  18271. sqlite3StrAccumReset(p);
  18272. return;
  18273. }
  18274. }
  18275. }
  18276. memcpy(&p->zText[p->nChar], z, N);
  18277. p->nChar += N;
  18278. }
  18279. /*
  18280. ** Finish off a string by making sure it is zero-terminated.
  18281. ** Return a pointer to the resulting string. Return a NULL
  18282. ** pointer if any kind of error was encountered.
  18283. */
  18284. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  18285. if( p->zText ){
  18286. p->zText[p->nChar] = 0;
  18287. if( p->useMalloc && p->zText==p->zBase ){
  18288. if( p->useMalloc==1 ){
  18289. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  18290. }else{
  18291. p->zText = sqlite3_malloc(p->nChar+1);
  18292. }
  18293. if( p->zText ){
  18294. memcpy(p->zText, p->zBase, p->nChar+1);
  18295. }else{
  18296. p->mallocFailed = 1;
  18297. }
  18298. }
  18299. }
  18300. return p->zText;
  18301. }
  18302. /*
  18303. ** Reset an StrAccum string. Reclaim all malloced memory.
  18304. */
  18305. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  18306. if( p->zText!=p->zBase ){
  18307. if( p->useMalloc==1 ){
  18308. sqlite3DbFree(p->db, p->zText);
  18309. }else{
  18310. sqlite3_free(p->zText);
  18311. }
  18312. }
  18313. p->zText = 0;
  18314. }
  18315. /*
  18316. ** Initialize a string accumulator
  18317. */
  18318. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  18319. p->zText = p->zBase = zBase;
  18320. p->db = 0;
  18321. p->nChar = 0;
  18322. p->nAlloc = n;
  18323. p->mxAlloc = mx;
  18324. p->useMalloc = 1;
  18325. p->tooBig = 0;
  18326. p->mallocFailed = 0;
  18327. }
  18328. /*
  18329. ** Print into memory obtained from sqliteMalloc(). Use the internal
  18330. ** %-conversion extensions.
  18331. */
  18332. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  18333. char *z;
  18334. char zBase[SQLITE_PRINT_BUF_SIZE];
  18335. StrAccum acc;
  18336. assert( db!=0 );
  18337. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  18338. db->aLimit[SQLITE_LIMIT_LENGTH]);
  18339. acc.db = db;
  18340. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  18341. z = sqlite3StrAccumFinish(&acc);
  18342. if( acc.mallocFailed ){
  18343. db->mallocFailed = 1;
  18344. }
  18345. return z;
  18346. }
  18347. /*
  18348. ** Print into memory obtained from sqliteMalloc(). Use the internal
  18349. ** %-conversion extensions.
  18350. */
  18351. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  18352. va_list ap;
  18353. char *z;
  18354. va_start(ap, zFormat);
  18355. z = sqlite3VMPrintf(db, zFormat, ap);
  18356. va_end(ap);
  18357. return z;
  18358. }
  18359. /*
  18360. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  18361. ** the string and before returnning. This routine is intended to be used
  18362. ** to modify an existing string. For example:
  18363. **
  18364. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  18365. **
  18366. */
  18367. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  18368. va_list ap;
  18369. char *z;
  18370. va_start(ap, zFormat);
  18371. z = sqlite3VMPrintf(db, zFormat, ap);
  18372. va_end(ap);
  18373. sqlite3DbFree(db, zStr);
  18374. return z;
  18375. }
  18376. /*
  18377. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  18378. ** %-conversion extensions.
  18379. */
  18380. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  18381. char *z;
  18382. char zBase[SQLITE_PRINT_BUF_SIZE];
  18383. StrAccum acc;
  18384. #ifndef SQLITE_OMIT_AUTOINIT
  18385. if( sqlite3_initialize() ) return 0;
  18386. #endif
  18387. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  18388. acc.useMalloc = 2;
  18389. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  18390. z = sqlite3StrAccumFinish(&acc);
  18391. return z;
  18392. }
  18393. /*
  18394. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  18395. ** %-conversion extensions.
  18396. */
  18397. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  18398. va_list ap;
  18399. char *z;
  18400. #ifndef SQLITE_OMIT_AUTOINIT
  18401. if( sqlite3_initialize() ) return 0;
  18402. #endif
  18403. va_start(ap, zFormat);
  18404. z = sqlite3_vmprintf(zFormat, ap);
  18405. va_end(ap);
  18406. return z;
  18407. }
  18408. /*
  18409. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  18410. ** current locale settings. This is important for SQLite because we
  18411. ** are not able to use a "," as the decimal point in place of "." as
  18412. ** specified by some locales.
  18413. **
  18414. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  18415. ** from the snprintf() standard. Unfortunately, it is too late to change
  18416. ** this without breaking compatibility, so we just have to live with the
  18417. ** mistake.
  18418. **
  18419. ** sqlite3_vsnprintf() is the varargs version.
  18420. */
  18421. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  18422. StrAccum acc;
  18423. if( n<=0 ) return zBuf;
  18424. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  18425. acc.useMalloc = 0;
  18426. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  18427. return sqlite3StrAccumFinish(&acc);
  18428. }
  18429. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  18430. char *z;
  18431. va_list ap;
  18432. va_start(ap,zFormat);
  18433. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  18434. va_end(ap);
  18435. return z;
  18436. }
  18437. /*
  18438. ** This is the routine that actually formats the sqlite3_log() message.
  18439. ** We house it in a separate routine from sqlite3_log() to avoid using
  18440. ** stack space on small-stack systems when logging is disabled.
  18441. **
  18442. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  18443. ** allocate memory because it might be called while the memory allocator
  18444. ** mutex is held.
  18445. */
  18446. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  18447. StrAccum acc; /* String accumulator */
  18448. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  18449. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  18450. acc.useMalloc = 0;
  18451. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  18452. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  18453. sqlite3StrAccumFinish(&acc));
  18454. }
  18455. /*
  18456. ** Format and write a message to the log if logging is enabled.
  18457. */
  18458. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  18459. va_list ap; /* Vararg list */
  18460. if( sqlite3GlobalConfig.xLog ){
  18461. va_start(ap, zFormat);
  18462. renderLogMsg(iErrCode, zFormat, ap);
  18463. va_end(ap);
  18464. }
  18465. }
  18466. #if defined(SQLITE_DEBUG)
  18467. /*
  18468. ** A version of printf() that understands %lld. Used for debugging.
  18469. ** The printf() built into some versions of windows does not understand %lld
  18470. ** and segfaults if you give it a long long int.
  18471. */
  18472. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  18473. va_list ap;
  18474. StrAccum acc;
  18475. char zBuf[500];
  18476. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  18477. acc.useMalloc = 0;
  18478. va_start(ap,zFormat);
  18479. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  18480. va_end(ap);
  18481. sqlite3StrAccumFinish(&acc);
  18482. fprintf(stdout,"%s", zBuf);
  18483. fflush(stdout);
  18484. }
  18485. #endif
  18486. #ifndef SQLITE_OMIT_TRACE
  18487. /*
  18488. ** variable-argument wrapper around sqlite3VXPrintf().
  18489. */
  18490. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  18491. va_list ap;
  18492. va_start(ap,zFormat);
  18493. sqlite3VXPrintf(p, 1, zFormat, ap);
  18494. va_end(ap);
  18495. }
  18496. #endif
  18497. /************** End of printf.c **********************************************/
  18498. /************** Begin file random.c ******************************************/
  18499. /*
  18500. ** 2001 September 15
  18501. **
  18502. ** The author disclaims copyright to this source code. In place of
  18503. ** a legal notice, here is a blessing:
  18504. **
  18505. ** May you do good and not evil.
  18506. ** May you find forgiveness for yourself and forgive others.
  18507. ** May you share freely, never taking more than you give.
  18508. **
  18509. *************************************************************************
  18510. ** This file contains code to implement a pseudo-random number
  18511. ** generator (PRNG) for SQLite.
  18512. **
  18513. ** Random numbers are used by some of the database backends in order
  18514. ** to generate random integer keys for tables or random filenames.
  18515. */
  18516. /* All threads share a single random number generator.
  18517. ** This structure is the current state of the generator.
  18518. */
  18519. static SQLITE_WSD struct sqlite3PrngType {
  18520. unsigned char isInit; /* True if initialized */
  18521. unsigned char i, j; /* State variables */
  18522. unsigned char s[256]; /* State variables */
  18523. } sqlite3Prng;
  18524. /*
  18525. ** Get a single 8-bit random value from the RC4 PRNG. The Mutex
  18526. ** must be held while executing this routine.
  18527. **
  18528. ** Why not just use a library random generator like lrand48() for this?
  18529. ** Because the OP_NewRowid opcode in the VDBE depends on having a very
  18530. ** good source of random numbers. The lrand48() library function may
  18531. ** well be good enough. But maybe not. Or maybe lrand48() has some
  18532. ** subtle problems on some systems that could cause problems. It is hard
  18533. ** to know. To minimize the risk of problems due to bad lrand48()
  18534. ** implementations, SQLite uses this random number generator based
  18535. ** on RC4, which we know works very well.
  18536. **
  18537. ** (Later): Actually, OP_NewRowid does not depend on a good source of
  18538. ** randomness any more. But we will leave this code in all the same.
  18539. */
  18540. static u8 randomByte(void){
  18541. unsigned char t;
  18542. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  18543. ** state vector. If writable static data is unsupported on the target,
  18544. ** we have to locate the state vector at run-time. In the more common
  18545. ** case where writable static data is supported, wsdPrng can refer directly
  18546. ** to the "sqlite3Prng" state vector declared above.
  18547. */
  18548. #ifdef SQLITE_OMIT_WSD
  18549. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  18550. # define wsdPrng p[0]
  18551. #else
  18552. # define wsdPrng sqlite3Prng
  18553. #endif
  18554. /* Initialize the state of the random number generator once,
  18555. ** the first time this routine is called. The seed value does
  18556. ** not need to contain a lot of randomness since we are not
  18557. ** trying to do secure encryption or anything like that...
  18558. **
  18559. ** Nothing in this file or anywhere else in SQLite does any kind of
  18560. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  18561. ** number generator) not as an encryption device.
  18562. */
  18563. if( !wsdPrng.isInit ){
  18564. int i;
  18565. char k[256];
  18566. wsdPrng.j = 0;
  18567. wsdPrng.i = 0;
  18568. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  18569. for(i=0; i<256; i++){
  18570. wsdPrng.s[i] = (u8)i;
  18571. }
  18572. for(i=0; i<256; i++){
  18573. wsdPrng.j += wsdPrng.s[i] + k[i];
  18574. t = wsdPrng.s[wsdPrng.j];
  18575. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  18576. wsdPrng.s[i] = t;
  18577. }
  18578. wsdPrng.isInit = 1;
  18579. }
  18580. /* Generate and return single random byte
  18581. */
  18582. wsdPrng.i++;
  18583. t = wsdPrng.s[wsdPrng.i];
  18584. wsdPrng.j += t;
  18585. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  18586. wsdPrng.s[wsdPrng.j] = t;
  18587. t += wsdPrng.s[wsdPrng.i];
  18588. return wsdPrng.s[t];
  18589. }
  18590. /*
  18591. ** Return N random bytes.
  18592. */
  18593. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  18594. unsigned char *zBuf = pBuf;
  18595. #if SQLITE_THREADSAFE
  18596. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  18597. #endif
  18598. sqlite3_mutex_enter(mutex);
  18599. while( N-- ){
  18600. *(zBuf++) = randomByte();
  18601. }
  18602. sqlite3_mutex_leave(mutex);
  18603. }
  18604. #ifndef SQLITE_OMIT_BUILTIN_TEST
  18605. /*
  18606. ** For testing purposes, we sometimes want to preserve the state of
  18607. ** PRNG and restore the PRNG to its saved state at a later time, or
  18608. ** to reset the PRNG to its initial state. These routines accomplish
  18609. ** those tasks.
  18610. **
  18611. ** The sqlite3_test_control() interface calls these routines to
  18612. ** control the PRNG.
  18613. */
  18614. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  18615. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  18616. memcpy(
  18617. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  18618. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  18619. sizeof(sqlite3Prng)
  18620. );
  18621. }
  18622. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  18623. memcpy(
  18624. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  18625. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  18626. sizeof(sqlite3Prng)
  18627. );
  18628. }
  18629. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  18630. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  18631. }
  18632. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  18633. /************** End of random.c **********************************************/
  18634. /************** Begin file utf.c *********************************************/
  18635. /*
  18636. ** 2004 April 13
  18637. **
  18638. ** The author disclaims copyright to this source code. In place of
  18639. ** a legal notice, here is a blessing:
  18640. **
  18641. ** May you do good and not evil.
  18642. ** May you find forgiveness for yourself and forgive others.
  18643. ** May you share freely, never taking more than you give.
  18644. **
  18645. *************************************************************************
  18646. ** This file contains routines used to translate between UTF-8,
  18647. ** UTF-16, UTF-16BE, and UTF-16LE.
  18648. **
  18649. ** Notes on UTF-8:
  18650. **
  18651. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  18652. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  18653. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  18654. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  18655. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  18656. **
  18657. **
  18658. ** Notes on UTF-16: (with wwww+1==uuuuu)
  18659. **
  18660. ** Word-0 Word-1 Value
  18661. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  18662. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  18663. **
  18664. **
  18665. ** BOM or Byte Order Mark:
  18666. ** 0xff 0xfe little-endian utf-16 follows
  18667. ** 0xfe 0xff big-endian utf-16 follows
  18668. **
  18669. */
  18670. #ifndef SQLITE_AMALGAMATION
  18671. /*
  18672. ** The following constant value is used by the SQLITE_BIGENDIAN and
  18673. ** SQLITE_LITTLEENDIAN macros.
  18674. */
  18675. SQLITE_PRIVATE const int sqlite3one = 1;
  18676. #endif /* SQLITE_AMALGAMATION */
  18677. /*
  18678. ** This lookup table is used to help decode the first byte of
  18679. ** a multi-byte UTF8 character.
  18680. */
  18681. static const unsigned char sqlite3Utf8Trans1[] = {
  18682. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  18683. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  18684. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  18685. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  18686. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  18687. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  18688. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  18689. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  18690. };
  18691. #define WRITE_UTF8(zOut, c) { \
  18692. if( c<0x00080 ){ \
  18693. *zOut++ = (u8)(c&0xFF); \
  18694. } \
  18695. else if( c<0x00800 ){ \
  18696. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  18697. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  18698. } \
  18699. else if( c<0x10000 ){ \
  18700. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  18701. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  18702. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  18703. }else{ \
  18704. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  18705. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  18706. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  18707. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  18708. } \
  18709. }
  18710. #define WRITE_UTF16LE(zOut, c) { \
  18711. if( c<=0xFFFF ){ \
  18712. *zOut++ = (u8)(c&0x00FF); \
  18713. *zOut++ = (u8)((c>>8)&0x00FF); \
  18714. }else{ \
  18715. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  18716. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  18717. *zOut++ = (u8)(c&0x00FF); \
  18718. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  18719. } \
  18720. }
  18721. #define WRITE_UTF16BE(zOut, c) { \
  18722. if( c<=0xFFFF ){ \
  18723. *zOut++ = (u8)((c>>8)&0x00FF); \
  18724. *zOut++ = (u8)(c&0x00FF); \
  18725. }else{ \
  18726. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  18727. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  18728. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  18729. *zOut++ = (u8)(c&0x00FF); \
  18730. } \
  18731. }
  18732. #define READ_UTF16LE(zIn, TERM, c){ \
  18733. c = (*zIn++); \
  18734. c += ((*zIn++)<<8); \
  18735. if( c>=0xD800 && c<0xE000 && TERM ){ \
  18736. int c2 = (*zIn++); \
  18737. c2 += ((*zIn++)<<8); \
  18738. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  18739. } \
  18740. }
  18741. #define READ_UTF16BE(zIn, TERM, c){ \
  18742. c = ((*zIn++)<<8); \
  18743. c += (*zIn++); \
  18744. if( c>=0xD800 && c<0xE000 && TERM ){ \
  18745. int c2 = ((*zIn++)<<8); \
  18746. c2 += (*zIn++); \
  18747. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  18748. } \
  18749. }
  18750. /*
  18751. ** Translate a single UTF-8 character. Return the unicode value.
  18752. **
  18753. ** During translation, assume that the byte that zTerm points
  18754. ** is a 0x00.
  18755. **
  18756. ** Write a pointer to the next unread byte back into *pzNext.
  18757. **
  18758. ** Notes On Invalid UTF-8:
  18759. **
  18760. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  18761. ** be encoded as a multi-byte character. Any multi-byte character that
  18762. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  18763. **
  18764. ** * This routine never allows a UTF16 surrogate value to be encoded.
  18765. ** If a multi-byte character attempts to encode a value between
  18766. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  18767. **
  18768. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  18769. ** byte of a character are interpreted as single-byte characters
  18770. ** and rendered as themselves even though they are technically
  18771. ** invalid characters.
  18772. **
  18773. ** * This routine accepts an infinite number of different UTF8 encodings
  18774. ** for unicode values 0x80 and greater. It do not change over-length
  18775. ** encodings to 0xfffd as some systems recommend.
  18776. */
  18777. #define READ_UTF8(zIn, zTerm, c) \
  18778. c = *(zIn++); \
  18779. if( c>=0xc0 ){ \
  18780. c = sqlite3Utf8Trans1[c-0xc0]; \
  18781. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  18782. c = (c<<6) + (0x3f & *(zIn++)); \
  18783. } \
  18784. if( c<0x80 \
  18785. || (c&0xFFFFF800)==0xD800 \
  18786. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  18787. }
  18788. SQLITE_PRIVATE int sqlite3Utf8Read(
  18789. const unsigned char *zIn, /* First byte of UTF-8 character */
  18790. const unsigned char **pzNext /* Write first byte past UTF-8 char here */
  18791. ){
  18792. unsigned int c;
  18793. /* Same as READ_UTF8() above but without the zTerm parameter.
  18794. ** For this routine, we assume the UTF8 string is always zero-terminated.
  18795. */
  18796. c = *(zIn++);
  18797. if( c>=0xc0 ){
  18798. c = sqlite3Utf8Trans1[c-0xc0];
  18799. while( (*zIn & 0xc0)==0x80 ){
  18800. c = (c<<6) + (0x3f & *(zIn++));
  18801. }
  18802. if( c<0x80
  18803. || (c&0xFFFFF800)==0xD800
  18804. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  18805. }
  18806. *pzNext = zIn;
  18807. return c;
  18808. }
  18809. /*
  18810. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  18811. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  18812. */
  18813. /* #define TRANSLATE_TRACE 1 */
  18814. #ifndef SQLITE_OMIT_UTF16
  18815. /*
  18816. ** This routine transforms the internal text encoding used by pMem to
  18817. ** desiredEnc. It is an error if the string is already of the desired
  18818. ** encoding, or if *pMem does not contain a string value.
  18819. */
  18820. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  18821. int len; /* Maximum length of output string in bytes */
  18822. unsigned char *zOut; /* Output buffer */
  18823. unsigned char *zIn; /* Input iterator */
  18824. unsigned char *zTerm; /* End of input */
  18825. unsigned char *z; /* Output iterator */
  18826. unsigned int c;
  18827. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  18828. assert( pMem->flags&MEM_Str );
  18829. assert( pMem->enc!=desiredEnc );
  18830. assert( pMem->enc!=0 );
  18831. assert( pMem->n>=0 );
  18832. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  18833. {
  18834. char zBuf[100];
  18835. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  18836. fprintf(stderr, "INPUT: %s\n", zBuf);
  18837. }
  18838. #endif
  18839. /* If the translation is between UTF-16 little and big endian, then
  18840. ** all that is required is to swap the byte order. This case is handled
  18841. ** differently from the others.
  18842. */
  18843. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  18844. u8 temp;
  18845. int rc;
  18846. rc = sqlite3VdbeMemMakeWriteable(pMem);
  18847. if( rc!=SQLITE_OK ){
  18848. assert( rc==SQLITE_NOMEM );
  18849. return SQLITE_NOMEM;
  18850. }
  18851. zIn = (u8*)pMem->z;
  18852. zTerm = &zIn[pMem->n&~1];
  18853. while( zIn<zTerm ){
  18854. temp = *zIn;
  18855. *zIn = *(zIn+1);
  18856. zIn++;
  18857. *zIn++ = temp;
  18858. }
  18859. pMem->enc = desiredEnc;
  18860. goto translate_out;
  18861. }
  18862. /* Set len to the maximum number of bytes required in the output buffer. */
  18863. if( desiredEnc==SQLITE_UTF8 ){
  18864. /* When converting from UTF-16, the maximum growth results from
  18865. ** translating a 2-byte character to a 4-byte UTF-8 character.
  18866. ** A single byte is required for the output string
  18867. ** nul-terminator.
  18868. */
  18869. pMem->n &= ~1;
  18870. len = pMem->n * 2 + 1;
  18871. }else{
  18872. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  18873. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  18874. ** character. Two bytes are required in the output buffer for the
  18875. ** nul-terminator.
  18876. */
  18877. len = pMem->n * 2 + 2;
  18878. }
  18879. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  18880. ** byte past the end.
  18881. **
  18882. ** Variable zOut is set to point at the output buffer, space obtained
  18883. ** from sqlite3_malloc().
  18884. */
  18885. zIn = (u8*)pMem->z;
  18886. zTerm = &zIn[pMem->n];
  18887. zOut = sqlite3DbMallocRaw(pMem->db, len);
  18888. if( !zOut ){
  18889. return SQLITE_NOMEM;
  18890. }
  18891. z = zOut;
  18892. if( pMem->enc==SQLITE_UTF8 ){
  18893. if( desiredEnc==SQLITE_UTF16LE ){
  18894. /* UTF-8 -> UTF-16 Little-endian */
  18895. while( zIn<zTerm ){
  18896. /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
  18897. READ_UTF8(zIn, zTerm, c);
  18898. WRITE_UTF16LE(z, c);
  18899. }
  18900. }else{
  18901. assert( desiredEnc==SQLITE_UTF16BE );
  18902. /* UTF-8 -> UTF-16 Big-endian */
  18903. while( zIn<zTerm ){
  18904. /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
  18905. READ_UTF8(zIn, zTerm, c);
  18906. WRITE_UTF16BE(z, c);
  18907. }
  18908. }
  18909. pMem->n = (int)(z - zOut);
  18910. *z++ = 0;
  18911. }else{
  18912. assert( desiredEnc==SQLITE_UTF8 );
  18913. if( pMem->enc==SQLITE_UTF16LE ){
  18914. /* UTF-16 Little-endian -> UTF-8 */
  18915. while( zIn<zTerm ){
  18916. READ_UTF16LE(zIn, zIn<zTerm, c);
  18917. WRITE_UTF8(z, c);
  18918. }
  18919. }else{
  18920. /* UTF-16 Big-endian -> UTF-8 */
  18921. while( zIn<zTerm ){
  18922. READ_UTF16BE(zIn, zIn<zTerm, c);
  18923. WRITE_UTF8(z, c);
  18924. }
  18925. }
  18926. pMem->n = (int)(z - zOut);
  18927. }
  18928. *z = 0;
  18929. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  18930. sqlite3VdbeMemRelease(pMem);
  18931. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  18932. pMem->enc = desiredEnc;
  18933. pMem->flags |= (MEM_Term|MEM_Dyn);
  18934. pMem->z = (char*)zOut;
  18935. pMem->zMalloc = pMem->z;
  18936. translate_out:
  18937. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  18938. {
  18939. char zBuf[100];
  18940. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  18941. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  18942. }
  18943. #endif
  18944. return SQLITE_OK;
  18945. }
  18946. /*
  18947. ** This routine checks for a byte-order mark at the beginning of the
  18948. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  18949. ** the encoding of the Mem adjusted. This routine does not do any
  18950. ** byte-swapping, it just sets Mem.enc appropriately.
  18951. **
  18952. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  18953. ** changed by this function.
  18954. */
  18955. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  18956. int rc = SQLITE_OK;
  18957. u8 bom = 0;
  18958. assert( pMem->n>=0 );
  18959. if( pMem->n>1 ){
  18960. u8 b1 = *(u8 *)pMem->z;
  18961. u8 b2 = *(((u8 *)pMem->z) + 1);
  18962. if( b1==0xFE && b2==0xFF ){
  18963. bom = SQLITE_UTF16BE;
  18964. }
  18965. if( b1==0xFF && b2==0xFE ){
  18966. bom = SQLITE_UTF16LE;
  18967. }
  18968. }
  18969. if( bom ){
  18970. rc = sqlite3VdbeMemMakeWriteable(pMem);
  18971. if( rc==SQLITE_OK ){
  18972. pMem->n -= 2;
  18973. memmove(pMem->z, &pMem->z[2], pMem->n);
  18974. pMem->z[pMem->n] = '\0';
  18975. pMem->z[pMem->n+1] = '\0';
  18976. pMem->flags |= MEM_Term;
  18977. pMem->enc = bom;
  18978. }
  18979. }
  18980. return rc;
  18981. }
  18982. #endif /* SQLITE_OMIT_UTF16 */
  18983. /*
  18984. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  18985. ** return the number of unicode characters in pZ up to (but not including)
  18986. ** the first 0x00 byte. If nByte is not less than zero, return the
  18987. ** number of unicode characters in the first nByte of pZ (or up to
  18988. ** the first 0x00, whichever comes first).
  18989. */
  18990. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  18991. int r = 0;
  18992. const u8 *z = (const u8*)zIn;
  18993. const u8 *zTerm;
  18994. if( nByte>=0 ){
  18995. zTerm = &z[nByte];
  18996. }else{
  18997. zTerm = (const u8*)(-1);
  18998. }
  18999. assert( z<=zTerm );
  19000. while( *z!=0 && z<zTerm ){
  19001. SQLITE_SKIP_UTF8(z);
  19002. r++;
  19003. }
  19004. return r;
  19005. }
  19006. /* This test function is not currently used by the automated test-suite.
  19007. ** Hence it is only available in debug builds.
  19008. */
  19009. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  19010. /*
  19011. ** Translate UTF-8 to UTF-8.
  19012. **
  19013. ** This has the effect of making sure that the string is well-formed
  19014. ** UTF-8. Miscoded characters are removed.
  19015. **
  19016. ** The translation is done in-place and aborted if the output
  19017. ** overruns the input.
  19018. */
  19019. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  19020. unsigned char *zOut = zIn;
  19021. unsigned char *zStart = zIn;
  19022. u32 c;
  19023. while( zIn[0] && zOut<=zIn ){
  19024. c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
  19025. if( c!=0xfffd ){
  19026. WRITE_UTF8(zOut, c);
  19027. }
  19028. }
  19029. *zOut = 0;
  19030. return (int)(zOut - zStart);
  19031. }
  19032. #endif
  19033. #ifndef SQLITE_OMIT_UTF16
  19034. /*
  19035. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  19036. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  19037. ** be freed by the calling function.
  19038. **
  19039. ** NULL is returned if there is an allocation error.
  19040. */
  19041. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  19042. Mem m;
  19043. memset(&m, 0, sizeof(m));
  19044. m.db = db;
  19045. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  19046. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  19047. if( db->mallocFailed ){
  19048. sqlite3VdbeMemRelease(&m);
  19049. m.z = 0;
  19050. }
  19051. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  19052. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  19053. assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
  19054. assert( m.z || db->mallocFailed );
  19055. return m.z;
  19056. }
  19057. /*
  19058. ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
  19059. ** enc. A pointer to the new string is returned, and the value of *pnOut
  19060. ** is set to the length of the returned string in bytes. The call should
  19061. ** arrange to call sqlite3DbFree() on the returned pointer when it is
  19062. ** no longer required.
  19063. **
  19064. ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
  19065. ** flag set.
  19066. */
  19067. #ifdef SQLITE_ENABLE_STAT2
  19068. SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
  19069. Mem m;
  19070. memset(&m, 0, sizeof(m));
  19071. m.db = db;
  19072. sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
  19073. if( sqlite3VdbeMemTranslate(&m, enc) ){
  19074. assert( db->mallocFailed );
  19075. return 0;
  19076. }
  19077. assert( m.z==m.zMalloc );
  19078. *pnOut = m.n;
  19079. return m.z;
  19080. }
  19081. #endif
  19082. /*
  19083. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  19084. ** Return the number of bytes in the first nChar unicode characters
  19085. ** in pZ. nChar must be non-negative.
  19086. */
  19087. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  19088. int c;
  19089. unsigned char const *z = zIn;
  19090. int n = 0;
  19091. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  19092. while( n<nChar ){
  19093. READ_UTF16BE(z, 1, c);
  19094. n++;
  19095. }
  19096. }else{
  19097. while( n<nChar ){
  19098. READ_UTF16LE(z, 1, c);
  19099. n++;
  19100. }
  19101. }
  19102. return (int)(z-(unsigned char const *)zIn);
  19103. }
  19104. #if defined(SQLITE_TEST)
  19105. /*
  19106. ** This routine is called from the TCL test function "translate_selftest".
  19107. ** It checks that the primitives for serializing and deserializing
  19108. ** characters in each encoding are inverses of each other.
  19109. */
  19110. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  19111. unsigned int i, t;
  19112. unsigned char zBuf[20];
  19113. unsigned char *z;
  19114. int n;
  19115. unsigned int c;
  19116. for(i=0; i<0x00110000; i++){
  19117. z = zBuf;
  19118. WRITE_UTF8(z, i);
  19119. n = (int)(z-zBuf);
  19120. assert( n>0 && n<=4 );
  19121. z[0] = 0;
  19122. z = zBuf;
  19123. c = sqlite3Utf8Read(z, (const u8**)&z);
  19124. t = i;
  19125. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  19126. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  19127. assert( c==t );
  19128. assert( (z-zBuf)==n );
  19129. }
  19130. for(i=0; i<0x00110000; i++){
  19131. if( i>=0xD800 && i<0xE000 ) continue;
  19132. z = zBuf;
  19133. WRITE_UTF16LE(z, i);
  19134. n = (int)(z-zBuf);
  19135. assert( n>0 && n<=4 );
  19136. z[0] = 0;
  19137. z = zBuf;
  19138. READ_UTF16LE(z, 1, c);
  19139. assert( c==i );
  19140. assert( (z-zBuf)==n );
  19141. }
  19142. for(i=0; i<0x00110000; i++){
  19143. if( i>=0xD800 && i<0xE000 ) continue;
  19144. z = zBuf;
  19145. WRITE_UTF16BE(z, i);
  19146. n = (int)(z-zBuf);
  19147. assert( n>0 && n<=4 );
  19148. z[0] = 0;
  19149. z = zBuf;
  19150. READ_UTF16BE(z, 1, c);
  19151. assert( c==i );
  19152. assert( (z-zBuf)==n );
  19153. }
  19154. }
  19155. #endif /* SQLITE_TEST */
  19156. #endif /* SQLITE_OMIT_UTF16 */
  19157. /************** End of utf.c *************************************************/
  19158. /************** Begin file util.c ********************************************/
  19159. /*
  19160. ** 2001 September 15
  19161. **
  19162. ** The author disclaims copyright to this source code. In place of
  19163. ** a legal notice, here is a blessing:
  19164. **
  19165. ** May you do good and not evil.
  19166. ** May you find forgiveness for yourself and forgive others.
  19167. ** May you share freely, never taking more than you give.
  19168. **
  19169. *************************************************************************
  19170. ** Utility functions used throughout sqlite.
  19171. **
  19172. ** This file contains functions for allocating memory, comparing
  19173. ** strings, and stuff like that.
  19174. **
  19175. */
  19176. #ifdef SQLITE_HAVE_ISNAN
  19177. # include <math.h>
  19178. #endif
  19179. /*
  19180. ** Routine needed to support the testcase() macro.
  19181. */
  19182. #ifdef SQLITE_COVERAGE_TEST
  19183. SQLITE_PRIVATE void sqlite3Coverage(int x){
  19184. static unsigned dummy = 0;
  19185. dummy += (unsigned)x;
  19186. }
  19187. #endif
  19188. #ifndef SQLITE_OMIT_FLOATING_POINT
  19189. /*
  19190. ** Return true if the floating point value is Not a Number (NaN).
  19191. **
  19192. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  19193. ** Otherwise, we have our own implementation that works on most systems.
  19194. */
  19195. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  19196. int rc; /* The value return */
  19197. #if !defined(SQLITE_HAVE_ISNAN)
  19198. /*
  19199. ** Systems that support the isnan() library function should probably
  19200. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  19201. ** found that many systems do not have a working isnan() function so
  19202. ** this implementation is provided as an alternative.
  19203. **
  19204. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  19205. ** On the other hand, the use of -ffast-math comes with the following
  19206. ** warning:
  19207. **
  19208. ** This option [-ffast-math] should never be turned on by any
  19209. ** -O option since it can result in incorrect output for programs
  19210. ** which depend on an exact implementation of IEEE or ISO
  19211. ** rules/specifications for math functions.
  19212. **
  19213. ** Under MSVC, this NaN test may fail if compiled with a floating-
  19214. ** point precision mode other than /fp:precise. From the MSDN
  19215. ** documentation:
  19216. **
  19217. ** The compiler [with /fp:precise] will properly handle comparisons
  19218. ** involving NaN. For example, x != x evaluates to true if x is NaN
  19219. ** ...
  19220. */
  19221. #ifdef __FAST_MATH__
  19222. # error SQLite will not work correctly with the -ffast-math option of GCC.
  19223. #endif
  19224. volatile double y = x;
  19225. volatile double z = y;
  19226. rc = (y!=z);
  19227. #else /* if defined(SQLITE_HAVE_ISNAN) */
  19228. rc = isnan(x);
  19229. #endif /* SQLITE_HAVE_ISNAN */
  19230. testcase( rc );
  19231. return rc;
  19232. }
  19233. #endif /* SQLITE_OMIT_FLOATING_POINT */
  19234. /*
  19235. ** Compute a string length that is limited to what can be stored in
  19236. ** lower 30 bits of a 32-bit signed integer.
  19237. **
  19238. ** The value returned will never be negative. Nor will it ever be greater
  19239. ** than the actual length of the string. For very long strings (greater
  19240. ** than 1GiB) the value returned might be less than the true string length.
  19241. */
  19242. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  19243. const char *z2 = z;
  19244. if( z==0 ) return 0;
  19245. while( *z2 ){ z2++; }
  19246. return 0x3fffffff & (int)(z2 - z);
  19247. }
  19248. /*
  19249. ** Set the most recent error code and error string for the sqlite
  19250. ** handle "db". The error code is set to "err_code".
  19251. **
  19252. ** If it is not NULL, string zFormat specifies the format of the
  19253. ** error string in the style of the printf functions: The following
  19254. ** format characters are allowed:
  19255. **
  19256. ** %s Insert a string
  19257. ** %z A string that should be freed after use
  19258. ** %d Insert an integer
  19259. ** %T Insert a token
  19260. ** %S Insert the first element of a SrcList
  19261. **
  19262. ** zFormat and any string tokens that follow it are assumed to be
  19263. ** encoded in UTF-8.
  19264. **
  19265. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  19266. ** should be called with err_code set to SQLITE_OK and zFormat set
  19267. ** to NULL.
  19268. */
  19269. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  19270. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  19271. db->errCode = err_code;
  19272. if( zFormat ){
  19273. char *z;
  19274. va_list ap;
  19275. va_start(ap, zFormat);
  19276. z = sqlite3VMPrintf(db, zFormat, ap);
  19277. va_end(ap);
  19278. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  19279. }else{
  19280. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  19281. }
  19282. }
  19283. }
  19284. /*
  19285. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  19286. ** The following formatting characters are allowed:
  19287. **
  19288. ** %s Insert a string
  19289. ** %z A string that should be freed after use
  19290. ** %d Insert an integer
  19291. ** %T Insert a token
  19292. ** %S Insert the first element of a SrcList
  19293. **
  19294. ** This function should be used to report any error that occurs whilst
  19295. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  19296. ** last thing the sqlite3_prepare() function does is copy the error
  19297. ** stored by this function into the database handle using sqlite3Error().
  19298. ** Function sqlite3Error() should be used during statement execution
  19299. ** (sqlite3_step() etc.).
  19300. */
  19301. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  19302. char *zMsg;
  19303. va_list ap;
  19304. sqlite3 *db = pParse->db;
  19305. va_start(ap, zFormat);
  19306. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  19307. va_end(ap);
  19308. if( db->suppressErr ){
  19309. sqlite3DbFree(db, zMsg);
  19310. }else{
  19311. pParse->nErr++;
  19312. sqlite3DbFree(db, pParse->zErrMsg);
  19313. pParse->zErrMsg = zMsg;
  19314. pParse->rc = SQLITE_ERROR;
  19315. }
  19316. }
  19317. /*
  19318. ** Convert an SQL-style quoted string into a normal string by removing
  19319. ** the quote characters. The conversion is done in-place. If the
  19320. ** input does not begin with a quote character, then this routine
  19321. ** is a no-op.
  19322. **
  19323. ** The input string must be zero-terminated. A new zero-terminator
  19324. ** is added to the dequoted string.
  19325. **
  19326. ** The return value is -1 if no dequoting occurs or the length of the
  19327. ** dequoted string, exclusive of the zero terminator, if dequoting does
  19328. ** occur.
  19329. **
  19330. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  19331. ** brackets from around identifers. For example: "[a-b-c]" becomes
  19332. ** "a-b-c".
  19333. */
  19334. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  19335. char quote;
  19336. int i, j;
  19337. if( z==0 ) return -1;
  19338. quote = z[0];
  19339. switch( quote ){
  19340. case '\'': break;
  19341. case '"': break;
  19342. case '`': break; /* For MySQL compatibility */
  19343. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  19344. default: return -1;
  19345. }
  19346. for(i=1, j=0; ALWAYS(z[i]); i++){
  19347. if( z[i]==quote ){
  19348. if( z[i+1]==quote ){
  19349. z[j++] = quote;
  19350. i++;
  19351. }else{
  19352. break;
  19353. }
  19354. }else{
  19355. z[j++] = z[i];
  19356. }
  19357. }
  19358. z[j] = 0;
  19359. return j;
  19360. }
  19361. /* Convenient short-hand */
  19362. #define UpperToLower sqlite3UpperToLower
  19363. /*
  19364. ** Some systems have stricmp(). Others have strcasecmp(). Because
  19365. ** there is no consistency, we will define our own.
  19366. **
  19367. ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
  19368. ** applications and extensions to compare the contents of two buffers
  19369. ** containing UTF-8 strings in a case-independent fashion, using the same
  19370. ** definition of case independence that SQLite uses internally when
  19371. ** comparing identifiers.
  19372. */
  19373. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  19374. register unsigned char *a, *b;
  19375. a = (unsigned char *)zLeft;
  19376. b = (unsigned char *)zRight;
  19377. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  19378. return UpperToLower[*a] - UpperToLower[*b];
  19379. }
  19380. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  19381. register unsigned char *a, *b;
  19382. a = (unsigned char *)zLeft;
  19383. b = (unsigned char *)zRight;
  19384. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  19385. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  19386. }
  19387. /*
  19388. ** The string z[] is an text representation of a real number.
  19389. ** Convert this string to a double and write it into *pResult.
  19390. **
  19391. ** The string z[] is length bytes in length (bytes, not characters) and
  19392. ** uses the encoding enc. The string is not necessarily zero-terminated.
  19393. **
  19394. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  19395. ** if the string is empty or contains extraneous text. Valid numbers
  19396. ** are in one of these formats:
  19397. **
  19398. ** [+-]digits[E[+-]digits]
  19399. ** [+-]digits.[digits][E[+-]digits]
  19400. ** [+-].digits[E[+-]digits]
  19401. **
  19402. ** Leading and trailing whitespace is ignored for the purpose of determining
  19403. ** validity.
  19404. **
  19405. ** If some prefix of the input string is a valid number, this routine
  19406. ** returns FALSE but it still converts the prefix and writes the result
  19407. ** into *pResult.
  19408. */
  19409. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  19410. #ifndef SQLITE_OMIT_FLOATING_POINT
  19411. int incr = (enc==SQLITE_UTF8?1:2);
  19412. const char *zEnd = z + length;
  19413. /* sign * significand * (10 ^ (esign * exponent)) */
  19414. int sign = 1; /* sign of significand */
  19415. i64 s = 0; /* significand */
  19416. int d = 0; /* adjust exponent for shifting decimal point */
  19417. int esign = 1; /* sign of exponent */
  19418. int e = 0; /* exponent */
  19419. int eValid = 1; /* True exponent is either not used or is well-formed */
  19420. double result;
  19421. int nDigits = 0;
  19422. *pResult = 0.0; /* Default return value, in case of an error */
  19423. if( enc==SQLITE_UTF16BE ) z++;
  19424. /* skip leading spaces */
  19425. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  19426. if( z>=zEnd ) return 0;
  19427. /* get sign of significand */
  19428. if( *z=='-' ){
  19429. sign = -1;
  19430. z+=incr;
  19431. }else if( *z=='+' ){
  19432. z+=incr;
  19433. }
  19434. /* skip leading zeroes */
  19435. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  19436. /* copy max significant digits to significand */
  19437. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  19438. s = s*10 + (*z - '0');
  19439. z+=incr, nDigits++;
  19440. }
  19441. /* skip non-significant significand digits
  19442. ** (increase exponent by d to shift decimal left) */
  19443. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  19444. if( z>=zEnd ) goto do_atof_calc;
  19445. /* if decimal point is present */
  19446. if( *z=='.' ){
  19447. z+=incr;
  19448. /* copy digits from after decimal to significand
  19449. ** (decrease exponent by d to shift decimal right) */
  19450. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  19451. s = s*10 + (*z - '0');
  19452. z+=incr, nDigits++, d--;
  19453. }
  19454. /* skip non-significant digits */
  19455. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  19456. }
  19457. if( z>=zEnd ) goto do_atof_calc;
  19458. /* if exponent is present */
  19459. if( *z=='e' || *z=='E' ){
  19460. z+=incr;
  19461. eValid = 0;
  19462. if( z>=zEnd ) goto do_atof_calc;
  19463. /* get sign of exponent */
  19464. if( *z=='-' ){
  19465. esign = -1;
  19466. z+=incr;
  19467. }else if( *z=='+' ){
  19468. z+=incr;
  19469. }
  19470. /* copy digits to exponent */
  19471. while( z<zEnd && sqlite3Isdigit(*z) ){
  19472. e = e*10 + (*z - '0');
  19473. z+=incr;
  19474. eValid = 1;
  19475. }
  19476. }
  19477. /* skip trailing spaces */
  19478. if( nDigits && eValid ){
  19479. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  19480. }
  19481. do_atof_calc:
  19482. /* adjust exponent by d, and update sign */
  19483. e = (e*esign) + d;
  19484. if( e<0 ) {
  19485. esign = -1;
  19486. e *= -1;
  19487. } else {
  19488. esign = 1;
  19489. }
  19490. /* if 0 significand */
  19491. if( !s ) {
  19492. /* In the IEEE 754 standard, zero is signed.
  19493. ** Add the sign if we've seen at least one digit */
  19494. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  19495. } else {
  19496. /* attempt to reduce exponent */
  19497. if( esign>0 ){
  19498. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  19499. }else{
  19500. while( !(s%10) && e>0 ) e--,s/=10;
  19501. }
  19502. /* adjust the sign of significand */
  19503. s = sign<0 ? -s : s;
  19504. /* if exponent, scale significand as appropriate
  19505. ** and store in result. */
  19506. if( e ){
  19507. double scale = 1.0;
  19508. /* attempt to handle extremely small/large numbers better */
  19509. if( e>307 && e<342 ){
  19510. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  19511. if( esign<0 ){
  19512. result = s / scale;
  19513. result /= 1.0e+308;
  19514. }else{
  19515. result = s * scale;
  19516. result *= 1.0e+308;
  19517. }
  19518. }else{
  19519. /* 1.0e+22 is the largest power of 10 than can be
  19520. ** represented exactly. */
  19521. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  19522. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  19523. if( esign<0 ){
  19524. result = s / scale;
  19525. }else{
  19526. result = s * scale;
  19527. }
  19528. }
  19529. } else {
  19530. result = (double)s;
  19531. }
  19532. }
  19533. /* store the result */
  19534. *pResult = result;
  19535. /* return true if number and no extra non-whitespace chracters after */
  19536. return z>=zEnd && nDigits>0 && eValid;
  19537. #else
  19538. return !sqlite3Atoi64(z, pResult, length, enc);
  19539. #endif /* SQLITE_OMIT_FLOATING_POINT */
  19540. }
  19541. /*
  19542. ** Compare the 19-character string zNum against the text representation
  19543. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  19544. ** if zNum is less than, equal to, or greater than the string.
  19545. ** Note that zNum must contain exactly 19 characters.
  19546. **
  19547. ** Unlike memcmp() this routine is guaranteed to return the difference
  19548. ** in the values of the last digit if the only difference is in the
  19549. ** last digit. So, for example,
  19550. **
  19551. ** compare2pow63("9223372036854775800", 1)
  19552. **
  19553. ** will return -8.
  19554. */
  19555. static int compare2pow63(const char *zNum, int incr){
  19556. int c = 0;
  19557. int i;
  19558. /* 012345678901234567 */
  19559. const char *pow63 = "922337203685477580";
  19560. for(i=0; c==0 && i<18; i++){
  19561. c = (zNum[i*incr]-pow63[i])*10;
  19562. }
  19563. if( c==0 ){
  19564. c = zNum[18*incr] - '8';
  19565. testcase( c==(-1) );
  19566. testcase( c==0 );
  19567. testcase( c==(+1) );
  19568. }
  19569. return c;
  19570. }
  19571. /*
  19572. ** Convert zNum to a 64-bit signed integer.
  19573. **
  19574. ** If the zNum value is representable as a 64-bit twos-complement
  19575. ** integer, then write that value into *pNum and return 0.
  19576. **
  19577. ** If zNum is exactly 9223372036854665808, return 2. This special
  19578. ** case is broken out because while 9223372036854665808 cannot be a
  19579. ** signed 64-bit integer, its negative -9223372036854665808 can be.
  19580. **
  19581. ** If zNum is too big for a 64-bit integer and is not
  19582. ** 9223372036854665808 then return 1.
  19583. **
  19584. ** length is the number of bytes in the string (bytes, not characters).
  19585. ** The string is not necessarily zero-terminated. The encoding is
  19586. ** given by enc.
  19587. */
  19588. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  19589. int incr = (enc==SQLITE_UTF8?1:2);
  19590. u64 u = 0;
  19591. int neg = 0; /* assume positive */
  19592. int i;
  19593. int c = 0;
  19594. const char *zStart;
  19595. const char *zEnd = zNum + length;
  19596. if( enc==SQLITE_UTF16BE ) zNum++;
  19597. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  19598. if( zNum<zEnd ){
  19599. if( *zNum=='-' ){
  19600. neg = 1;
  19601. zNum+=incr;
  19602. }else if( *zNum=='+' ){
  19603. zNum+=incr;
  19604. }
  19605. }
  19606. zStart = zNum;
  19607. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  19608. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  19609. u = u*10 + c - '0';
  19610. }
  19611. if( u>LARGEST_INT64 ){
  19612. *pNum = SMALLEST_INT64;
  19613. }else if( neg ){
  19614. *pNum = -(i64)u;
  19615. }else{
  19616. *pNum = (i64)u;
  19617. }
  19618. testcase( i==18 );
  19619. testcase( i==19 );
  19620. testcase( i==20 );
  19621. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
  19622. /* zNum is empty or contains non-numeric text or is longer
  19623. ** than 19 digits (thus guaranteeing that it is too large) */
  19624. return 1;
  19625. }else if( i<19*incr ){
  19626. /* Less than 19 digits, so we know that it fits in 64 bits */
  19627. assert( u<=LARGEST_INT64 );
  19628. return 0;
  19629. }else{
  19630. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  19631. c = compare2pow63(zNum, incr);
  19632. if( c<0 ){
  19633. /* zNum is less than 9223372036854775808 so it fits */
  19634. assert( u<=LARGEST_INT64 );
  19635. return 0;
  19636. }else if( c>0 ){
  19637. /* zNum is greater than 9223372036854775808 so it overflows */
  19638. return 1;
  19639. }else{
  19640. /* zNum is exactly 9223372036854775808. Fits if negative. The
  19641. ** special case 2 overflow if positive */
  19642. assert( u-1==LARGEST_INT64 );
  19643. assert( (*pNum)==SMALLEST_INT64 );
  19644. return neg ? 0 : 2;
  19645. }
  19646. }
  19647. }
  19648. /*
  19649. ** If zNum represents an integer that will fit in 32-bits, then set
  19650. ** *pValue to that integer and return true. Otherwise return false.
  19651. **
  19652. ** Any non-numeric characters that following zNum are ignored.
  19653. ** This is different from sqlite3Atoi64() which requires the
  19654. ** input number to be zero-terminated.
  19655. */
  19656. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  19657. sqlite_int64 v = 0;
  19658. int i, c;
  19659. int neg = 0;
  19660. if( zNum[0]=='-' ){
  19661. neg = 1;
  19662. zNum++;
  19663. }else if( zNum[0]=='+' ){
  19664. zNum++;
  19665. }
  19666. while( zNum[0]=='0' ) zNum++;
  19667. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  19668. v = v*10 + c;
  19669. }
  19670. /* The longest decimal representation of a 32 bit integer is 10 digits:
  19671. **
  19672. ** 1234567890
  19673. ** 2^31 -> 2147483648
  19674. */
  19675. testcase( i==10 );
  19676. if( i>10 ){
  19677. return 0;
  19678. }
  19679. testcase( v-neg==2147483647 );
  19680. if( v-neg>2147483647 ){
  19681. return 0;
  19682. }
  19683. if( neg ){
  19684. v = -v;
  19685. }
  19686. *pValue = (int)v;
  19687. return 1;
  19688. }
  19689. /*
  19690. ** Return a 32-bit integer value extracted from a string. If the
  19691. ** string is not an integer, just return 0.
  19692. */
  19693. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  19694. int x = 0;
  19695. if( z ) sqlite3GetInt32(z, &x);
  19696. return x;
  19697. }
  19698. /*
  19699. ** The variable-length integer encoding is as follows:
  19700. **
  19701. ** KEY:
  19702. ** A = 0xxxxxxx 7 bits of data and one flag bit
  19703. ** B = 1xxxxxxx 7 bits of data and one flag bit
  19704. ** C = xxxxxxxx 8 bits of data
  19705. **
  19706. ** 7 bits - A
  19707. ** 14 bits - BA
  19708. ** 21 bits - BBA
  19709. ** 28 bits - BBBA
  19710. ** 35 bits - BBBBA
  19711. ** 42 bits - BBBBBA
  19712. ** 49 bits - BBBBBBA
  19713. ** 56 bits - BBBBBBBA
  19714. ** 64 bits - BBBBBBBBC
  19715. */
  19716. /*
  19717. ** Write a 64-bit variable-length integer to memory starting at p[0].
  19718. ** The length of data write will be between 1 and 9 bytes. The number
  19719. ** of bytes written is returned.
  19720. **
  19721. ** A variable-length integer consists of the lower 7 bits of each byte
  19722. ** for all bytes that have the 8th bit set and one byte with the 8th
  19723. ** bit clear. Except, if we get to the 9th byte, it stores the full
  19724. ** 8 bits and is the last byte.
  19725. */
  19726. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  19727. int i, j, n;
  19728. u8 buf[10];
  19729. if( v & (((u64)0xff000000)<<32) ){
  19730. p[8] = (u8)v;
  19731. v >>= 8;
  19732. for(i=7; i>=0; i--){
  19733. p[i] = (u8)((v & 0x7f) | 0x80);
  19734. v >>= 7;
  19735. }
  19736. return 9;
  19737. }
  19738. n = 0;
  19739. do{
  19740. buf[n++] = (u8)((v & 0x7f) | 0x80);
  19741. v >>= 7;
  19742. }while( v!=0 );
  19743. buf[0] &= 0x7f;
  19744. assert( n<=9 );
  19745. for(i=0, j=n-1; j>=0; j--, i++){
  19746. p[i] = buf[j];
  19747. }
  19748. return n;
  19749. }
  19750. /*
  19751. ** This routine is a faster version of sqlite3PutVarint() that only
  19752. ** works for 32-bit positive integers and which is optimized for
  19753. ** the common case of small integers. A MACRO version, putVarint32,
  19754. ** is provided which inlines the single-byte case. All code should use
  19755. ** the MACRO version as this function assumes the single-byte case has
  19756. ** already been handled.
  19757. */
  19758. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  19759. #ifndef putVarint32
  19760. if( (v & ~0x7f)==0 ){
  19761. p[0] = v;
  19762. return 1;
  19763. }
  19764. #endif
  19765. if( (v & ~0x3fff)==0 ){
  19766. p[0] = (u8)((v>>7) | 0x80);
  19767. p[1] = (u8)(v & 0x7f);
  19768. return 2;
  19769. }
  19770. return sqlite3PutVarint(p, v);
  19771. }
  19772. /*
  19773. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  19774. ** are defined here rather than simply putting the constant expressions
  19775. ** inline in order to work around bugs in the RVT compiler.
  19776. **
  19777. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  19778. **
  19779. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  19780. */
  19781. #define SLOT_2_0 0x001fc07f
  19782. #define SLOT_4_2_0 0xf01fc07f
  19783. /*
  19784. ** Read a 64-bit variable-length integer from memory starting at p[0].
  19785. ** Return the number of bytes read. The value is stored in *v.
  19786. */
  19787. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  19788. u32 a,b,s;
  19789. a = *p;
  19790. /* a: p0 (unmasked) */
  19791. if (!(a&0x80))
  19792. {
  19793. *v = a;
  19794. return 1;
  19795. }
  19796. p++;
  19797. b = *p;
  19798. /* b: p1 (unmasked) */
  19799. if (!(b&0x80))
  19800. {
  19801. a &= 0x7f;
  19802. a = a<<7;
  19803. a |= b;
  19804. *v = a;
  19805. return 2;
  19806. }
  19807. /* Verify that constants are precomputed correctly */
  19808. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  19809. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  19810. p++;
  19811. a = a<<14;
  19812. a |= *p;
  19813. /* a: p0<<14 | p2 (unmasked) */
  19814. if (!(a&0x80))
  19815. {
  19816. a &= SLOT_2_0;
  19817. b &= 0x7f;
  19818. b = b<<7;
  19819. a |= b;
  19820. *v = a;
  19821. return 3;
  19822. }
  19823. /* CSE1 from below */
  19824. a &= SLOT_2_0;
  19825. p++;
  19826. b = b<<14;
  19827. b |= *p;
  19828. /* b: p1<<14 | p3 (unmasked) */
  19829. if (!(b&0x80))
  19830. {
  19831. b &= SLOT_2_0;
  19832. /* moved CSE1 up */
  19833. /* a &= (0x7f<<14)|(0x7f); */
  19834. a = a<<7;
  19835. a |= b;
  19836. *v = a;
  19837. return 4;
  19838. }
  19839. /* a: p0<<14 | p2 (masked) */
  19840. /* b: p1<<14 | p3 (unmasked) */
  19841. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  19842. /* moved CSE1 up */
  19843. /* a &= (0x7f<<14)|(0x7f); */
  19844. b &= SLOT_2_0;
  19845. s = a;
  19846. /* s: p0<<14 | p2 (masked) */
  19847. p++;
  19848. a = a<<14;
  19849. a |= *p;
  19850. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  19851. if (!(a&0x80))
  19852. {
  19853. /* we can skip these cause they were (effectively) done above in calc'ing s */
  19854. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  19855. /* b &= (0x7f<<14)|(0x7f); */
  19856. b = b<<7;
  19857. a |= b;
  19858. s = s>>18;
  19859. *v = ((u64)s)<<32 | a;
  19860. return 5;
  19861. }
  19862. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  19863. s = s<<7;
  19864. s |= b;
  19865. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  19866. p++;
  19867. b = b<<14;
  19868. b |= *p;
  19869. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  19870. if (!(b&0x80))
  19871. {
  19872. /* we can skip this cause it was (effectively) done above in calc'ing s */
  19873. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  19874. a &= SLOT_2_0;
  19875. a = a<<7;
  19876. a |= b;
  19877. s = s>>18;
  19878. *v = ((u64)s)<<32 | a;
  19879. return 6;
  19880. }
  19881. p++;
  19882. a = a<<14;
  19883. a |= *p;
  19884. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  19885. if (!(a&0x80))
  19886. {
  19887. a &= SLOT_4_2_0;
  19888. b &= SLOT_2_0;
  19889. b = b<<7;
  19890. a |= b;
  19891. s = s>>11;
  19892. *v = ((u64)s)<<32 | a;
  19893. return 7;
  19894. }
  19895. /* CSE2 from below */
  19896. a &= SLOT_2_0;
  19897. p++;
  19898. b = b<<14;
  19899. b |= *p;
  19900. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  19901. if (!(b&0x80))
  19902. {
  19903. b &= SLOT_4_2_0;
  19904. /* moved CSE2 up */
  19905. /* a &= (0x7f<<14)|(0x7f); */
  19906. a = a<<7;
  19907. a |= b;
  19908. s = s>>4;
  19909. *v = ((u64)s)<<32 | a;
  19910. return 8;
  19911. }
  19912. p++;
  19913. a = a<<15;
  19914. a |= *p;
  19915. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  19916. /* moved CSE2 up */
  19917. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  19918. b &= SLOT_2_0;
  19919. b = b<<8;
  19920. a |= b;
  19921. s = s<<4;
  19922. b = p[-4];
  19923. b &= 0x7f;
  19924. b = b>>3;
  19925. s |= b;
  19926. *v = ((u64)s)<<32 | a;
  19927. return 9;
  19928. }
  19929. /*
  19930. ** Read a 32-bit variable-length integer from memory starting at p[0].
  19931. ** Return the number of bytes read. The value is stored in *v.
  19932. **
  19933. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  19934. ** integer, then set *v to 0xffffffff.
  19935. **
  19936. ** A MACRO version, getVarint32, is provided which inlines the
  19937. ** single-byte case. All code should use the MACRO version as
  19938. ** this function assumes the single-byte case has already been handled.
  19939. */
  19940. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  19941. u32 a,b;
  19942. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  19943. ** by the getVarin32() macro */
  19944. a = *p;
  19945. /* a: p0 (unmasked) */
  19946. #ifndef getVarint32
  19947. if (!(a&0x80))
  19948. {
  19949. /* Values between 0 and 127 */
  19950. *v = a;
  19951. return 1;
  19952. }
  19953. #endif
  19954. /* The 2-byte case */
  19955. p++;
  19956. b = *p;
  19957. /* b: p1 (unmasked) */
  19958. if (!(b&0x80))
  19959. {
  19960. /* Values between 128 and 16383 */
  19961. a &= 0x7f;
  19962. a = a<<7;
  19963. *v = a | b;
  19964. return 2;
  19965. }
  19966. /* The 3-byte case */
  19967. p++;
  19968. a = a<<14;
  19969. a |= *p;
  19970. /* a: p0<<14 | p2 (unmasked) */
  19971. if (!(a&0x80))
  19972. {
  19973. /* Values between 16384 and 2097151 */
  19974. a &= (0x7f<<14)|(0x7f);
  19975. b &= 0x7f;
  19976. b = b<<7;
  19977. *v = a | b;
  19978. return 3;
  19979. }
  19980. /* A 32-bit varint is used to store size information in btrees.
  19981. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  19982. ** A 3-byte varint is sufficient, for example, to record the size
  19983. ** of a 1048569-byte BLOB or string.
  19984. **
  19985. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  19986. ** rare larger cases can be handled by the slower 64-bit varint
  19987. ** routine.
  19988. */
  19989. #if 1
  19990. {
  19991. u64 v64;
  19992. u8 n;
  19993. p -= 2;
  19994. n = sqlite3GetVarint(p, &v64);
  19995. assert( n>3 && n<=9 );
  19996. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  19997. *v = 0xffffffff;
  19998. }else{
  19999. *v = (u32)v64;
  20000. }
  20001. return n;
  20002. }
  20003. #else
  20004. /* For following code (kept for historical record only) shows an
  20005. ** unrolling for the 3- and 4-byte varint cases. This code is
  20006. ** slightly faster, but it is also larger and much harder to test.
  20007. */
  20008. p++;
  20009. b = b<<14;
  20010. b |= *p;
  20011. /* b: p1<<14 | p3 (unmasked) */
  20012. if (!(b&0x80))
  20013. {
  20014. /* Values between 2097152 and 268435455 */
  20015. b &= (0x7f<<14)|(0x7f);
  20016. a &= (0x7f<<14)|(0x7f);
  20017. a = a<<7;
  20018. *v = a | b;
  20019. return 4;
  20020. }
  20021. p++;
  20022. a = a<<14;
  20023. a |= *p;
  20024. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  20025. if (!(a&0x80))
  20026. {
  20027. /* Values between 268435456 and 34359738367 */
  20028. a &= SLOT_4_2_0;
  20029. b &= SLOT_4_2_0;
  20030. b = b<<7;
  20031. *v = a | b;
  20032. return 5;
  20033. }
  20034. /* We can only reach this point when reading a corrupt database
  20035. ** file. In that case we are not in any hurry. Use the (relatively
  20036. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  20037. ** value. */
  20038. {
  20039. u64 v64;
  20040. u8 n;
  20041. p -= 4;
  20042. n = sqlite3GetVarint(p, &v64);
  20043. assert( n>5 && n<=9 );
  20044. *v = (u32)v64;
  20045. return n;
  20046. }
  20047. #endif
  20048. }
  20049. /*
  20050. ** Return the number of bytes that will be needed to store the given
  20051. ** 64-bit integer.
  20052. */
  20053. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  20054. int i = 0;
  20055. do{
  20056. i++;
  20057. v >>= 7;
  20058. }while( v!=0 && ALWAYS(i<9) );
  20059. return i;
  20060. }
  20061. /*
  20062. ** Read or write a four-byte big-endian integer value.
  20063. */
  20064. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  20065. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  20066. }
  20067. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  20068. p[0] = (u8)(v>>24);
  20069. p[1] = (u8)(v>>16);
  20070. p[2] = (u8)(v>>8);
  20071. p[3] = (u8)v;
  20072. }
  20073. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  20074. /*
  20075. ** Translate a single byte of Hex into an integer.
  20076. ** This routine only works if h really is a valid hexadecimal
  20077. ** character: 0..9a..fA..F
  20078. */
  20079. static u8 hexToInt(int h){
  20080. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  20081. #ifdef SQLITE_ASCII
  20082. h += 9*(1&(h>>6));
  20083. #endif
  20084. #ifdef SQLITE_EBCDIC
  20085. h += 9*(1&~(h>>4));
  20086. #endif
  20087. return (u8)(h & 0xf);
  20088. }
  20089. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  20090. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  20091. /*
  20092. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  20093. ** value. Return a pointer to its binary value. Space to hold the
  20094. ** binary value has been obtained from malloc and must be freed by
  20095. ** the calling routine.
  20096. */
  20097. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  20098. char *zBlob;
  20099. int i;
  20100. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  20101. n--;
  20102. if( zBlob ){
  20103. for(i=0; i<n; i+=2){
  20104. zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
  20105. }
  20106. zBlob[i/2] = 0;
  20107. }
  20108. return zBlob;
  20109. }
  20110. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  20111. /*
  20112. ** Log an error that is an API call on a connection pointer that should
  20113. ** not have been used. The "type" of connection pointer is given as the
  20114. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  20115. */
  20116. static void logBadConnection(const char *zType){
  20117. sqlite3_log(SQLITE_MISUSE,
  20118. "API call with %s database connection pointer",
  20119. zType
  20120. );
  20121. }
  20122. /*
  20123. ** Check to make sure we have a valid db pointer. This test is not
  20124. ** foolproof but it does provide some measure of protection against
  20125. ** misuse of the interface such as passing in db pointers that are
  20126. ** NULL or which have been previously closed. If this routine returns
  20127. ** 1 it means that the db pointer is valid and 0 if it should not be
  20128. ** dereferenced for any reason. The calling function should invoke
  20129. ** SQLITE_MISUSE immediately.
  20130. **
  20131. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  20132. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  20133. ** open properly and is not fit for general use but which can be
  20134. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  20135. */
  20136. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  20137. u32 magic;
  20138. if( db==0 ){
  20139. logBadConnection("NULL");
  20140. return 0;
  20141. }
  20142. magic = db->magic;
  20143. if( magic!=SQLITE_MAGIC_OPEN ){
  20144. if( sqlite3SafetyCheckSickOrOk(db) ){
  20145. testcase( sqlite3GlobalConfig.xLog!=0 );
  20146. logBadConnection("unopened");
  20147. }
  20148. return 0;
  20149. }else{
  20150. return 1;
  20151. }
  20152. }
  20153. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  20154. u32 magic;
  20155. magic = db->magic;
  20156. if( magic!=SQLITE_MAGIC_SICK &&
  20157. magic!=SQLITE_MAGIC_OPEN &&
  20158. magic!=SQLITE_MAGIC_BUSY ){
  20159. testcase( sqlite3GlobalConfig.xLog!=0 );
  20160. logBadConnection("invalid");
  20161. return 0;
  20162. }else{
  20163. return 1;
  20164. }
  20165. }
  20166. /*
  20167. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  20168. ** the other 64-bit signed integer at *pA and store the result in *pA.
  20169. ** Return 0 on success. Or if the operation would have resulted in an
  20170. ** overflow, leave *pA unchanged and return 1.
  20171. */
  20172. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  20173. i64 iA = *pA;
  20174. testcase( iA==0 ); testcase( iA==1 );
  20175. testcase( iB==-1 ); testcase( iB==0 );
  20176. if( iB>=0 ){
  20177. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  20178. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  20179. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  20180. *pA += iB;
  20181. }else{
  20182. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  20183. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  20184. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  20185. *pA += iB;
  20186. }
  20187. return 0;
  20188. }
  20189. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  20190. testcase( iB==SMALLEST_INT64+1 );
  20191. if( iB==SMALLEST_INT64 ){
  20192. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  20193. if( (*pA)>=0 ) return 1;
  20194. *pA -= iB;
  20195. return 0;
  20196. }else{
  20197. return sqlite3AddInt64(pA, -iB);
  20198. }
  20199. }
  20200. #define TWOPOWER32 (((i64)1)<<32)
  20201. #define TWOPOWER31 (((i64)1)<<31)
  20202. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  20203. i64 iA = *pA;
  20204. i64 iA1, iA0, iB1, iB0, r;
  20205. iA1 = iA/TWOPOWER32;
  20206. iA0 = iA % TWOPOWER32;
  20207. iB1 = iB/TWOPOWER32;
  20208. iB0 = iB % TWOPOWER32;
  20209. if( iA1*iB1 != 0 ) return 1;
  20210. assert( iA1*iB0==0 || iA0*iB1==0 );
  20211. r = iA1*iB0 + iA0*iB1;
  20212. testcase( r==(-TWOPOWER31)-1 );
  20213. testcase( r==(-TWOPOWER31) );
  20214. testcase( r==TWOPOWER31 );
  20215. testcase( r==TWOPOWER31-1 );
  20216. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  20217. r *= TWOPOWER32;
  20218. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  20219. *pA = r;
  20220. return 0;
  20221. }
  20222. /*
  20223. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  20224. ** if the integer has a value of -2147483648, return +2147483647
  20225. */
  20226. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  20227. if( x>=0 ) return x;
  20228. if( x==(int)0x80000000 ) return 0x7fffffff;
  20229. return -x;
  20230. }
  20231. /************** End of util.c ************************************************/
  20232. /************** Begin file hash.c ********************************************/
  20233. /*
  20234. ** 2001 September 22
  20235. **
  20236. ** The author disclaims copyright to this source code. In place of
  20237. ** a legal notice, here is a blessing:
  20238. **
  20239. ** May you do good and not evil.
  20240. ** May you find forgiveness for yourself and forgive others.
  20241. ** May you share freely, never taking more than you give.
  20242. **
  20243. *************************************************************************
  20244. ** This is the implementation of generic hash-tables
  20245. ** used in SQLite.
  20246. */
  20247. /* Turn bulk memory into a hash table object by initializing the
  20248. ** fields of the Hash structure.
  20249. **
  20250. ** "pNew" is a pointer to the hash table that is to be initialized.
  20251. */
  20252. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  20253. assert( pNew!=0 );
  20254. pNew->first = 0;
  20255. pNew->count = 0;
  20256. pNew->htsize = 0;
  20257. pNew->ht = 0;
  20258. }
  20259. /* Remove all entries from a hash table. Reclaim all memory.
  20260. ** Call this routine to delete a hash table or to reset a hash table
  20261. ** to the empty state.
  20262. */
  20263. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  20264. HashElem *elem; /* For looping over all elements of the table */
  20265. assert( pH!=0 );
  20266. elem = pH->first;
  20267. pH->first = 0;
  20268. sqlite3_free(pH->ht);
  20269. pH->ht = 0;
  20270. pH->htsize = 0;
  20271. while( elem ){
  20272. HashElem *next_elem = elem->next;
  20273. sqlite3_free(elem);
  20274. elem = next_elem;
  20275. }
  20276. pH->count = 0;
  20277. }
  20278. /*
  20279. ** The hashing function.
  20280. */
  20281. static unsigned int strHash(const char *z, int nKey){
  20282. int h = 0;
  20283. assert( nKey>=0 );
  20284. while( nKey > 0 ){
  20285. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  20286. nKey--;
  20287. }
  20288. return h;
  20289. }
  20290. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  20291. ** insert pNew into the pEntry hash bucket.
  20292. */
  20293. static void insertElement(
  20294. Hash *pH, /* The complete hash table */
  20295. struct _ht *pEntry, /* The entry into which pNew is inserted */
  20296. HashElem *pNew /* The element to be inserted */
  20297. ){
  20298. HashElem *pHead; /* First element already in pEntry */
  20299. if( pEntry ){
  20300. pHead = pEntry->count ? pEntry->chain : 0;
  20301. pEntry->count++;
  20302. pEntry->chain = pNew;
  20303. }else{
  20304. pHead = 0;
  20305. }
  20306. if( pHead ){
  20307. pNew->next = pHead;
  20308. pNew->prev = pHead->prev;
  20309. if( pHead->prev ){ pHead->prev->next = pNew; }
  20310. else { pH->first = pNew; }
  20311. pHead->prev = pNew;
  20312. }else{
  20313. pNew->next = pH->first;
  20314. if( pH->first ){ pH->first->prev = pNew; }
  20315. pNew->prev = 0;
  20316. pH->first = pNew;
  20317. }
  20318. }
  20319. /* Resize the hash table so that it cantains "new_size" buckets.
  20320. **
  20321. ** The hash table might fail to resize if sqlite3_malloc() fails or
  20322. ** if the new size is the same as the prior size.
  20323. ** Return TRUE if the resize occurs and false if not.
  20324. */
  20325. static int rehash(Hash *pH, unsigned int new_size){
  20326. struct _ht *new_ht; /* The new hash table */
  20327. HashElem *elem, *next_elem; /* For looping over existing elements */
  20328. #if SQLITE_MALLOC_SOFT_LIMIT>0
  20329. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  20330. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  20331. }
  20332. if( new_size==pH->htsize ) return 0;
  20333. #endif
  20334. /* The inability to allocates space for a larger hash table is
  20335. ** a performance hit but it is not a fatal error. So mark the
  20336. ** allocation as a benign.
  20337. */
  20338. sqlite3BeginBenignMalloc();
  20339. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  20340. sqlite3EndBenignMalloc();
  20341. if( new_ht==0 ) return 0;
  20342. sqlite3_free(pH->ht);
  20343. pH->ht = new_ht;
  20344. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  20345. memset(new_ht, 0, new_size*sizeof(struct _ht));
  20346. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  20347. unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
  20348. next_elem = elem->next;
  20349. insertElement(pH, &new_ht[h], elem);
  20350. }
  20351. return 1;
  20352. }
  20353. /* This function (for internal use only) locates an element in an
  20354. ** hash table that matches the given key. The hash for this key has
  20355. ** already been computed and is passed as the 4th parameter.
  20356. */
  20357. static HashElem *findElementGivenHash(
  20358. const Hash *pH, /* The pH to be searched */
  20359. const char *pKey, /* The key we are searching for */
  20360. int nKey, /* Bytes in key (not counting zero terminator) */
  20361. unsigned int h /* The hash for this key. */
  20362. ){
  20363. HashElem *elem; /* Used to loop thru the element list */
  20364. int count; /* Number of elements left to test */
  20365. if( pH->ht ){
  20366. struct _ht *pEntry = &pH->ht[h];
  20367. elem = pEntry->chain;
  20368. count = pEntry->count;
  20369. }else{
  20370. elem = pH->first;
  20371. count = pH->count;
  20372. }
  20373. while( count-- && ALWAYS(elem) ){
  20374. if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  20375. return elem;
  20376. }
  20377. elem = elem->next;
  20378. }
  20379. return 0;
  20380. }
  20381. /* Remove a single entry from the hash table given a pointer to that
  20382. ** element and a hash on the element's key.
  20383. */
  20384. static void removeElementGivenHash(
  20385. Hash *pH, /* The pH containing "elem" */
  20386. HashElem* elem, /* The element to be removed from the pH */
  20387. unsigned int h /* Hash value for the element */
  20388. ){
  20389. struct _ht *pEntry;
  20390. if( elem->prev ){
  20391. elem->prev->next = elem->next;
  20392. }else{
  20393. pH->first = elem->next;
  20394. }
  20395. if( elem->next ){
  20396. elem->next->prev = elem->prev;
  20397. }
  20398. if( pH->ht ){
  20399. pEntry = &pH->ht[h];
  20400. if( pEntry->chain==elem ){
  20401. pEntry->chain = elem->next;
  20402. }
  20403. pEntry->count--;
  20404. assert( pEntry->count>=0 );
  20405. }
  20406. sqlite3_free( elem );
  20407. pH->count--;
  20408. if( pH->count<=0 ){
  20409. assert( pH->first==0 );
  20410. assert( pH->count==0 );
  20411. sqlite3HashClear(pH);
  20412. }
  20413. }
  20414. /* Attempt to locate an element of the hash table pH with a key
  20415. ** that matches pKey,nKey. Return the data for this element if it is
  20416. ** found, or NULL if there is no match.
  20417. */
  20418. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  20419. HashElem *elem; /* The element that matches key */
  20420. unsigned int h; /* A hash on key */
  20421. assert( pH!=0 );
  20422. assert( pKey!=0 );
  20423. assert( nKey>=0 );
  20424. if( pH->ht ){
  20425. h = strHash(pKey, nKey) % pH->htsize;
  20426. }else{
  20427. h = 0;
  20428. }
  20429. elem = findElementGivenHash(pH, pKey, nKey, h);
  20430. return elem ? elem->data : 0;
  20431. }
  20432. /* Insert an element into the hash table pH. The key is pKey,nKey
  20433. ** and the data is "data".
  20434. **
  20435. ** If no element exists with a matching key, then a new
  20436. ** element is created and NULL is returned.
  20437. **
  20438. ** If another element already exists with the same key, then the
  20439. ** new data replaces the old data and the old data is returned.
  20440. ** The key is not copied in this instance. If a malloc fails, then
  20441. ** the new data is returned and the hash table is unchanged.
  20442. **
  20443. ** If the "data" parameter to this function is NULL, then the
  20444. ** element corresponding to "key" is removed from the hash table.
  20445. */
  20446. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  20447. unsigned int h; /* the hash of the key modulo hash table size */
  20448. HashElem *elem; /* Used to loop thru the element list */
  20449. HashElem *new_elem; /* New element added to the pH */
  20450. assert( pH!=0 );
  20451. assert( pKey!=0 );
  20452. assert( nKey>=0 );
  20453. if( pH->htsize ){
  20454. h = strHash(pKey, nKey) % pH->htsize;
  20455. }else{
  20456. h = 0;
  20457. }
  20458. elem = findElementGivenHash(pH,pKey,nKey,h);
  20459. if( elem ){
  20460. void *old_data = elem->data;
  20461. if( data==0 ){
  20462. removeElementGivenHash(pH,elem,h);
  20463. }else{
  20464. elem->data = data;
  20465. elem->pKey = pKey;
  20466. assert(nKey==elem->nKey);
  20467. }
  20468. return old_data;
  20469. }
  20470. if( data==0 ) return 0;
  20471. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  20472. if( new_elem==0 ) return data;
  20473. new_elem->pKey = pKey;
  20474. new_elem->nKey = nKey;
  20475. new_elem->data = data;
  20476. pH->count++;
  20477. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  20478. if( rehash(pH, pH->count*2) ){
  20479. assert( pH->htsize>0 );
  20480. h = strHash(pKey, nKey) % pH->htsize;
  20481. }
  20482. }
  20483. if( pH->ht ){
  20484. insertElement(pH, &pH->ht[h], new_elem);
  20485. }else{
  20486. insertElement(pH, 0, new_elem);
  20487. }
  20488. return 0;
  20489. }
  20490. /************** End of hash.c ************************************************/
  20491. /************** Begin file opcodes.c *****************************************/
  20492. /* Automatically generated. Do not edit */
  20493. /* See the mkopcodec.awk script for details. */
  20494. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  20495. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  20496. static const char *const azName[] = { "?",
  20497. /* 1 */ "Goto",
  20498. /* 2 */ "Gosub",
  20499. /* 3 */ "Return",
  20500. /* 4 */ "Yield",
  20501. /* 5 */ "HaltIfNull",
  20502. /* 6 */ "Halt",
  20503. /* 7 */ "Integer",
  20504. /* 8 */ "Int64",
  20505. /* 9 */ "String",
  20506. /* 10 */ "Null",
  20507. /* 11 */ "Blob",
  20508. /* 12 */ "Variable",
  20509. /* 13 */ "Move",
  20510. /* 14 */ "Copy",
  20511. /* 15 */ "SCopy",
  20512. /* 16 */ "ResultRow",
  20513. /* 17 */ "CollSeq",
  20514. /* 18 */ "Function",
  20515. /* 19 */ "Not",
  20516. /* 20 */ "AddImm",
  20517. /* 21 */ "MustBeInt",
  20518. /* 22 */ "RealAffinity",
  20519. /* 23 */ "Permutation",
  20520. /* 24 */ "Compare",
  20521. /* 25 */ "Jump",
  20522. /* 26 */ "If",
  20523. /* 27 */ "IfNot",
  20524. /* 28 */ "Column",
  20525. /* 29 */ "Affinity",
  20526. /* 30 */ "MakeRecord",
  20527. /* 31 */ "Count",
  20528. /* 32 */ "Savepoint",
  20529. /* 33 */ "AutoCommit",
  20530. /* 34 */ "Transaction",
  20531. /* 35 */ "ReadCookie",
  20532. /* 36 */ "SetCookie",
  20533. /* 37 */ "VerifyCookie",
  20534. /* 38 */ "OpenRead",
  20535. /* 39 */ "OpenWrite",
  20536. /* 40 */ "OpenAutoindex",
  20537. /* 41 */ "OpenEphemeral",
  20538. /* 42 */ "OpenPseudo",
  20539. /* 43 */ "Close",
  20540. /* 44 */ "SeekLt",
  20541. /* 45 */ "SeekLe",
  20542. /* 46 */ "SeekGe",
  20543. /* 47 */ "SeekGt",
  20544. /* 48 */ "Seek",
  20545. /* 49 */ "NotFound",
  20546. /* 50 */ "Found",
  20547. /* 51 */ "IsUnique",
  20548. /* 52 */ "NotExists",
  20549. /* 53 */ "Sequence",
  20550. /* 54 */ "NewRowid",
  20551. /* 55 */ "Insert",
  20552. /* 56 */ "InsertInt",
  20553. /* 57 */ "Delete",
  20554. /* 58 */ "ResetCount",
  20555. /* 59 */ "RowKey",
  20556. /* 60 */ "RowData",
  20557. /* 61 */ "Rowid",
  20558. /* 62 */ "NullRow",
  20559. /* 63 */ "Last",
  20560. /* 64 */ "Sort",
  20561. /* 65 */ "Rewind",
  20562. /* 66 */ "Prev",
  20563. /* 67 */ "Next",
  20564. /* 68 */ "Or",
  20565. /* 69 */ "And",
  20566. /* 70 */ "IdxInsert",
  20567. /* 71 */ "IdxDelete",
  20568. /* 72 */ "IdxRowid",
  20569. /* 73 */ "IsNull",
  20570. /* 74 */ "NotNull",
  20571. /* 75 */ "Ne",
  20572. /* 76 */ "Eq",
  20573. /* 77 */ "Gt",
  20574. /* 78 */ "Le",
  20575. /* 79 */ "Lt",
  20576. /* 80 */ "Ge",
  20577. /* 81 */ "IdxLT",
  20578. /* 82 */ "BitAnd",
  20579. /* 83 */ "BitOr",
  20580. /* 84 */ "ShiftLeft",
  20581. /* 85 */ "ShiftRight",
  20582. /* 86 */ "Add",
  20583. /* 87 */ "Subtract",
  20584. /* 88 */ "Multiply",
  20585. /* 89 */ "Divide",
  20586. /* 90 */ "Remainder",
  20587. /* 91 */ "Concat",
  20588. /* 92 */ "IdxGE",
  20589. /* 93 */ "BitNot",
  20590. /* 94 */ "String8",
  20591. /* 95 */ "Destroy",
  20592. /* 96 */ "Clear",
  20593. /* 97 */ "CreateIndex",
  20594. /* 98 */ "CreateTable",
  20595. /* 99 */ "ParseSchema",
  20596. /* 100 */ "LoadAnalysis",
  20597. /* 101 */ "DropTable",
  20598. /* 102 */ "DropIndex",
  20599. /* 103 */ "DropTrigger",
  20600. /* 104 */ "IntegrityCk",
  20601. /* 105 */ "RowSetAdd",
  20602. /* 106 */ "RowSetRead",
  20603. /* 107 */ "RowSetTest",
  20604. /* 108 */ "Program",
  20605. /* 109 */ "Param",
  20606. /* 110 */ "FkCounter",
  20607. /* 111 */ "FkIfZero",
  20608. /* 112 */ "MemMax",
  20609. /* 113 */ "IfPos",
  20610. /* 114 */ "IfNeg",
  20611. /* 115 */ "IfZero",
  20612. /* 116 */ "AggStep",
  20613. /* 117 */ "AggFinal",
  20614. /* 118 */ "Checkpoint",
  20615. /* 119 */ "JournalMode",
  20616. /* 120 */ "Vacuum",
  20617. /* 121 */ "IncrVacuum",
  20618. /* 122 */ "Expire",
  20619. /* 123 */ "TableLock",
  20620. /* 124 */ "VBegin",
  20621. /* 125 */ "VCreate",
  20622. /* 126 */ "VDestroy",
  20623. /* 127 */ "VOpen",
  20624. /* 128 */ "VFilter",
  20625. /* 129 */ "VColumn",
  20626. /* 130 */ "Real",
  20627. /* 131 */ "VNext",
  20628. /* 132 */ "VRename",
  20629. /* 133 */ "VUpdate",
  20630. /* 134 */ "Pagecount",
  20631. /* 135 */ "MaxPgcnt",
  20632. /* 136 */ "Trace",
  20633. /* 137 */ "Noop",
  20634. /* 138 */ "Explain",
  20635. /* 139 */ "NotUsed_139",
  20636. /* 140 */ "NotUsed_140",
  20637. /* 141 */ "ToText",
  20638. /* 142 */ "ToBlob",
  20639. /* 143 */ "ToNumeric",
  20640. /* 144 */ "ToInt",
  20641. /* 145 */ "ToReal",
  20642. };
  20643. return azName[i];
  20644. }
  20645. #endif
  20646. /************** End of opcodes.c *********************************************/
  20647. /************** Begin file os_os2.c ******************************************/
  20648. /*
  20649. ** 2006 Feb 14
  20650. **
  20651. ** The author disclaims copyright to this source code. In place of
  20652. ** a legal notice, here is a blessing:
  20653. **
  20654. ** May you do good and not evil.
  20655. ** May you find forgiveness for yourself and forgive others.
  20656. ** May you share freely, never taking more than you give.
  20657. **
  20658. ******************************************************************************
  20659. **
  20660. ** This file contains code that is specific to OS/2.
  20661. */
  20662. #if SQLITE_OS_OS2
  20663. /*
  20664. ** A Note About Memory Allocation:
  20665. **
  20666. ** This driver uses malloc()/free() directly rather than going through
  20667. ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
  20668. ** are designed for use on embedded systems where memory is scarce and
  20669. ** malloc failures happen frequently. OS/2 does not typically run on
  20670. ** embedded systems, and when it does the developers normally have bigger
  20671. ** problems to worry about than running out of memory. So there is not
  20672. ** a compelling need to use the wrappers.
  20673. **
  20674. ** But there is a good reason to not use the wrappers. If we use the
  20675. ** wrappers then we will get simulated malloc() failures within this
  20676. ** driver. And that causes all kinds of problems for our tests. We
  20677. ** could enhance SQLite to deal with simulated malloc failures within
  20678. ** the OS driver, but the code to deal with those failure would not
  20679. ** be exercised on Linux (which does not need to malloc() in the driver)
  20680. ** and so we would have difficulty writing coverage tests for that
  20681. ** code. Better to leave the code out, we think.
  20682. **
  20683. ** The point of this discussion is as follows: When creating a new
  20684. ** OS layer for an embedded system, if you use this file as an example,
  20685. ** avoid the use of malloc()/free(). Those routines work ok on OS/2
  20686. ** desktops but not so well in embedded systems.
  20687. */
  20688. /*
  20689. ** Macros used to determine whether or not to use threads.
  20690. */
  20691. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
  20692. # define SQLITE_OS2_THREADS 1
  20693. #endif
  20694. /*
  20695. ** Include code that is common to all os_*.c files
  20696. */
  20697. /************** Include os_common.h in the middle of os_os2.c ****************/
  20698. /************** Begin file os_common.h ***************************************/
  20699. /*
  20700. ** 2004 May 22
  20701. **
  20702. ** The author disclaims copyright to this source code. In place of
  20703. ** a legal notice, here is a blessing:
  20704. **
  20705. ** May you do good and not evil.
  20706. ** May you find forgiveness for yourself and forgive others.
  20707. ** May you share freely, never taking more than you give.
  20708. **
  20709. ******************************************************************************
  20710. **
  20711. ** This file contains macros and a little bit of code that is common to
  20712. ** all of the platform-specific files (os_*.c) and is #included into those
  20713. ** files.
  20714. **
  20715. ** This file should be #included by the os_*.c files only. It is not a
  20716. ** general purpose header file.
  20717. */
  20718. #ifndef _OS_COMMON_H_
  20719. #define _OS_COMMON_H_
  20720. /*
  20721. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  20722. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  20723. ** switch. The following code should catch this problem at compile-time.
  20724. */
  20725. #ifdef MEMORY_DEBUG
  20726. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  20727. #endif
  20728. #ifdef SQLITE_DEBUG
  20729. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  20730. #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  20731. #else
  20732. #define OSTRACE(X)
  20733. #endif
  20734. /*
  20735. ** Macros for performance tracing. Normally turned off. Only works
  20736. ** on i486 hardware.
  20737. */
  20738. #ifdef SQLITE_PERFORMANCE_TRACE
  20739. /*
  20740. ** hwtime.h contains inline assembler code for implementing
  20741. ** high-performance timing routines.
  20742. */
  20743. /************** Include hwtime.h in the middle of os_common.h ****************/
  20744. /************** Begin file hwtime.h ******************************************/
  20745. /*
  20746. ** 2008 May 27
  20747. **
  20748. ** The author disclaims copyright to this source code. In place of
  20749. ** a legal notice, here is a blessing:
  20750. **
  20751. ** May you do good and not evil.
  20752. ** May you find forgiveness for yourself and forgive others.
  20753. ** May you share freely, never taking more than you give.
  20754. **
  20755. ******************************************************************************
  20756. **
  20757. ** This file contains inline asm code for retrieving "high-performance"
  20758. ** counters for x86 class CPUs.
  20759. */
  20760. #ifndef _HWTIME_H_
  20761. #define _HWTIME_H_
  20762. /*
  20763. ** The following routine only works on pentium-class (or newer) processors.
  20764. ** It uses the RDTSC opcode to read the cycle count value out of the
  20765. ** processor and returns that value. This can be used for high-res
  20766. ** profiling.
  20767. */
  20768. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  20769. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  20770. #if defined(__GNUC__)
  20771. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20772. unsigned int lo, hi;
  20773. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  20774. return (sqlite_uint64)hi << 32 | lo;
  20775. }
  20776. #elif defined(_MSC_VER)
  20777. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  20778. __asm {
  20779. rdtsc
  20780. ret ; return value at EDX:EAX
  20781. }
  20782. }
  20783. #endif
  20784. #elif (defined(__GNUC__) && defined(__x86_64__))
  20785. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20786. unsigned long val;
  20787. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  20788. return val;
  20789. }
  20790. #elif (defined(__GNUC__) && defined(__ppc__))
  20791. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  20792. unsigned long long retval;
  20793. unsigned long junk;
  20794. __asm__ __volatile__ ("\n\
  20795. 1: mftbu %1\n\
  20796. mftb %L0\n\
  20797. mftbu %0\n\
  20798. cmpw %0,%1\n\
  20799. bne 1b"
  20800. : "=r" (retval), "=r" (junk));
  20801. return retval;
  20802. }
  20803. #else
  20804. #error Need implementation of sqlite3Hwtime() for your platform.
  20805. /*
  20806. ** To compile without implementing sqlite3Hwtime() for your platform,
  20807. ** you can remove the above #error and use the following
  20808. ** stub function. You will lose timing support for many
  20809. ** of the debugging and testing utilities, but it should at
  20810. ** least compile and run.
  20811. */
  20812. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  20813. #endif
  20814. #endif /* !defined(_HWTIME_H_) */
  20815. /************** End of hwtime.h **********************************************/
  20816. /************** Continuing where we left off in os_common.h ******************/
  20817. static sqlite_uint64 g_start;
  20818. static sqlite_uint64 g_elapsed;
  20819. #define TIMER_START g_start=sqlite3Hwtime()
  20820. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  20821. #define TIMER_ELAPSED g_elapsed
  20822. #else
  20823. #define TIMER_START
  20824. #define TIMER_END
  20825. #define TIMER_ELAPSED ((sqlite_uint64)0)
  20826. #endif
  20827. /*
  20828. ** If we compile with the SQLITE_TEST macro set, then the following block
  20829. ** of code will give us the ability to simulate a disk I/O error. This
  20830. ** is used for testing the I/O recovery logic.
  20831. */
  20832. #ifdef SQLITE_TEST
  20833. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  20834. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  20835. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  20836. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  20837. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  20838. SQLITE_API int sqlite3_diskfull_pending = 0;
  20839. SQLITE_API int sqlite3_diskfull = 0;
  20840. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  20841. #define SimulateIOError(CODE) \
  20842. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  20843. || sqlite3_io_error_pending-- == 1 ) \
  20844. { local_ioerr(); CODE; }
  20845. static void local_ioerr(){
  20846. IOTRACE(("IOERR\n"));
  20847. sqlite3_io_error_hit++;
  20848. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  20849. }
  20850. #define SimulateDiskfullError(CODE) \
  20851. if( sqlite3_diskfull_pending ){ \
  20852. if( sqlite3_diskfull_pending == 1 ){ \
  20853. local_ioerr(); \
  20854. sqlite3_diskfull = 1; \
  20855. sqlite3_io_error_hit = 1; \
  20856. CODE; \
  20857. }else{ \
  20858. sqlite3_diskfull_pending--; \
  20859. } \
  20860. }
  20861. #else
  20862. #define SimulateIOErrorBenign(X)
  20863. #define SimulateIOError(A)
  20864. #define SimulateDiskfullError(A)
  20865. #endif
  20866. /*
  20867. ** When testing, keep a count of the number of open files.
  20868. */
  20869. #ifdef SQLITE_TEST
  20870. SQLITE_API int sqlite3_open_file_count = 0;
  20871. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  20872. #else
  20873. #define OpenCounter(X)
  20874. #endif
  20875. #endif /* !defined(_OS_COMMON_H_) */
  20876. /************** End of os_common.h *******************************************/
  20877. /************** Continuing where we left off in os_os2.c *********************/
  20878. /* Forward references */
  20879. typedef struct os2File os2File; /* The file structure */
  20880. typedef struct os2ShmNode os2ShmNode; /* A shared descritive memory node */
  20881. typedef struct os2ShmLink os2ShmLink; /* A connection to shared-memory */
  20882. /*
  20883. ** The os2File structure is subclass of sqlite3_file specific for the OS/2
  20884. ** protability layer.
  20885. */
  20886. struct os2File {
  20887. const sqlite3_io_methods *pMethod; /* Always the first entry */
  20888. HFILE h; /* Handle for accessing the file */
  20889. int flags; /* Flags provided to os2Open() */
  20890. int locktype; /* Type of lock currently held on this file */
  20891. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  20892. char *zFullPathCp; /* Full path name of this file */
  20893. os2ShmLink *pShmLink; /* Instance of shared memory on this file */
  20894. };
  20895. #define LOCK_TIMEOUT 10L /* the default locking timeout */
  20896. /*
  20897. ** Missing from some versions of the OS/2 toolkit -
  20898. ** used to allocate from high memory if possible
  20899. */
  20900. #ifndef OBJ_ANY
  20901. # define OBJ_ANY 0x00000400
  20902. #endif
  20903. /*****************************************************************************
  20904. ** The next group of routines implement the I/O methods specified
  20905. ** by the sqlite3_io_methods object.
  20906. ******************************************************************************/
  20907. /*
  20908. ** Close a file.
  20909. */
  20910. static int os2Close( sqlite3_file *id ){
  20911. APIRET rc;
  20912. os2File *pFile = (os2File*)id;
  20913. assert( id!=0 );
  20914. OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
  20915. rc = DosClose( pFile->h );
  20916. if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
  20917. DosForceDelete( (PSZ)pFile->zFullPathCp );
  20918. free( pFile->zFullPathCp );
  20919. pFile->zFullPathCp = NULL;
  20920. pFile->locktype = NO_LOCK;
  20921. pFile->h = (HFILE)-1;
  20922. pFile->flags = 0;
  20923. OpenCounter( -1 );
  20924. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  20925. }
  20926. /*
  20927. ** Read data from a file into a buffer. Return SQLITE_OK if all
  20928. ** bytes were read successfully and SQLITE_IOERR if anything goes
  20929. ** wrong.
  20930. */
  20931. static int os2Read(
  20932. sqlite3_file *id, /* File to read from */
  20933. void *pBuf, /* Write content into this buffer */
  20934. int amt, /* Number of bytes to read */
  20935. sqlite3_int64 offset /* Begin reading at this offset */
  20936. ){
  20937. ULONG fileLocation = 0L;
  20938. ULONG got;
  20939. os2File *pFile = (os2File*)id;
  20940. assert( id!=0 );
  20941. SimulateIOError( return SQLITE_IOERR_READ );
  20942. OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
  20943. if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
  20944. return SQLITE_IOERR;
  20945. }
  20946. if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
  20947. return SQLITE_IOERR_READ;
  20948. }
  20949. if( got == (ULONG)amt )
  20950. return SQLITE_OK;
  20951. else {
  20952. /* Unread portions of the input buffer must be zero-filled */
  20953. memset(&((char*)pBuf)[got], 0, amt-got);
  20954. return SQLITE_IOERR_SHORT_READ;
  20955. }
  20956. }
  20957. /*
  20958. ** Write data from a buffer into a file. Return SQLITE_OK on success
  20959. ** or some other error code on failure.
  20960. */
  20961. static int os2Write(
  20962. sqlite3_file *id, /* File to write into */
  20963. const void *pBuf, /* The bytes to be written */
  20964. int amt, /* Number of bytes to write */
  20965. sqlite3_int64 offset /* Offset into the file to begin writing at */
  20966. ){
  20967. ULONG fileLocation = 0L;
  20968. APIRET rc = NO_ERROR;
  20969. ULONG wrote;
  20970. os2File *pFile = (os2File*)id;
  20971. assert( id!=0 );
  20972. SimulateIOError( return SQLITE_IOERR_WRITE );
  20973. SimulateDiskfullError( return SQLITE_FULL );
  20974. OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
  20975. if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
  20976. return SQLITE_IOERR;
  20977. }
  20978. assert( amt>0 );
  20979. while( amt > 0 &&
  20980. ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
  20981. wrote > 0
  20982. ){
  20983. amt -= wrote;
  20984. pBuf = &((char*)pBuf)[wrote];
  20985. }
  20986. return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
  20987. }
  20988. /*
  20989. ** Truncate an open file to a specified size
  20990. */
  20991. static int os2Truncate( sqlite3_file *id, i64 nByte ){
  20992. APIRET rc;
  20993. os2File *pFile = (os2File*)id;
  20994. assert( id!=0 );
  20995. OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
  20996. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  20997. /* If the user has configured a chunk-size for this file, truncate the
  20998. ** file so that it consists of an integer number of chunks (i.e. the
  20999. ** actual file size after the operation may be larger than the requested
  21000. ** size).
  21001. */
  21002. if( pFile->szChunk ){
  21003. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  21004. }
  21005. rc = DosSetFileSize( pFile->h, nByte );
  21006. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
  21007. }
  21008. #ifdef SQLITE_TEST
  21009. /*
  21010. ** Count the number of fullsyncs and normal syncs. This is used to test
  21011. ** that syncs and fullsyncs are occuring at the right times.
  21012. */
  21013. SQLITE_API int sqlite3_sync_count = 0;
  21014. SQLITE_API int sqlite3_fullsync_count = 0;
  21015. #endif
  21016. /*
  21017. ** Make sure all writes to a particular file are committed to disk.
  21018. */
  21019. static int os2Sync( sqlite3_file *id, int flags ){
  21020. os2File *pFile = (os2File*)id;
  21021. OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
  21022. #ifdef SQLITE_TEST
  21023. if( flags & SQLITE_SYNC_FULL){
  21024. sqlite3_fullsync_count++;
  21025. }
  21026. sqlite3_sync_count++;
  21027. #endif
  21028. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  21029. ** no-op
  21030. */
  21031. #ifdef SQLITE_NO_SYNC
  21032. UNUSED_PARAMETER(pFile);
  21033. return SQLITE_OK;
  21034. #else
  21035. return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  21036. #endif
  21037. }
  21038. /*
  21039. ** Determine the current size of a file in bytes
  21040. */
  21041. static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
  21042. APIRET rc = NO_ERROR;
  21043. FILESTATUS3 fsts3FileInfo;
  21044. memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
  21045. assert( id!=0 );
  21046. SimulateIOError( return SQLITE_IOERR_FSTAT );
  21047. rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
  21048. if( rc == NO_ERROR ){
  21049. *pSize = fsts3FileInfo.cbFile;
  21050. return SQLITE_OK;
  21051. }else{
  21052. return SQLITE_IOERR_FSTAT;
  21053. }
  21054. }
  21055. /*
  21056. ** Acquire a reader lock.
  21057. */
  21058. static int getReadLock( os2File *pFile ){
  21059. FILELOCK LockArea,
  21060. UnlockArea;
  21061. APIRET res;
  21062. memset(&LockArea, 0, sizeof(LockArea));
  21063. memset(&UnlockArea, 0, sizeof(UnlockArea));
  21064. LockArea.lOffset = SHARED_FIRST;
  21065. LockArea.lRange = SHARED_SIZE;
  21066. UnlockArea.lOffset = 0L;
  21067. UnlockArea.lRange = 0L;
  21068. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  21069. OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
  21070. return res;
  21071. }
  21072. /*
  21073. ** Undo a readlock
  21074. */
  21075. static int unlockReadLock( os2File *id ){
  21076. FILELOCK LockArea,
  21077. UnlockArea;
  21078. APIRET res;
  21079. memset(&LockArea, 0, sizeof(LockArea));
  21080. memset(&UnlockArea, 0, sizeof(UnlockArea));
  21081. LockArea.lOffset = 0L;
  21082. LockArea.lRange = 0L;
  21083. UnlockArea.lOffset = SHARED_FIRST;
  21084. UnlockArea.lRange = SHARED_SIZE;
  21085. res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
  21086. OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
  21087. return res;
  21088. }
  21089. /*
  21090. ** Lock the file with the lock specified by parameter locktype - one
  21091. ** of the following:
  21092. **
  21093. ** (1) SHARED_LOCK
  21094. ** (2) RESERVED_LOCK
  21095. ** (3) PENDING_LOCK
  21096. ** (4) EXCLUSIVE_LOCK
  21097. **
  21098. ** Sometimes when requesting one lock state, additional lock states
  21099. ** are inserted in between. The locking might fail on one of the later
  21100. ** transitions leaving the lock state different from what it started but
  21101. ** still short of its goal. The following chart shows the allowed
  21102. ** transitions and the inserted intermediate states:
  21103. **
  21104. ** UNLOCKED -> SHARED
  21105. ** SHARED -> RESERVED
  21106. ** SHARED -> (PENDING) -> EXCLUSIVE
  21107. ** RESERVED -> (PENDING) -> EXCLUSIVE
  21108. ** PENDING -> EXCLUSIVE
  21109. **
  21110. ** This routine will only increase a lock. The os2Unlock() routine
  21111. ** erases all locks at once and returns us immediately to locking level 0.
  21112. ** It is not possible to lower the locking level one step at a time. You
  21113. ** must go straight to locking level 0.
  21114. */
  21115. static int os2Lock( sqlite3_file *id, int locktype ){
  21116. int rc = SQLITE_OK; /* Return code from subroutines */
  21117. APIRET res = NO_ERROR; /* Result of an OS/2 lock call */
  21118. int newLocktype; /* Set pFile->locktype to this value before exiting */
  21119. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  21120. FILELOCK LockArea,
  21121. UnlockArea;
  21122. os2File *pFile = (os2File*)id;
  21123. memset(&LockArea, 0, sizeof(LockArea));
  21124. memset(&UnlockArea, 0, sizeof(UnlockArea));
  21125. assert( pFile!=0 );
  21126. OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
  21127. /* If there is already a lock of this type or more restrictive on the
  21128. ** os2File, do nothing. Don't use the end_lock: exit path, as
  21129. ** sqlite3_mutex_enter() hasn't been called yet.
  21130. */
  21131. if( pFile->locktype>=locktype ){
  21132. OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
  21133. return SQLITE_OK;
  21134. }
  21135. /* Make sure the locking sequence is correct
  21136. */
  21137. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  21138. assert( locktype!=PENDING_LOCK );
  21139. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  21140. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  21141. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  21142. ** the PENDING_LOCK byte is temporary.
  21143. */
  21144. newLocktype = pFile->locktype;
  21145. if( pFile->locktype==NO_LOCK
  21146. || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  21147. ){
  21148. LockArea.lOffset = PENDING_BYTE;
  21149. LockArea.lRange = 1L;
  21150. UnlockArea.lOffset = 0L;
  21151. UnlockArea.lRange = 0L;
  21152. /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
  21153. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
  21154. if( res == NO_ERROR ){
  21155. gotPendingLock = 1;
  21156. OSTRACE(( "LOCK %d pending lock boolean set. res=%d\n", pFile->h, res ));
  21157. }
  21158. }
  21159. /* Acquire a shared lock
  21160. */
  21161. if( locktype==SHARED_LOCK && res == NO_ERROR ){
  21162. assert( pFile->locktype==NO_LOCK );
  21163. res = getReadLock(pFile);
  21164. if( res == NO_ERROR ){
  21165. newLocktype = SHARED_LOCK;
  21166. }
  21167. OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
  21168. }
  21169. /* Acquire a RESERVED lock
  21170. */
  21171. if( locktype==RESERVED_LOCK && res == NO_ERROR ){
  21172. assert( pFile->locktype==SHARED_LOCK );
  21173. LockArea.lOffset = RESERVED_BYTE;
  21174. LockArea.lRange = 1L;
  21175. UnlockArea.lOffset = 0L;
  21176. UnlockArea.lRange = 0L;
  21177. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21178. if( res == NO_ERROR ){
  21179. newLocktype = RESERVED_LOCK;
  21180. }
  21181. OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
  21182. }
  21183. /* Acquire a PENDING lock
  21184. */
  21185. if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
  21186. newLocktype = PENDING_LOCK;
  21187. gotPendingLock = 0;
  21188. OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
  21189. pFile->h ));
  21190. }
  21191. /* Acquire an EXCLUSIVE lock
  21192. */
  21193. if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
  21194. assert( pFile->locktype>=SHARED_LOCK );
  21195. res = unlockReadLock(pFile);
  21196. OSTRACE(( "unreadlock = %d\n", res ));
  21197. LockArea.lOffset = SHARED_FIRST;
  21198. LockArea.lRange = SHARED_SIZE;
  21199. UnlockArea.lOffset = 0L;
  21200. UnlockArea.lRange = 0L;
  21201. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21202. if( res == NO_ERROR ){
  21203. newLocktype = EXCLUSIVE_LOCK;
  21204. }else{
  21205. OSTRACE(( "OS/2 error-code = %d\n", res ));
  21206. getReadLock(pFile);
  21207. }
  21208. OSTRACE(( "LOCK %d acquire exclusive lock. res=%d\n", pFile->h, res ));
  21209. }
  21210. /* If we are holding a PENDING lock that ought to be released, then
  21211. ** release it now.
  21212. */
  21213. if( gotPendingLock && locktype==SHARED_LOCK ){
  21214. int r;
  21215. LockArea.lOffset = 0L;
  21216. LockArea.lRange = 0L;
  21217. UnlockArea.lOffset = PENDING_BYTE;
  21218. UnlockArea.lRange = 1L;
  21219. r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21220. OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
  21221. }
  21222. /* Update the state of the lock has held in the file descriptor then
  21223. ** return the appropriate result code.
  21224. */
  21225. if( res == NO_ERROR ){
  21226. rc = SQLITE_OK;
  21227. }else{
  21228. OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  21229. locktype, newLocktype ));
  21230. rc = SQLITE_BUSY;
  21231. }
  21232. pFile->locktype = newLocktype;
  21233. OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
  21234. return rc;
  21235. }
  21236. /*
  21237. ** This routine checks if there is a RESERVED lock held on the specified
  21238. ** file by this or any other process. If such a lock is held, return
  21239. ** non-zero, otherwise zero.
  21240. */
  21241. static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
  21242. int r = 0;
  21243. os2File *pFile = (os2File*)id;
  21244. assert( pFile!=0 );
  21245. if( pFile->locktype>=RESERVED_LOCK ){
  21246. r = 1;
  21247. OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
  21248. }else{
  21249. FILELOCK LockArea,
  21250. UnlockArea;
  21251. APIRET rc = NO_ERROR;
  21252. memset(&LockArea, 0, sizeof(LockArea));
  21253. memset(&UnlockArea, 0, sizeof(UnlockArea));
  21254. LockArea.lOffset = RESERVED_BYTE;
  21255. LockArea.lRange = 1L;
  21256. UnlockArea.lOffset = 0L;
  21257. UnlockArea.lRange = 0L;
  21258. rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21259. OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
  21260. if( rc == NO_ERROR ){
  21261. APIRET rcu = NO_ERROR; /* return code for unlocking */
  21262. LockArea.lOffset = 0L;
  21263. LockArea.lRange = 0L;
  21264. UnlockArea.lOffset = RESERVED_BYTE;
  21265. UnlockArea.lRange = 1L;
  21266. rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21267. OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
  21268. }
  21269. r = !(rc == NO_ERROR);
  21270. OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
  21271. }
  21272. *pOut = r;
  21273. return SQLITE_OK;
  21274. }
  21275. /*
  21276. ** Lower the locking level on file descriptor id to locktype. locktype
  21277. ** must be either NO_LOCK or SHARED_LOCK.
  21278. **
  21279. ** If the locking level of the file descriptor is already at or below
  21280. ** the requested locking level, this routine is a no-op.
  21281. **
  21282. ** It is not possible for this routine to fail if the second argument
  21283. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  21284. ** might return SQLITE_IOERR;
  21285. */
  21286. static int os2Unlock( sqlite3_file *id, int locktype ){
  21287. int type;
  21288. os2File *pFile = (os2File*)id;
  21289. APIRET rc = SQLITE_OK;
  21290. APIRET res = NO_ERROR;
  21291. FILELOCK LockArea,
  21292. UnlockArea;
  21293. memset(&LockArea, 0, sizeof(LockArea));
  21294. memset(&UnlockArea, 0, sizeof(UnlockArea));
  21295. assert( pFile!=0 );
  21296. assert( locktype<=SHARED_LOCK );
  21297. OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
  21298. type = pFile->locktype;
  21299. if( type>=EXCLUSIVE_LOCK ){
  21300. LockArea.lOffset = 0L;
  21301. LockArea.lRange = 0L;
  21302. UnlockArea.lOffset = SHARED_FIRST;
  21303. UnlockArea.lRange = SHARED_SIZE;
  21304. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21305. OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
  21306. if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
  21307. /* This should never happen. We should always be able to
  21308. ** reacquire the read lock */
  21309. OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
  21310. rc = SQLITE_IOERR_UNLOCK;
  21311. }
  21312. }
  21313. if( type>=RESERVED_LOCK ){
  21314. LockArea.lOffset = 0L;
  21315. LockArea.lRange = 0L;
  21316. UnlockArea.lOffset = RESERVED_BYTE;
  21317. UnlockArea.lRange = 1L;
  21318. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21319. OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
  21320. }
  21321. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  21322. res = unlockReadLock(pFile);
  21323. OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
  21324. pFile->h, type, locktype, res ));
  21325. }
  21326. if( type>=PENDING_LOCK ){
  21327. LockArea.lOffset = 0L;
  21328. LockArea.lRange = 0L;
  21329. UnlockArea.lOffset = PENDING_BYTE;
  21330. UnlockArea.lRange = 1L;
  21331. res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
  21332. OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
  21333. }
  21334. pFile->locktype = locktype;
  21335. OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
  21336. return rc;
  21337. }
  21338. /*
  21339. ** Control and query of the open file handle.
  21340. */
  21341. static int os2FileControl(sqlite3_file *id, int op, void *pArg){
  21342. switch( op ){
  21343. case SQLITE_FCNTL_LOCKSTATE: {
  21344. *(int*)pArg = ((os2File*)id)->locktype;
  21345. OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
  21346. ((os2File*)id)->h, ((os2File*)id)->locktype ));
  21347. return SQLITE_OK;
  21348. }
  21349. case SQLITE_FCNTL_CHUNK_SIZE: {
  21350. ((os2File*)id)->szChunk = *(int*)pArg;
  21351. return SQLITE_OK;
  21352. }
  21353. case SQLITE_FCNTL_SIZE_HINT: {
  21354. sqlite3_int64 sz = *(sqlite3_int64*)pArg;
  21355. SimulateIOErrorBenign(1);
  21356. os2Truncate(id, sz);
  21357. SimulateIOErrorBenign(0);
  21358. return SQLITE_OK;
  21359. }
  21360. case SQLITE_FCNTL_SYNC_OMITTED: {
  21361. return SQLITE_OK;
  21362. }
  21363. }
  21364. return SQLITE_NOTFOUND;
  21365. }
  21366. /*
  21367. ** Return the sector size in bytes of the underlying block device for
  21368. ** the specified file. This is almost always 512 bytes, but may be
  21369. ** larger for some devices.
  21370. **
  21371. ** SQLite code assumes this function cannot fail. It also assumes that
  21372. ** if two files are created in the same file-system directory (i.e.
  21373. ** a database and its journal file) that the sector size will be the
  21374. ** same for both.
  21375. */
  21376. static int os2SectorSize(sqlite3_file *id){
  21377. UNUSED_PARAMETER(id);
  21378. return SQLITE_DEFAULT_SECTOR_SIZE;
  21379. }
  21380. /*
  21381. ** Return a vector of device characteristics.
  21382. */
  21383. static int os2DeviceCharacteristics(sqlite3_file *id){
  21384. UNUSED_PARAMETER(id);
  21385. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
  21386. }
  21387. /*
  21388. ** Character set conversion objects used by conversion routines.
  21389. */
  21390. static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
  21391. static UconvObject uclCp = NULL; /* convert between local codepage and UCS-2 */
  21392. /*
  21393. ** Helper function to initialize the conversion objects from and to UTF-8.
  21394. */
  21395. static void initUconvObjects( void ){
  21396. if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
  21397. ucUtf8 = NULL;
  21398. if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
  21399. uclCp = NULL;
  21400. }
  21401. /*
  21402. ** Helper function to free the conversion objects from and to UTF-8.
  21403. */
  21404. static void freeUconvObjects( void ){
  21405. if ( ucUtf8 )
  21406. UniFreeUconvObject( ucUtf8 );
  21407. if ( uclCp )
  21408. UniFreeUconvObject( uclCp );
  21409. ucUtf8 = NULL;
  21410. uclCp = NULL;
  21411. }
  21412. /*
  21413. ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
  21414. ** The two-step process: first convert the incoming UTF-8 string
  21415. ** into UCS-2 and then from UCS-2 to the current codepage.
  21416. ** The returned char pointer has to be freed.
  21417. */
  21418. static char *convertUtf8PathToCp( const char *in ){
  21419. UniChar tempPath[CCHMAXPATH];
  21420. char *out = (char *)calloc( CCHMAXPATH, 1 );
  21421. if( !out )
  21422. return NULL;
  21423. if( !ucUtf8 || !uclCp )
  21424. initUconvObjects();
  21425. /* determine string for the conversion of UTF-8 which is CP1208 */
  21426. if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
  21427. return out; /* if conversion fails, return the empty string */
  21428. /* conversion for current codepage which can be used for paths */
  21429. UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
  21430. return out;
  21431. }
  21432. /*
  21433. ** Helper function to convert filenames from local codepage to UTF-8.
  21434. ** The two-step process: first convert the incoming codepage-specific
  21435. ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
  21436. ** The returned char pointer has to be freed.
  21437. **
  21438. ** This function is non-static to be able to use this in shell.c and
  21439. ** similar applications that take command line arguments.
  21440. */
  21441. char *convertCpPathToUtf8( const char *in ){
  21442. UniChar tempPath[CCHMAXPATH];
  21443. char *out = (char *)calloc( CCHMAXPATH, 1 );
  21444. if( !out )
  21445. return NULL;
  21446. if( !ucUtf8 || !uclCp )
  21447. initUconvObjects();
  21448. /* conversion for current codepage which can be used for paths */
  21449. if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
  21450. return out; /* if conversion fails, return the empty string */
  21451. /* determine string for the conversion of UTF-8 which is CP1208 */
  21452. UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
  21453. return out;
  21454. }
  21455. #ifndef SQLITE_OMIT_WAL
  21456. /*
  21457. ** Use main database file for interprocess locking. If un-defined
  21458. ** a separate file is created for this purpose. The file will be
  21459. ** used only to set file locks. There will be no data written to it.
  21460. */
  21461. #define SQLITE_OS2_NO_WAL_LOCK_FILE
  21462. #if 0
  21463. static void _ERR_TRACE( const char *fmt, ... ) {
  21464. va_list ap;
  21465. va_start(ap, fmt);
  21466. vfprintf(stderr, fmt, ap);
  21467. fflush(stderr);
  21468. }
  21469. #define ERR_TRACE(rc, msg) \
  21470. if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
  21471. #else
  21472. #define ERR_TRACE(rc, msg)
  21473. #endif
  21474. /*
  21475. ** Helper functions to obtain and relinquish the global mutex. The
  21476. ** global mutex is used to protect os2ShmNodeList.
  21477. **
  21478. ** Function os2ShmMutexHeld() is used to assert() that the global mutex
  21479. ** is held when required. This function is only used as part of assert()
  21480. ** statements. e.g.
  21481. **
  21482. ** os2ShmEnterMutex()
  21483. ** assert( os2ShmMutexHeld() );
  21484. ** os2ShmLeaveMutex()
  21485. */
  21486. static void os2ShmEnterMutex(void){
  21487. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21488. }
  21489. static void os2ShmLeaveMutex(void){
  21490. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21491. }
  21492. #ifdef SQLITE_DEBUG
  21493. static int os2ShmMutexHeld(void) {
  21494. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21495. }
  21496. int GetCurrentProcessId(void) {
  21497. PPIB pib;
  21498. DosGetInfoBlocks(NULL, &pib);
  21499. return (int)pib->pib_ulpid;
  21500. }
  21501. #endif
  21502. /*
  21503. ** Object used to represent a the shared memory area for a single log file.
  21504. ** When multiple threads all reference the same log-summary, each thread has
  21505. ** its own os2File object, but they all point to a single instance of this
  21506. ** object. In other words, each log-summary is opened only once per process.
  21507. **
  21508. ** os2ShmMutexHeld() must be true when creating or destroying
  21509. ** this object or while reading or writing the following fields:
  21510. **
  21511. ** nRef
  21512. ** pNext
  21513. **
  21514. ** The following fields are read-only after the object is created:
  21515. **
  21516. ** szRegion
  21517. ** hLockFile
  21518. ** shmBaseName
  21519. **
  21520. ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
  21521. ** os2ShmMutexHeld() is true when reading or writing any other field
  21522. ** in this structure.
  21523. **
  21524. */
  21525. struct os2ShmNode {
  21526. sqlite3_mutex *mutex; /* Mutex to access this object */
  21527. os2ShmNode *pNext; /* Next in list of all os2ShmNode objects */
  21528. int szRegion; /* Size of shared-memory regions */
  21529. int nRegion; /* Size of array apRegion */
  21530. void **apRegion; /* Array of pointers to shared-memory regions */
  21531. int nRef; /* Number of os2ShmLink objects pointing to this */
  21532. os2ShmLink *pFirst; /* First os2ShmLink object pointing to this */
  21533. HFILE hLockFile; /* File used for inter-process memory locking */
  21534. char shmBaseName[1]; /* Name of the memory object !!! must last !!! */
  21535. };
  21536. /*
  21537. ** Structure used internally by this VFS to record the state of an
  21538. ** open shared memory connection.
  21539. **
  21540. ** The following fields are initialized when this object is created and
  21541. ** are read-only thereafter:
  21542. **
  21543. ** os2Shm.pShmNode
  21544. ** os2Shm.id
  21545. **
  21546. ** All other fields are read/write. The os2Shm.pShmNode->mutex must be held
  21547. ** while accessing any read/write fields.
  21548. */
  21549. struct os2ShmLink {
  21550. os2ShmNode *pShmNode; /* The underlying os2ShmNode object */
  21551. os2ShmLink *pNext; /* Next os2Shm with the same os2ShmNode */
  21552. u32 sharedMask; /* Mask of shared locks held */
  21553. u32 exclMask; /* Mask of exclusive locks held */
  21554. #ifdef SQLITE_DEBUG
  21555. u8 id; /* Id of this connection with its os2ShmNode */
  21556. #endif
  21557. };
  21558. /*
  21559. ** A global list of all os2ShmNode objects.
  21560. **
  21561. ** The os2ShmMutexHeld() must be true while reading or writing this list.
  21562. */
  21563. static os2ShmNode *os2ShmNodeList = NULL;
  21564. /*
  21565. ** Constants used for locking
  21566. */
  21567. #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
  21568. #define OS2_SHM_BASE (PENDING_BYTE + 0x10000) /* first lock byte */
  21569. #else
  21570. #define OS2_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  21571. #endif
  21572. #define OS2_SHM_DMS (OS2_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  21573. /*
  21574. ** Apply advisory locks for all n bytes beginning at ofst.
  21575. */
  21576. #define _SHM_UNLCK 1 /* no lock */
  21577. #define _SHM_RDLCK 2 /* shared lock, no wait */
  21578. #define _SHM_WRLCK 3 /* exlusive lock, no wait */
  21579. #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
  21580. static int os2ShmSystemLock(
  21581. os2ShmNode *pNode, /* Apply locks to this open shared-memory segment */
  21582. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
  21583. int ofst, /* Offset to first byte to be locked/unlocked */
  21584. int nByte /* Number of bytes to lock or unlock */
  21585. ){
  21586. APIRET rc;
  21587. FILELOCK area;
  21588. ULONG mode, timeout;
  21589. /* Access to the os2ShmNode object is serialized by the caller */
  21590. assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
  21591. mode = 1; /* shared lock */
  21592. timeout = 0; /* no wait */
  21593. area.lOffset = ofst;
  21594. area.lRange = nByte;
  21595. switch( lockType ) {
  21596. case _SHM_WRLCK_WAIT:
  21597. timeout = (ULONG)-1; /* wait forever */
  21598. case _SHM_WRLCK:
  21599. mode = 0; /* exclusive lock */
  21600. case _SHM_RDLCK:
  21601. rc = DosSetFileLocks(pNode->hLockFile,
  21602. NULL, &area, timeout, mode);
  21603. break;
  21604. /* case _SHM_UNLCK: */
  21605. default:
  21606. rc = DosSetFileLocks(pNode->hLockFile,
  21607. &area, NULL, 0, 0);
  21608. break;
  21609. }
  21610. OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
  21611. pNode->hLockFile,
  21612. rc==SQLITE_OK ? "ok" : "failed",
  21613. lockType==_SHM_UNLCK ? "Unlock" : "Lock",
  21614. rc));
  21615. ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
  21616. return ( rc == 0 ) ? SQLITE_OK : SQLITE_BUSY;
  21617. }
  21618. /*
  21619. ** Find an os2ShmNode in global list or allocate a new one, if not found.
  21620. **
  21621. ** This is not a VFS shared-memory method; it is a utility function called
  21622. ** by VFS shared-memory methods.
  21623. */
  21624. static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
  21625. os2ShmLink *pLink;
  21626. os2ShmNode *pNode;
  21627. int cbShmName, rc = SQLITE_OK;
  21628. char shmName[CCHMAXPATH + 30];
  21629. #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
  21630. ULONG action;
  21631. #endif
  21632. /* We need some additional space at the end to append the region number */
  21633. cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
  21634. if( cbShmName >= CCHMAXPATH-8 )
  21635. return SQLITE_IOERR_SHMOPEN;
  21636. /* Replace colon in file name to form a valid shared memory name */
  21637. shmName[10+1] = '!';
  21638. /* Allocate link object (we free it later in case of failure) */
  21639. pLink = sqlite3_malloc( sizeof(*pLink) );
  21640. if( !pLink )
  21641. return SQLITE_NOMEM;
  21642. /* Access node list */
  21643. os2ShmEnterMutex();
  21644. /* Find node by it's shared memory base name */
  21645. for( pNode = os2ShmNodeList;
  21646. pNode && stricmp(shmName, pNode->shmBaseName) != 0;
  21647. pNode = pNode->pNext ) ;
  21648. /* Not found: allocate a new node */
  21649. if( !pNode ) {
  21650. pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
  21651. if( pNode ) {
  21652. memset(pNode, 0, sizeof(*pNode) );
  21653. pNode->szRegion = szRegion;
  21654. pNode->hLockFile = (HFILE)-1;
  21655. strcpy(pNode->shmBaseName, shmName);
  21656. #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
  21657. if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
  21658. #else
  21659. sprintf(shmName, "%s-lck", fd->zFullPathCp);
  21660. if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
  21661. OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
  21662. OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
  21663. OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
  21664. NULL) != 0 ) {
  21665. #endif
  21666. sqlite3_free(pNode);
  21667. rc = SQLITE_IOERR;
  21668. } else {
  21669. pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  21670. if( !pNode->mutex ) {
  21671. sqlite3_free(pNode);
  21672. rc = SQLITE_NOMEM;
  21673. }
  21674. }
  21675. } else {
  21676. rc = SQLITE_NOMEM;
  21677. }
  21678. if( rc == SQLITE_OK ) {
  21679. pNode->pNext = os2ShmNodeList;
  21680. os2ShmNodeList = pNode;
  21681. } else {
  21682. pNode = NULL;
  21683. }
  21684. } else if( pNode->szRegion != szRegion ) {
  21685. rc = SQLITE_IOERR_SHMSIZE;
  21686. pNode = NULL;
  21687. }
  21688. if( pNode ) {
  21689. sqlite3_mutex_enter(pNode->mutex);
  21690. memset(pLink, 0, sizeof(*pLink));
  21691. pLink->pShmNode = pNode;
  21692. pLink->pNext = pNode->pFirst;
  21693. pNode->pFirst = pLink;
  21694. pNode->nRef++;
  21695. fd->pShmLink = pLink;
  21696. sqlite3_mutex_leave(pNode->mutex);
  21697. } else {
  21698. /* Error occured. Free our link object. */
  21699. sqlite3_free(pLink);
  21700. }
  21701. os2ShmLeaveMutex();
  21702. ERR_TRACE(rc, ("os2OpenSharedMemory: %d %s\n", rc, fd->zFullPathCp))
  21703. return rc;
  21704. }
  21705. /*
  21706. ** Purge the os2ShmNodeList list of all entries with nRef==0.
  21707. **
  21708. ** This is not a VFS shared-memory method; it is a utility function called
  21709. ** by VFS shared-memory methods.
  21710. */
  21711. static void os2PurgeShmNodes( int deleteFlag ) {
  21712. os2ShmNode *pNode;
  21713. os2ShmNode **ppNode;
  21714. os2ShmEnterMutex();
  21715. ppNode = &os2ShmNodeList;
  21716. while( *ppNode ) {
  21717. pNode = *ppNode;
  21718. if( pNode->nRef == 0 ) {
  21719. *ppNode = pNode->pNext;
  21720. if( pNode->apRegion ) {
  21721. /* Prevent other processes from resizing the shared memory */
  21722. os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
  21723. while( pNode->nRegion-- ) {
  21724. #ifdef SQLITE_DEBUG
  21725. int rc =
  21726. #endif
  21727. DosFreeMem(pNode->apRegion[pNode->nRegion]);
  21728. OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
  21729. (int)GetCurrentProcessId(), pNode->nRegion,
  21730. rc == 0 ? "ok" : "failed"));
  21731. }
  21732. /* Allow other processes to resize the shared memory */
  21733. os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
  21734. sqlite3_free(pNode->apRegion);
  21735. }
  21736. DosClose(pNode->hLockFile);
  21737. #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
  21738. if( deleteFlag ) {
  21739. char fileName[CCHMAXPATH];
  21740. /* Skip "\\SHAREMEM\\" */
  21741. sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
  21742. /* restore colon */
  21743. fileName[1] = ':';
  21744. DosForceDelete(fileName);
  21745. }
  21746. #endif
  21747. sqlite3_mutex_free(pNode->mutex);
  21748. sqlite3_free(pNode);
  21749. } else {
  21750. ppNode = &pNode->pNext;
  21751. }
  21752. }
  21753. os2ShmLeaveMutex();
  21754. }
  21755. /*
  21756. ** This function is called to obtain a pointer to region iRegion of the
  21757. ** shared-memory associated with the database file id. Shared-memory regions
  21758. ** are numbered starting from zero. Each shared-memory region is szRegion
  21759. ** bytes in size.
  21760. **
  21761. ** If an error occurs, an error code is returned and *pp is set to NULL.
  21762. **
  21763. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  21764. ** region has not been allocated (by any client, including one running in a
  21765. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  21766. ** bExtend is non-zero and the requested shared-memory region has not yet
  21767. ** been allocated, it is allocated by this function.
  21768. **
  21769. ** If the shared-memory region has already been allocated or is allocated by
  21770. ** this call as described above, then it is mapped into this processes
  21771. ** address space (if it is not already), *pp is set to point to the mapped
  21772. ** memory and SQLITE_OK returned.
  21773. */
  21774. static int os2ShmMap(
  21775. sqlite3_file *id, /* Handle open on database file */
  21776. int iRegion, /* Region to retrieve */
  21777. int szRegion, /* Size of regions */
  21778. int bExtend, /* True to extend block if necessary */
  21779. void volatile **pp /* OUT: Mapped memory */
  21780. ){
  21781. PVOID pvTemp;
  21782. void **apRegion;
  21783. os2ShmNode *pNode;
  21784. int n, rc = SQLITE_OK;
  21785. char shmName[CCHMAXPATH];
  21786. os2File *pFile = (os2File*)id;
  21787. *pp = NULL;
  21788. if( !pFile->pShmLink )
  21789. rc = os2OpenSharedMemory( pFile, szRegion );
  21790. if( rc == SQLITE_OK ) {
  21791. pNode = pFile->pShmLink->pShmNode ;
  21792. sqlite3_mutex_enter(pNode->mutex);
  21793. assert( szRegion==pNode->szRegion );
  21794. /* Unmapped region ? */
  21795. if( iRegion >= pNode->nRegion ) {
  21796. /* Prevent other processes from resizing the shared memory */
  21797. os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
  21798. apRegion = sqlite3_realloc(
  21799. pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
  21800. if( apRegion ) {
  21801. pNode->apRegion = apRegion;
  21802. while( pNode->nRegion <= iRegion ) {
  21803. sprintf(shmName, "%s-%u",
  21804. pNode->shmBaseName, pNode->nRegion);
  21805. if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
  21806. PAG_READ | PAG_WRITE) != NO_ERROR ) {
  21807. if( !bExtend )
  21808. break;
  21809. if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
  21810. PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
  21811. DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
  21812. PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
  21813. rc = SQLITE_NOMEM;
  21814. break;
  21815. }
  21816. }
  21817. apRegion[pNode->nRegion++] = pvTemp;
  21818. }
  21819. /* zero out remaining entries */
  21820. for( n = pNode->nRegion; n <= iRegion; n++ )
  21821. pNode->apRegion[n] = NULL;
  21822. /* Return this region (maybe zero) */
  21823. *pp = pNode->apRegion[iRegion];
  21824. } else {
  21825. rc = SQLITE_NOMEM;
  21826. }
  21827. /* Allow other processes to resize the shared memory */
  21828. os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
  21829. } else {
  21830. /* Region has been mapped previously */
  21831. *pp = pNode->apRegion[iRegion];
  21832. }
  21833. sqlite3_mutex_leave(pNode->mutex);
  21834. }
  21835. ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
  21836. pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
  21837. return rc;
  21838. }
  21839. /*
  21840. ** Close a connection to shared-memory. Delete the underlying
  21841. ** storage if deleteFlag is true.
  21842. **
  21843. ** If there is no shared memory associated with the connection then this
  21844. ** routine is a harmless no-op.
  21845. */
  21846. static int os2ShmUnmap(
  21847. sqlite3_file *id, /* The underlying database file */
  21848. int deleteFlag /* Delete shared-memory if true */
  21849. ){
  21850. os2File *pFile = (os2File*)id;
  21851. os2ShmLink *pLink = pFile->pShmLink;
  21852. if( pLink ) {
  21853. int nRef = -1;
  21854. os2ShmLink **ppLink;
  21855. os2ShmNode *pNode = pLink->pShmNode;
  21856. sqlite3_mutex_enter(pNode->mutex);
  21857. for( ppLink = &pNode->pFirst;
  21858. *ppLink && *ppLink != pLink;
  21859. ppLink = &(*ppLink)->pNext ) ;
  21860. assert(*ppLink);
  21861. if( *ppLink ) {
  21862. *ppLink = pLink->pNext;
  21863. nRef = --pNode->nRef;
  21864. } else {
  21865. ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
  21866. pNode->shmBaseName))
  21867. }
  21868. pFile->pShmLink = NULL;
  21869. sqlite3_free(pLink);
  21870. sqlite3_mutex_leave(pNode->mutex);
  21871. if( nRef == 0 )
  21872. os2PurgeShmNodes( deleteFlag );
  21873. }
  21874. return SQLITE_OK;
  21875. }
  21876. /*
  21877. ** Change the lock state for a shared-memory segment.
  21878. **
  21879. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  21880. ** different here than in posix. In xShmLock(), one can go from unlocked
  21881. ** to shared and back or from unlocked to exclusive and back. But one may
  21882. ** not go from shared to exclusive or from exclusive to shared.
  21883. */
  21884. static int os2ShmLock(
  21885. sqlite3_file *id, /* Database file holding the shared memory */
  21886. int ofst, /* First lock to acquire or release */
  21887. int n, /* Number of locks to acquire or release */
  21888. int flags /* What to do with the lock */
  21889. ){
  21890. u32 mask; /* Mask of locks to take or release */
  21891. int rc = SQLITE_OK; /* Result code */
  21892. os2File *pFile = (os2File*)id;
  21893. os2ShmLink *p = pFile->pShmLink; /* The shared memory being locked */
  21894. os2ShmLink *pX; /* For looping over all siblings */
  21895. os2ShmNode *pShmNode = p->pShmNode; /* Our node */
  21896. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  21897. assert( n>=1 );
  21898. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  21899. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  21900. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  21901. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  21902. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  21903. mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
  21904. assert( n>1 || mask==(1<<ofst) );
  21905. sqlite3_mutex_enter(pShmNode->mutex);
  21906. if( flags & SQLITE_SHM_UNLOCK ){
  21907. u32 allMask = 0; /* Mask of locks held by siblings */
  21908. /* See if any siblings hold this same lock */
  21909. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  21910. if( pX==p ) continue;
  21911. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  21912. allMask |= pX->sharedMask;
  21913. }
  21914. /* Unlock the system-level locks */
  21915. if( (mask & allMask)==0 ){
  21916. rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
  21917. }else{
  21918. rc = SQLITE_OK;
  21919. }
  21920. /* Undo the local locks */
  21921. if( rc==SQLITE_OK ){
  21922. p->exclMask &= ~mask;
  21923. p->sharedMask &= ~mask;
  21924. }
  21925. }else if( flags & SQLITE_SHM_SHARED ){
  21926. u32 allShared = 0; /* Union of locks held by connections other than "p" */
  21927. /* Find out which shared locks are already held by sibling connections.
  21928. ** If any sibling already holds an exclusive lock, go ahead and return
  21929. ** SQLITE_BUSY.
  21930. */
  21931. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  21932. if( (pX->exclMask & mask)!=0 ){
  21933. rc = SQLITE_BUSY;
  21934. break;
  21935. }
  21936. allShared |= pX->sharedMask;
  21937. }
  21938. /* Get shared locks at the system level, if necessary */
  21939. if( rc==SQLITE_OK ){
  21940. if( (allShared & mask)==0 ){
  21941. rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
  21942. }else{
  21943. rc = SQLITE_OK;
  21944. }
  21945. }
  21946. /* Get the local shared locks */
  21947. if( rc==SQLITE_OK ){
  21948. p->sharedMask |= mask;
  21949. }
  21950. }else{
  21951. /* Make sure no sibling connections hold locks that will block this
  21952. ** lock. If any do, return SQLITE_BUSY right away.
  21953. */
  21954. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  21955. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  21956. rc = SQLITE_BUSY;
  21957. break;
  21958. }
  21959. }
  21960. /* Get the exclusive locks at the system level. Then if successful
  21961. ** also mark the local connection as being locked.
  21962. */
  21963. if( rc==SQLITE_OK ){
  21964. rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
  21965. if( rc==SQLITE_OK ){
  21966. assert( (p->sharedMask & mask)==0 );
  21967. p->exclMask |= mask;
  21968. }
  21969. }
  21970. }
  21971. sqlite3_mutex_leave(pShmNode->mutex);
  21972. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
  21973. p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
  21974. rc ? "failed" : "ok"));
  21975. ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
  21976. ofst, n, flags, rc))
  21977. return rc;
  21978. }
  21979. /*
  21980. ** Implement a memory barrier or memory fence on shared memory.
  21981. **
  21982. ** All loads and stores begun before the barrier must complete before
  21983. ** any load or store begun after the barrier.
  21984. */
  21985. static void os2ShmBarrier(
  21986. sqlite3_file *id /* Database file holding the shared memory */
  21987. ){
  21988. UNUSED_PARAMETER(id);
  21989. os2ShmEnterMutex();
  21990. os2ShmLeaveMutex();
  21991. }
  21992. #else
  21993. # define os2ShmMap 0
  21994. # define os2ShmLock 0
  21995. # define os2ShmBarrier 0
  21996. # define os2ShmUnmap 0
  21997. #endif /* #ifndef SQLITE_OMIT_WAL */
  21998. /*
  21999. ** This vector defines all the methods that can operate on an
  22000. ** sqlite3_file for os2.
  22001. */
  22002. static const sqlite3_io_methods os2IoMethod = {
  22003. 2, /* iVersion */
  22004. os2Close, /* xClose */
  22005. os2Read, /* xRead */
  22006. os2Write, /* xWrite */
  22007. os2Truncate, /* xTruncate */
  22008. os2Sync, /* xSync */
  22009. os2FileSize, /* xFileSize */
  22010. os2Lock, /* xLock */
  22011. os2Unlock, /* xUnlock */
  22012. os2CheckReservedLock, /* xCheckReservedLock */
  22013. os2FileControl, /* xFileControl */
  22014. os2SectorSize, /* xSectorSize */
  22015. os2DeviceCharacteristics, /* xDeviceCharacteristics */
  22016. os2ShmMap, /* xShmMap */
  22017. os2ShmLock, /* xShmLock */
  22018. os2ShmBarrier, /* xShmBarrier */
  22019. os2ShmUnmap /* xShmUnmap */
  22020. };
  22021. /***************************************************************************
  22022. ** Here ends the I/O methods that form the sqlite3_io_methods object.
  22023. **
  22024. ** The next block of code implements the VFS methods.
  22025. ****************************************************************************/
  22026. /*
  22027. ** Create a temporary file name in zBuf. zBuf must be big enough to
  22028. ** hold at pVfs->mxPathname characters.
  22029. */
  22030. static int getTempname(int nBuf, char *zBuf ){
  22031. static const char zChars[] =
  22032. "abcdefghijklmnopqrstuvwxyz"
  22033. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  22034. "0123456789";
  22035. int i, j;
  22036. PSZ zTempPathCp;
  22037. char zTempPath[CCHMAXPATH];
  22038. ULONG ulDriveNum, ulDriveMap;
  22039. /* It's odd to simulate an io-error here, but really this is just
  22040. ** using the io-error infrastructure to test that SQLite handles this
  22041. ** function failing.
  22042. */
  22043. SimulateIOError( return SQLITE_IOERR );
  22044. if( sqlite3_temp_directory ) {
  22045. sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
  22046. } else if( DosScanEnv( (PSZ)"TEMP", &zTempPathCp ) == NO_ERROR ||
  22047. DosScanEnv( (PSZ)"TMP", &zTempPathCp ) == NO_ERROR ||
  22048. DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
  22049. char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
  22050. sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
  22051. free( zTempPathUTF );
  22052. } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
  22053. zTempPath[0] = (char)('A' + ulDriveNum - 1);
  22054. zTempPath[1] = ':';
  22055. zTempPath[2] = '\0';
  22056. } else {
  22057. zTempPath[0] = '\0';
  22058. }
  22059. /* Strip off a trailing slashes or backslashes, otherwise we would get *
  22060. * multiple (back)slashes which causes DosOpen() to fail. *
  22061. * Trailing spaces are not allowed, either. */
  22062. j = sqlite3Strlen30(zTempPath);
  22063. while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
  22064. zTempPath[j-1] == ' ' ) ){
  22065. j--;
  22066. }
  22067. zTempPath[j] = '\0';
  22068. /* We use 20 bytes to randomize the name */
  22069. sqlite3_snprintf(nBuf-22, zBuf,
  22070. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
  22071. j = sqlite3Strlen30(zBuf);
  22072. sqlite3_randomness( 20, &zBuf[j] );
  22073. for( i = 0; i < 20; i++, j++ ){
  22074. zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  22075. }
  22076. zBuf[j] = 0;
  22077. OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
  22078. return SQLITE_OK;
  22079. }
  22080. /*
  22081. ** Turn a relative pathname into a full pathname. Write the full
  22082. ** pathname into zFull[]. zFull[] will be at least pVfs->mxPathname
  22083. ** bytes in size.
  22084. */
  22085. static int os2FullPathname(
  22086. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  22087. const char *zRelative, /* Possibly relative input path */
  22088. int nFull, /* Size of output buffer in bytes */
  22089. char *zFull /* Output buffer */
  22090. ){
  22091. char *zRelativeCp = convertUtf8PathToCp( zRelative );
  22092. char zFullCp[CCHMAXPATH] = "\0";
  22093. char *zFullUTF;
  22094. APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
  22095. zFullCp, CCHMAXPATH );
  22096. free( zRelativeCp );
  22097. zFullUTF = convertCpPathToUtf8( zFullCp );
  22098. sqlite3_snprintf( nFull, zFull, zFullUTF );
  22099. free( zFullUTF );
  22100. return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
  22101. }
  22102. /*
  22103. ** Open a file.
  22104. */
  22105. static int os2Open(
  22106. sqlite3_vfs *pVfs, /* Not used */
  22107. const char *zName, /* Name of the file (UTF-8) */
  22108. sqlite3_file *id, /* Write the SQLite file handle here */
  22109. int flags, /* Open mode flags */
  22110. int *pOutFlags /* Status return flags */
  22111. ){
  22112. HFILE h;
  22113. ULONG ulOpenFlags = 0;
  22114. ULONG ulOpenMode = 0;
  22115. ULONG ulAction = 0;
  22116. ULONG rc;
  22117. os2File *pFile = (os2File*)id;
  22118. const char *zUtf8Name = zName;
  22119. char *zNameCp;
  22120. char zTmpname[CCHMAXPATH];
  22121. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  22122. int isCreate = (flags & SQLITE_OPEN_CREATE);
  22123. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  22124. #ifndef NDEBUG
  22125. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  22126. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  22127. int eType = (flags & 0xFFFFFF00);
  22128. int isOpenJournal = (isCreate && (
  22129. eType==SQLITE_OPEN_MASTER_JOURNAL
  22130. || eType==SQLITE_OPEN_MAIN_JOURNAL
  22131. || eType==SQLITE_OPEN_WAL
  22132. ));
  22133. #endif
  22134. UNUSED_PARAMETER(pVfs);
  22135. assert( id!=0 );
  22136. /* Check the following statements are true:
  22137. **
  22138. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  22139. ** (b) if CREATE is set, then READWRITE must also be set, and
  22140. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  22141. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  22142. */
  22143. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  22144. assert(isCreate==0 || isReadWrite);
  22145. assert(isExclusive==0 || isCreate);
  22146. assert(isDelete==0 || isCreate);
  22147. /* The main DB, main journal, WAL file and master journal are never
  22148. ** automatically deleted. Nor are they ever temporary files. */
  22149. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  22150. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  22151. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  22152. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  22153. /* Assert that the upper layer has set one of the "file-type" flags. */
  22154. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  22155. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  22156. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  22157. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  22158. );
  22159. memset( pFile, 0, sizeof(*pFile) );
  22160. pFile->h = (HFILE)-1;
  22161. /* If the second argument to this function is NULL, generate a
  22162. ** temporary file name to use
  22163. */
  22164. if( !zUtf8Name ){
  22165. assert(isDelete && !isOpenJournal);
  22166. rc = getTempname(CCHMAXPATH, zTmpname);
  22167. if( rc!=SQLITE_OK ){
  22168. return rc;
  22169. }
  22170. zUtf8Name = zTmpname;
  22171. }
  22172. if( isReadWrite ){
  22173. ulOpenMode |= OPEN_ACCESS_READWRITE;
  22174. }else{
  22175. ulOpenMode |= OPEN_ACCESS_READONLY;
  22176. }
  22177. /* Open in random access mode for possibly better speed. Allow full
  22178. ** sharing because file locks will provide exclusive access when needed.
  22179. ** The handle should not be inherited by child processes and we don't
  22180. ** want popups from the critical error handler.
  22181. */
  22182. ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
  22183. OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
  22184. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  22185. ** created. SQLite doesn't use it to indicate "exclusive access"
  22186. ** as it is usually understood.
  22187. */
  22188. if( isExclusive ){
  22189. /* Creates a new file, only if it does not already exist. */
  22190. /* If the file exists, it fails. */
  22191. ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
  22192. }else if( isCreate ){
  22193. /* Open existing file, or create if it doesn't exist */
  22194. ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
  22195. }else{
  22196. /* Opens a file, only if it exists. */
  22197. ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
  22198. }
  22199. zNameCp = convertUtf8PathToCp( zUtf8Name );
  22200. rc = DosOpen( (PSZ)zNameCp,
  22201. &h,
  22202. &ulAction,
  22203. 0L,
  22204. FILE_NORMAL,
  22205. ulOpenFlags,
  22206. ulOpenMode,
  22207. (PEAOP2)NULL );
  22208. free( zNameCp );
  22209. if( rc != NO_ERROR ){
  22210. OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
  22211. rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
  22212. if( isReadWrite ){
  22213. return os2Open( pVfs, zName, id,
  22214. ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  22215. pOutFlags );
  22216. }else{
  22217. return SQLITE_CANTOPEN;
  22218. }
  22219. }
  22220. if( pOutFlags ){
  22221. *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
  22222. }
  22223. os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
  22224. pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
  22225. pFile->pMethod = &os2IoMethod;
  22226. pFile->flags = flags;
  22227. pFile->h = h;
  22228. OpenCounter(+1);
  22229. OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
  22230. return SQLITE_OK;
  22231. }
  22232. /*
  22233. ** Delete the named file.
  22234. */
  22235. static int os2Delete(
  22236. sqlite3_vfs *pVfs, /* Not used on os2 */
  22237. const char *zFilename, /* Name of file to delete */
  22238. int syncDir /* Not used on os2 */
  22239. ){
  22240. APIRET rc;
  22241. char *zFilenameCp;
  22242. SimulateIOError( return SQLITE_IOERR_DELETE );
  22243. zFilenameCp = convertUtf8PathToCp( zFilename );
  22244. rc = DosDelete( (PSZ)zFilenameCp );
  22245. free( zFilenameCp );
  22246. OSTRACE(( "DELETE \"%s\"\n", zFilename ));
  22247. return (rc == NO_ERROR ||
  22248. rc == ERROR_FILE_NOT_FOUND ||
  22249. rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
  22250. }
  22251. /*
  22252. ** Check the existance and status of a file.
  22253. */
  22254. static int os2Access(
  22255. sqlite3_vfs *pVfs, /* Not used on os2 */
  22256. const char *zFilename, /* Name of file to check */
  22257. int flags, /* Type of test to make on this file */
  22258. int *pOut /* Write results here */
  22259. ){
  22260. APIRET rc;
  22261. FILESTATUS3 fsts3ConfigInfo;
  22262. char *zFilenameCp;
  22263. UNUSED_PARAMETER(pVfs);
  22264. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  22265. zFilenameCp = convertUtf8PathToCp( zFilename );
  22266. rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
  22267. &fsts3ConfigInfo, sizeof(FILESTATUS3) );
  22268. free( zFilenameCp );
  22269. OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
  22270. fsts3ConfigInfo.attrFile, flags, rc ));
  22271. switch( flags ){
  22272. case SQLITE_ACCESS_EXISTS:
  22273. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  22274. ** as if it does not exist.
  22275. */
  22276. if( fsts3ConfigInfo.cbFile == 0 )
  22277. rc = ERROR_FILE_NOT_FOUND;
  22278. break;
  22279. case SQLITE_ACCESS_READ:
  22280. break;
  22281. case SQLITE_ACCESS_READWRITE:
  22282. if( fsts3ConfigInfo.attrFile & FILE_READONLY )
  22283. rc = ERROR_ACCESS_DENIED;
  22284. break;
  22285. default:
  22286. rc = ERROR_FILE_NOT_FOUND;
  22287. assert( !"Invalid flags argument" );
  22288. }
  22289. *pOut = (rc == NO_ERROR);
  22290. OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
  22291. return SQLITE_OK;
  22292. }
  22293. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  22294. /*
  22295. ** Interfaces for opening a shared library, finding entry points
  22296. ** within the shared library, and closing the shared library.
  22297. */
  22298. /*
  22299. ** Interfaces for opening a shared library, finding entry points
  22300. ** within the shared library, and closing the shared library.
  22301. */
  22302. static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  22303. HMODULE hmod;
  22304. APIRET rc;
  22305. char *zFilenameCp = convertUtf8PathToCp(zFilename);
  22306. rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
  22307. free(zFilenameCp);
  22308. return rc != NO_ERROR ? 0 : (void*)hmod;
  22309. }
  22310. /*
  22311. ** A no-op since the error code is returned on the DosLoadModule call.
  22312. ** os2Dlopen returns zero if DosLoadModule is not successful.
  22313. */
  22314. static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  22315. /* no-op */
  22316. }
  22317. static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
  22318. PFN pfn;
  22319. APIRET rc;
  22320. rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
  22321. if( rc != NO_ERROR ){
  22322. /* if the symbol itself was not found, search again for the same
  22323. * symbol with an extra underscore, that might be needed depending
  22324. * on the calling convention */
  22325. char _zSymbol[256] = "_";
  22326. strncat(_zSymbol, zSymbol, 254);
  22327. rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
  22328. }
  22329. return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
  22330. }
  22331. static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
  22332. DosFreeModule((HMODULE)pHandle);
  22333. }
  22334. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  22335. #define os2DlOpen 0
  22336. #define os2DlError 0
  22337. #define os2DlSym 0
  22338. #define os2DlClose 0
  22339. #endif
  22340. /*
  22341. ** Write up to nBuf bytes of randomness into zBuf.
  22342. */
  22343. static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
  22344. int n = 0;
  22345. #if defined(SQLITE_TEST)
  22346. n = nBuf;
  22347. memset(zBuf, 0, nBuf);
  22348. #else
  22349. int i;
  22350. PPIB ppib;
  22351. PTIB ptib;
  22352. DATETIME dt;
  22353. static unsigned c = 0;
  22354. /* Ordered by variation probability */
  22355. static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
  22356. QSV_MAXPRMEM, QSV_MAXSHMEM,
  22357. QSV_TOTAVAILMEM, QSV_TOTRESMEM };
  22358. /* 8 bytes; timezone and weekday don't increase the randomness much */
  22359. if( (int)sizeof(dt)-3 <= nBuf - n ){
  22360. c += 0x0100;
  22361. DosGetDateTime(&dt);
  22362. dt.year = (USHORT)((dt.year - 1900) | c);
  22363. memcpy(&zBuf[n], &dt, sizeof(dt)-3);
  22364. n += sizeof(dt)-3;
  22365. }
  22366. /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
  22367. if( (int)sizeof(ULONG) <= nBuf - n ){
  22368. DosGetInfoBlocks(&ptib, &ppib);
  22369. *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
  22370. ptib->tib_ptib2->tib2_ultid);
  22371. n += sizeof(ULONG);
  22372. }
  22373. /* Up to 6 * 4 bytes; variables depend on the system state */
  22374. for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
  22375. DosQuerySysInfo(svIdx[i], svIdx[i],
  22376. (PULONG)&zBuf[n], sizeof(ULONG));
  22377. n += sizeof(ULONG);
  22378. }
  22379. #endif
  22380. return n;
  22381. }
  22382. /*
  22383. ** Sleep for a little while. Return the amount of time slept.
  22384. ** The argument is the number of microseconds we want to sleep.
  22385. ** The return value is the number of microseconds of sleep actually
  22386. ** requested from the underlying operating system, a number which
  22387. ** might be greater than or equal to the argument, but not less
  22388. ** than the argument.
  22389. */
  22390. static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
  22391. DosSleep( (microsec/1000) );
  22392. return microsec;
  22393. }
  22394. /*
  22395. ** The following variable, if set to a non-zero value, becomes the result
  22396. ** returned from sqlite3OsCurrentTime(). This is used for testing.
  22397. */
  22398. #ifdef SQLITE_TEST
  22399. SQLITE_API int sqlite3_current_time = 0;
  22400. #endif
  22401. /*
  22402. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  22403. ** the current time and date as a Julian Day number times 86_400_000. In
  22404. ** other words, write into *piNow the number of milliseconds since the Julian
  22405. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  22406. ** proleptic Gregorian calendar.
  22407. **
  22408. ** On success, return 0. Return 1 if the time and date cannot be found.
  22409. */
  22410. static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  22411. #ifdef SQLITE_TEST
  22412. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  22413. #endif
  22414. int year, month, datepart, timepart;
  22415. DATETIME dt;
  22416. DosGetDateTime( &dt );
  22417. year = dt.year;
  22418. month = dt.month;
  22419. /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
  22420. ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
  22421. ** Calculate the Julian days
  22422. */
  22423. datepart = (int)dt.day - 32076 +
  22424. 1461*(year + 4800 + (month - 14)/12)/4 +
  22425. 367*(month - 2 - (month - 14)/12*12)/12 -
  22426. 3*((year + 4900 + (month - 14)/12)/100)/4;
  22427. /* Time in milliseconds, hours to noon added */
  22428. timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
  22429. ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
  22430. *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
  22431. #ifdef SQLITE_TEST
  22432. if( sqlite3_current_time ){
  22433. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  22434. }
  22435. #endif
  22436. UNUSED_PARAMETER(pVfs);
  22437. return 0;
  22438. }
  22439. /*
  22440. ** Find the current time (in Universal Coordinated Time). Write the
  22441. ** current time and date as a Julian Day number into *prNow and
  22442. ** return 0. Return 1 if the time and date cannot be found.
  22443. */
  22444. static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
  22445. int rc;
  22446. sqlite3_int64 i;
  22447. rc = os2CurrentTimeInt64(pVfs, &i);
  22448. if( !rc ){
  22449. *prNow = i/86400000.0;
  22450. }
  22451. return rc;
  22452. }
  22453. /*
  22454. ** The idea is that this function works like a combination of
  22455. ** GetLastError() and FormatMessage() on windows (or errno and
  22456. ** strerror_r() on unix). After an error is returned by an OS
  22457. ** function, SQLite calls this function with zBuf pointing to
  22458. ** a buffer of nBuf bytes. The OS layer should populate the
  22459. ** buffer with a nul-terminated UTF-8 encoded error message
  22460. ** describing the last IO error to have occurred within the calling
  22461. ** thread.
  22462. **
  22463. ** If the error message is too large for the supplied buffer,
  22464. ** it should be truncated. The return value of xGetLastError
  22465. ** is zero if the error message fits in the buffer, or non-zero
  22466. ** otherwise (if the message was truncated). If non-zero is returned,
  22467. ** then it is not necessary to include the nul-terminator character
  22468. ** in the output buffer.
  22469. **
  22470. ** Not supplying an error message will have no adverse effect
  22471. ** on SQLite. It is fine to have an implementation that never
  22472. ** returns an error message:
  22473. **
  22474. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  22475. ** assert(zBuf[0]=='\0');
  22476. ** return 0;
  22477. ** }
  22478. **
  22479. ** However if an error message is supplied, it will be incorporated
  22480. ** by sqlite into the error message available to the user using
  22481. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  22482. */
  22483. static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  22484. assert(zBuf[0]=='\0');
  22485. return 0;
  22486. }
  22487. /*
  22488. ** Initialize and deinitialize the operating system interface.
  22489. */
  22490. SQLITE_API int sqlite3_os_init(void){
  22491. static sqlite3_vfs os2Vfs = {
  22492. 3, /* iVersion */
  22493. sizeof(os2File), /* szOsFile */
  22494. CCHMAXPATH, /* mxPathname */
  22495. 0, /* pNext */
  22496. "os2", /* zName */
  22497. 0, /* pAppData */
  22498. os2Open, /* xOpen */
  22499. os2Delete, /* xDelete */
  22500. os2Access, /* xAccess */
  22501. os2FullPathname, /* xFullPathname */
  22502. os2DlOpen, /* xDlOpen */
  22503. os2DlError, /* xDlError */
  22504. os2DlSym, /* xDlSym */
  22505. os2DlClose, /* xDlClose */
  22506. os2Randomness, /* xRandomness */
  22507. os2Sleep, /* xSleep */
  22508. os2CurrentTime, /* xCurrentTime */
  22509. os2GetLastError, /* xGetLastError */
  22510. os2CurrentTimeInt64, /* xCurrentTimeInt64 */
  22511. 0, /* xSetSystemCall */
  22512. 0, /* xGetSystemCall */
  22513. 0 /* xNextSystemCall */
  22514. };
  22515. sqlite3_vfs_register(&os2Vfs, 1);
  22516. initUconvObjects();
  22517. /* sqlite3OSTrace = 1; */
  22518. return SQLITE_OK;
  22519. }
  22520. SQLITE_API int sqlite3_os_end(void){
  22521. freeUconvObjects();
  22522. return SQLITE_OK;
  22523. }
  22524. #endif /* SQLITE_OS_OS2 */
  22525. /************** End of os_os2.c **********************************************/
  22526. /************** Begin file os_unix.c *****************************************/
  22527. /*
  22528. ** 2004 May 22
  22529. **
  22530. ** The author disclaims copyright to this source code. In place of
  22531. ** a legal notice, here is a blessing:
  22532. **
  22533. ** May you do good and not evil.
  22534. ** May you find forgiveness for yourself and forgive others.
  22535. ** May you share freely, never taking more than you give.
  22536. **
  22537. ******************************************************************************
  22538. **
  22539. ** This file contains the VFS implementation for unix-like operating systems
  22540. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  22541. **
  22542. ** There are actually several different VFS implementations in this file.
  22543. ** The differences are in the way that file locking is done. The default
  22544. ** implementation uses Posix Advisory Locks. Alternative implementations
  22545. ** use flock(), dot-files, various proprietary locking schemas, or simply
  22546. ** skip locking all together.
  22547. **
  22548. ** This source file is organized into divisions where the logic for various
  22549. ** subfunctions is contained within the appropriate division. PLEASE
  22550. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  22551. ** in the correct division and should be clearly labeled.
  22552. **
  22553. ** The layout of divisions is as follows:
  22554. **
  22555. ** * General-purpose declarations and utility functions.
  22556. ** * Unique file ID logic used by VxWorks.
  22557. ** * Various locking primitive implementations (all except proxy locking):
  22558. ** + for Posix Advisory Locks
  22559. ** + for no-op locks
  22560. ** + for dot-file locks
  22561. ** + for flock() locking
  22562. ** + for named semaphore locks (VxWorks only)
  22563. ** + for AFP filesystem locks (MacOSX only)
  22564. ** * sqlite3_file methods not associated with locking.
  22565. ** * Definitions of sqlite3_io_methods objects for all locking
  22566. ** methods plus "finder" functions for each locking method.
  22567. ** * sqlite3_vfs method implementations.
  22568. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  22569. ** * Definitions of sqlite3_vfs objects for all locking methods
  22570. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  22571. */
  22572. #if SQLITE_OS_UNIX /* This file is used on unix only */
  22573. /*
  22574. ** There are various methods for file locking used for concurrency
  22575. ** control:
  22576. **
  22577. ** 1. POSIX locking (the default),
  22578. ** 2. No locking,
  22579. ** 3. Dot-file locking,
  22580. ** 4. flock() locking,
  22581. ** 5. AFP locking (OSX only),
  22582. ** 6. Named POSIX semaphores (VXWorks only),
  22583. ** 7. proxy locking. (OSX only)
  22584. **
  22585. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  22586. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  22587. ** selection of the appropriate locking style based on the filesystem
  22588. ** where the database is located.
  22589. */
  22590. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  22591. # if defined(__APPLE__)
  22592. # define SQLITE_ENABLE_LOCKING_STYLE 1
  22593. # else
  22594. # define SQLITE_ENABLE_LOCKING_STYLE 0
  22595. # endif
  22596. #endif
  22597. /*
  22598. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  22599. ** vxworks, or 0 otherwise.
  22600. */
  22601. #ifndef OS_VXWORKS
  22602. # if defined(__RTP__) || defined(_WRS_KERNEL)
  22603. # define OS_VXWORKS 1
  22604. # else
  22605. # define OS_VXWORKS 0
  22606. # endif
  22607. #endif
  22608. /*
  22609. ** These #defines should enable >2GB file support on Posix if the
  22610. ** underlying operating system supports it. If the OS lacks
  22611. ** large file support, these should be no-ops.
  22612. **
  22613. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  22614. ** on the compiler command line. This is necessary if you are compiling
  22615. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  22616. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  22617. ** without this option, LFS is enable. But LFS does not exist in the kernel
  22618. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  22619. ** portability you should omit LFS.
  22620. **
  22621. ** The previous paragraph was written in 2005. (This paragraph is written
  22622. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  22623. ** you should probably leave LFS enabled. But some embedded platforms might
  22624. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  22625. */
  22626. #ifndef SQLITE_DISABLE_LFS
  22627. # define _LARGE_FILE 1
  22628. # ifndef _FILE_OFFSET_BITS
  22629. # define _FILE_OFFSET_BITS 64
  22630. # endif
  22631. # define _LARGEFILE_SOURCE 1
  22632. #endif
  22633. /*
  22634. ** standard include files.
  22635. */
  22636. #include <sys/types.h>
  22637. #include <sys/stat.h>
  22638. #include <fcntl.h>
  22639. #include <unistd.h>
  22640. #include <sys/time.h>
  22641. #include <errno.h>
  22642. #ifndef SQLITE_OMIT_WAL
  22643. #include <sys/mman.h>
  22644. #endif
  22645. #if SQLITE_ENABLE_LOCKING_STYLE
  22646. # include <sys/ioctl.h>
  22647. # if OS_VXWORKS
  22648. # include <semaphore.h>
  22649. # include <limits.h>
  22650. # else
  22651. # include <sys/file.h>
  22652. # include <sys/param.h>
  22653. # endif
  22654. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  22655. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  22656. # include <sys/mount.h>
  22657. #endif
  22658. /*
  22659. ** Allowed values of unixFile.fsFlags
  22660. */
  22661. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  22662. /*
  22663. ** If we are to be thread-safe, include the pthreads header and define
  22664. ** the SQLITE_UNIX_THREADS macro.
  22665. */
  22666. #if SQLITE_THREADSAFE
  22667. # define SQLITE_UNIX_THREADS 1
  22668. #endif
  22669. /*
  22670. ** Default permissions when creating a new file
  22671. */
  22672. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  22673. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  22674. #endif
  22675. /*
  22676. ** Default permissions when creating auto proxy dir
  22677. */
  22678. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  22679. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  22680. #endif
  22681. /*
  22682. ** Maximum supported path-length.
  22683. */
  22684. #define MAX_PATHNAME 512
  22685. /*
  22686. ** Only set the lastErrno if the error code is a real error and not
  22687. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  22688. */
  22689. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  22690. /* Forward references */
  22691. typedef struct unixShm unixShm; /* Connection shared memory */
  22692. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  22693. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  22694. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  22695. /*
  22696. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  22697. ** cannot be closed immediately. In these cases, instances of the following
  22698. ** structure are used to store the file descriptor while waiting for an
  22699. ** opportunity to either close or reuse it.
  22700. */
  22701. struct UnixUnusedFd {
  22702. int fd; /* File descriptor to close */
  22703. int flags; /* Flags this file descriptor was opened with */
  22704. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  22705. };
  22706. /*
  22707. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  22708. ** VFS implementations.
  22709. */
  22710. typedef struct unixFile unixFile;
  22711. struct unixFile {
  22712. sqlite3_io_methods const *pMethod; /* Always the first entry */
  22713. unixInodeInfo *pInode; /* Info about locks on this inode */
  22714. int h; /* The file descriptor */
  22715. int dirfd; /* File descriptor for the directory */
  22716. unsigned char eFileLock; /* The type of lock held on this fd */
  22717. unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  22718. int lastErrno; /* The unix errno from last I/O error */
  22719. void *lockingContext; /* Locking style specific state */
  22720. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  22721. const char *zPath; /* Name of the file */
  22722. unixShm *pShm; /* Shared memory segment information */
  22723. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  22724. #if SQLITE_ENABLE_LOCKING_STYLE
  22725. int openFlags; /* The flags specified at open() */
  22726. #endif
  22727. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  22728. unsigned fsFlags; /* cached details from statfs() */
  22729. #endif
  22730. #if OS_VXWORKS
  22731. int isDelete; /* Delete on close if true */
  22732. struct vxworksFileId *pId; /* Unique file ID */
  22733. #endif
  22734. #ifndef NDEBUG
  22735. /* The next group of variables are used to track whether or not the
  22736. ** transaction counter in bytes 24-27 of database files are updated
  22737. ** whenever any part of the database changes. An assertion fault will
  22738. ** occur if a file is updated without also updating the transaction
  22739. ** counter. This test is made to avoid new problems similar to the
  22740. ** one described by ticket #3584.
  22741. */
  22742. unsigned char transCntrChng; /* True if the transaction counter changed */
  22743. unsigned char dbUpdate; /* True if any part of database file changed */
  22744. unsigned char inNormalWrite; /* True if in a normal write operation */
  22745. #endif
  22746. #ifdef SQLITE_TEST
  22747. /* In test mode, increase the size of this structure a bit so that
  22748. ** it is larger than the struct CrashFile defined in test6.c.
  22749. */
  22750. char aPadding[32];
  22751. #endif
  22752. };
  22753. /*
  22754. ** Allowed values for the unixFile.ctrlFlags bitmask:
  22755. */
  22756. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  22757. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  22758. /*
  22759. ** Include code that is common to all os_*.c files
  22760. */
  22761. /************** Include os_common.h in the middle of os_unix.c ***************/
  22762. /************** Begin file os_common.h ***************************************/
  22763. /*
  22764. ** 2004 May 22
  22765. **
  22766. ** The author disclaims copyright to this source code. In place of
  22767. ** a legal notice, here is a blessing:
  22768. **
  22769. ** May you do good and not evil.
  22770. ** May you find forgiveness for yourself and forgive others.
  22771. ** May you share freely, never taking more than you give.
  22772. **
  22773. ******************************************************************************
  22774. **
  22775. ** This file contains macros and a little bit of code that is common to
  22776. ** all of the platform-specific files (os_*.c) and is #included into those
  22777. ** files.
  22778. **
  22779. ** This file should be #included by the os_*.c files only. It is not a
  22780. ** general purpose header file.
  22781. */
  22782. #ifndef _OS_COMMON_H_
  22783. #define _OS_COMMON_H_
  22784. /*
  22785. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  22786. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  22787. ** switch. The following code should catch this problem at compile-time.
  22788. */
  22789. #ifdef MEMORY_DEBUG
  22790. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  22791. #endif
  22792. #ifdef SQLITE_DEBUG
  22793. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  22794. #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  22795. #else
  22796. #define OSTRACE(X)
  22797. #endif
  22798. /*
  22799. ** Macros for performance tracing. Normally turned off. Only works
  22800. ** on i486 hardware.
  22801. */
  22802. #ifdef SQLITE_PERFORMANCE_TRACE
  22803. /*
  22804. ** hwtime.h contains inline assembler code for implementing
  22805. ** high-performance timing routines.
  22806. */
  22807. /************** Include hwtime.h in the middle of os_common.h ****************/
  22808. /************** Begin file hwtime.h ******************************************/
  22809. /*
  22810. ** 2008 May 27
  22811. **
  22812. ** The author disclaims copyright to this source code. In place of
  22813. ** a legal notice, here is a blessing:
  22814. **
  22815. ** May you do good and not evil.
  22816. ** May you find forgiveness for yourself and forgive others.
  22817. ** May you share freely, never taking more than you give.
  22818. **
  22819. ******************************************************************************
  22820. **
  22821. ** This file contains inline asm code for retrieving "high-performance"
  22822. ** counters for x86 class CPUs.
  22823. */
  22824. #ifndef _HWTIME_H_
  22825. #define _HWTIME_H_
  22826. /*
  22827. ** The following routine only works on pentium-class (or newer) processors.
  22828. ** It uses the RDTSC opcode to read the cycle count value out of the
  22829. ** processor and returns that value. This can be used for high-res
  22830. ** profiling.
  22831. */
  22832. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  22833. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  22834. #if defined(__GNUC__)
  22835. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22836. unsigned int lo, hi;
  22837. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  22838. return (sqlite_uint64)hi << 32 | lo;
  22839. }
  22840. #elif defined(_MSC_VER)
  22841. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  22842. __asm {
  22843. rdtsc
  22844. ret ; return value at EDX:EAX
  22845. }
  22846. }
  22847. #endif
  22848. #elif (defined(__GNUC__) && defined(__x86_64__))
  22849. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22850. unsigned long val;
  22851. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  22852. return val;
  22853. }
  22854. #elif (defined(__GNUC__) && defined(__ppc__))
  22855. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22856. unsigned long long retval;
  22857. unsigned long junk;
  22858. __asm__ __volatile__ ("\n\
  22859. 1: mftbu %1\n\
  22860. mftb %L0\n\
  22861. mftbu %0\n\
  22862. cmpw %0,%1\n\
  22863. bne 1b"
  22864. : "=r" (retval), "=r" (junk));
  22865. return retval;
  22866. }
  22867. #else
  22868. #error Need implementation of sqlite3Hwtime() for your platform.
  22869. /*
  22870. ** To compile without implementing sqlite3Hwtime() for your platform,
  22871. ** you can remove the above #error and use the following
  22872. ** stub function. You will lose timing support for many
  22873. ** of the debugging and testing utilities, but it should at
  22874. ** least compile and run.
  22875. */
  22876. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  22877. #endif
  22878. #endif /* !defined(_HWTIME_H_) */
  22879. /************** End of hwtime.h **********************************************/
  22880. /************** Continuing where we left off in os_common.h ******************/
  22881. static sqlite_uint64 g_start;
  22882. static sqlite_uint64 g_elapsed;
  22883. #define TIMER_START g_start=sqlite3Hwtime()
  22884. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  22885. #define TIMER_ELAPSED g_elapsed
  22886. #else
  22887. #define TIMER_START
  22888. #define TIMER_END
  22889. #define TIMER_ELAPSED ((sqlite_uint64)0)
  22890. #endif
  22891. /*
  22892. ** If we compile with the SQLITE_TEST macro set, then the following block
  22893. ** of code will give us the ability to simulate a disk I/O error. This
  22894. ** is used for testing the I/O recovery logic.
  22895. */
  22896. #ifdef SQLITE_TEST
  22897. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  22898. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  22899. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  22900. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  22901. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  22902. SQLITE_API int sqlite3_diskfull_pending = 0;
  22903. SQLITE_API int sqlite3_diskfull = 0;
  22904. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  22905. #define SimulateIOError(CODE) \
  22906. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  22907. || sqlite3_io_error_pending-- == 1 ) \
  22908. { local_ioerr(); CODE; }
  22909. static void local_ioerr(){
  22910. IOTRACE(("IOERR\n"));
  22911. sqlite3_io_error_hit++;
  22912. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  22913. }
  22914. #define SimulateDiskfullError(CODE) \
  22915. if( sqlite3_diskfull_pending ){ \
  22916. if( sqlite3_diskfull_pending == 1 ){ \
  22917. local_ioerr(); \
  22918. sqlite3_diskfull = 1; \
  22919. sqlite3_io_error_hit = 1; \
  22920. CODE; \
  22921. }else{ \
  22922. sqlite3_diskfull_pending--; \
  22923. } \
  22924. }
  22925. #else
  22926. #define SimulateIOErrorBenign(X)
  22927. #define SimulateIOError(A)
  22928. #define SimulateDiskfullError(A)
  22929. #endif
  22930. /*
  22931. ** When testing, keep a count of the number of open files.
  22932. */
  22933. #ifdef SQLITE_TEST
  22934. SQLITE_API int sqlite3_open_file_count = 0;
  22935. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  22936. #else
  22937. #define OpenCounter(X)
  22938. #endif
  22939. #endif /* !defined(_OS_COMMON_H_) */
  22940. /************** End of os_common.h *******************************************/
  22941. /************** Continuing where we left off in os_unix.c ********************/
  22942. /*
  22943. ** Define various macros that are missing from some systems.
  22944. */
  22945. #ifndef O_LARGEFILE
  22946. # define O_LARGEFILE 0
  22947. #endif
  22948. #ifdef SQLITE_DISABLE_LFS
  22949. # undef O_LARGEFILE
  22950. # define O_LARGEFILE 0
  22951. #endif
  22952. #ifndef O_NOFOLLOW
  22953. # define O_NOFOLLOW 0
  22954. #endif
  22955. #ifndef O_BINARY
  22956. # define O_BINARY 0
  22957. #endif
  22958. /*
  22959. ** The threadid macro resolves to the thread-id or to 0. Used for
  22960. ** testing and debugging only.
  22961. */
  22962. #if SQLITE_THREADSAFE
  22963. #define threadid pthread_self()
  22964. #else
  22965. #define threadid 0
  22966. #endif
  22967. /*
  22968. ** Many system calls are accessed through pointer-to-functions so that
  22969. ** they may be overridden at runtime to facilitate fault injection during
  22970. ** testing and sandboxing. The following array holds the names and pointers
  22971. ** to all overrideable system calls.
  22972. */
  22973. static struct unix_syscall {
  22974. const char *zName; /* Name of the sytem call */
  22975. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  22976. sqlite3_syscall_ptr pDefault; /* Default value */
  22977. } aSyscall[] = {
  22978. { "open", (sqlite3_syscall_ptr)open, 0 },
  22979. #define osOpen ((int(*)(const char*,int,...))aSyscall[0].pCurrent)
  22980. { "close", (sqlite3_syscall_ptr)close, 0 },
  22981. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  22982. { "access", (sqlite3_syscall_ptr)access, 0 },
  22983. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  22984. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  22985. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  22986. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  22987. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  22988. /*
  22989. ** The DJGPP compiler environment looks mostly like Unix, but it
  22990. ** lacks the fcntl() system call. So redefine fcntl() to be something
  22991. ** that always succeeds. This means that locking does not occur under
  22992. ** DJGPP. But it is DOS - what did you expect?
  22993. */
  22994. #ifdef __DJGPP__
  22995. { "fstat", 0, 0 },
  22996. #define osFstat(a,b,c) 0
  22997. #else
  22998. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  22999. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  23000. #endif
  23001. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  23002. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  23003. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  23004. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  23005. { "read", (sqlite3_syscall_ptr)read, 0 },
  23006. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  23007. #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
  23008. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  23009. #else
  23010. { "pread", (sqlite3_syscall_ptr)0, 0 },
  23011. #endif
  23012. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  23013. #if defined(USE_PREAD64)
  23014. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  23015. #else
  23016. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  23017. #endif
  23018. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  23019. { "write", (sqlite3_syscall_ptr)write, 0 },
  23020. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  23021. #if defined(USE_PREAD) || defined(SQLITE_ENABLE_LOCKING_STYLE)
  23022. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  23023. #else
  23024. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  23025. #endif
  23026. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  23027. aSyscall[12].pCurrent)
  23028. #if defined(USE_PREAD64)
  23029. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  23030. #else
  23031. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  23032. #endif
  23033. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  23034. aSyscall[13].pCurrent)
  23035. #if SQLITE_ENABLE_LOCKING_STYLE
  23036. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  23037. #else
  23038. { "fchmod", (sqlite3_syscall_ptr)0, 0 },
  23039. #endif
  23040. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  23041. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  23042. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  23043. #else
  23044. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  23045. #endif
  23046. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  23047. }; /* End of the overrideable system calls */
  23048. /*
  23049. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  23050. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  23051. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  23052. ** system call named zName.
  23053. */
  23054. static int unixSetSystemCall(
  23055. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  23056. const char *zName, /* Name of system call to override */
  23057. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  23058. ){
  23059. unsigned int i;
  23060. int rc = SQLITE_NOTFOUND;
  23061. UNUSED_PARAMETER(pNotUsed);
  23062. if( zName==0 ){
  23063. /* If no zName is given, restore all system calls to their default
  23064. ** settings and return NULL
  23065. */
  23066. rc = SQLITE_OK;
  23067. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23068. if( aSyscall[i].pDefault ){
  23069. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  23070. }
  23071. }
  23072. }else{
  23073. /* If zName is specified, operate on only the one system call
  23074. ** specified.
  23075. */
  23076. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23077. if( strcmp(zName, aSyscall[i].zName)==0 ){
  23078. if( aSyscall[i].pDefault==0 ){
  23079. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  23080. }
  23081. rc = SQLITE_OK;
  23082. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  23083. aSyscall[i].pCurrent = pNewFunc;
  23084. break;
  23085. }
  23086. }
  23087. }
  23088. return rc;
  23089. }
  23090. /*
  23091. ** Return the value of a system call. Return NULL if zName is not a
  23092. ** recognized system call name. NULL is also returned if the system call
  23093. ** is currently undefined.
  23094. */
  23095. static sqlite3_syscall_ptr unixGetSystemCall(
  23096. sqlite3_vfs *pNotUsed,
  23097. const char *zName
  23098. ){
  23099. unsigned int i;
  23100. UNUSED_PARAMETER(pNotUsed);
  23101. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23102. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  23103. }
  23104. return 0;
  23105. }
  23106. /*
  23107. ** Return the name of the first system call after zName. If zName==NULL
  23108. ** then return the name of the first system call. Return NULL if zName
  23109. ** is the last system call or if zName is not the name of a valid
  23110. ** system call.
  23111. */
  23112. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  23113. int i = -1;
  23114. UNUSED_PARAMETER(p);
  23115. if( zName ){
  23116. for(i=0; i<ArraySize(aSyscall)-1; i++){
  23117. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  23118. }
  23119. }
  23120. for(i++; i<ArraySize(aSyscall); i++){
  23121. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  23122. }
  23123. return 0;
  23124. }
  23125. /*
  23126. ** Retry open() calls that fail due to EINTR
  23127. */
  23128. static int robust_open(const char *z, int f, int m){
  23129. int rc;
  23130. do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
  23131. return rc;
  23132. }
  23133. /*
  23134. ** Helper functions to obtain and relinquish the global mutex. The
  23135. ** global mutex is used to protect the unixInodeInfo and
  23136. ** vxworksFileId objects used by this file, all of which may be
  23137. ** shared by multiple threads.
  23138. **
  23139. ** Function unixMutexHeld() is used to assert() that the global mutex
  23140. ** is held when required. This function is only used as part of assert()
  23141. ** statements. e.g.
  23142. **
  23143. ** unixEnterMutex()
  23144. ** assert( unixMutexHeld() );
  23145. ** unixEnterLeave()
  23146. */
  23147. static void unixEnterMutex(void){
  23148. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  23149. }
  23150. static void unixLeaveMutex(void){
  23151. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  23152. }
  23153. #ifdef SQLITE_DEBUG
  23154. static int unixMutexHeld(void) {
  23155. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  23156. }
  23157. #endif
  23158. #ifdef SQLITE_DEBUG
  23159. /*
  23160. ** Helper function for printing out trace information from debugging
  23161. ** binaries. This returns the string represetation of the supplied
  23162. ** integer lock-type.
  23163. */
  23164. static const char *azFileLock(int eFileLock){
  23165. switch( eFileLock ){
  23166. case NO_LOCK: return "NONE";
  23167. case SHARED_LOCK: return "SHARED";
  23168. case RESERVED_LOCK: return "RESERVED";
  23169. case PENDING_LOCK: return "PENDING";
  23170. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  23171. }
  23172. return "ERROR";
  23173. }
  23174. #endif
  23175. #ifdef SQLITE_LOCK_TRACE
  23176. /*
  23177. ** Print out information about all locking operations.
  23178. **
  23179. ** This routine is used for troubleshooting locks on multithreaded
  23180. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  23181. ** command-line option on the compiler. This code is normally
  23182. ** turned off.
  23183. */
  23184. static int lockTrace(int fd, int op, struct flock *p){
  23185. char *zOpName, *zType;
  23186. int s;
  23187. int savedErrno;
  23188. if( op==F_GETLK ){
  23189. zOpName = "GETLK";
  23190. }else if( op==F_SETLK ){
  23191. zOpName = "SETLK";
  23192. }else{
  23193. s = osFcntl(fd, op, p);
  23194. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  23195. return s;
  23196. }
  23197. if( p->l_type==F_RDLCK ){
  23198. zType = "RDLCK";
  23199. }else if( p->l_type==F_WRLCK ){
  23200. zType = "WRLCK";
  23201. }else if( p->l_type==F_UNLCK ){
  23202. zType = "UNLCK";
  23203. }else{
  23204. assert( 0 );
  23205. }
  23206. assert( p->l_whence==SEEK_SET );
  23207. s = osFcntl(fd, op, p);
  23208. savedErrno = errno;
  23209. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  23210. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  23211. (int)p->l_pid, s);
  23212. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  23213. struct flock l2;
  23214. l2 = *p;
  23215. osFcntl(fd, F_GETLK, &l2);
  23216. if( l2.l_type==F_RDLCK ){
  23217. zType = "RDLCK";
  23218. }else if( l2.l_type==F_WRLCK ){
  23219. zType = "WRLCK";
  23220. }else if( l2.l_type==F_UNLCK ){
  23221. zType = "UNLCK";
  23222. }else{
  23223. assert( 0 );
  23224. }
  23225. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  23226. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  23227. }
  23228. errno = savedErrno;
  23229. return s;
  23230. }
  23231. #undef osFcntl
  23232. #define osFcntl lockTrace
  23233. #endif /* SQLITE_LOCK_TRACE */
  23234. /*
  23235. ** Retry ftruncate() calls that fail due to EINTR
  23236. */
  23237. static int robust_ftruncate(int h, sqlite3_int64 sz){
  23238. int rc;
  23239. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  23240. return rc;
  23241. }
  23242. /*
  23243. ** This routine translates a standard POSIX errno code into something
  23244. ** useful to the clients of the sqlite3 functions. Specifically, it is
  23245. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  23246. ** and a variety of "please close the file descriptor NOW" errors into
  23247. ** SQLITE_IOERR
  23248. **
  23249. ** Errors during initialization of locks, or file system support for locks,
  23250. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  23251. */
  23252. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  23253. switch (posixError) {
  23254. #if 0
  23255. /* At one point this code was not commented out. In theory, this branch
  23256. ** should never be hit, as this function should only be called after
  23257. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  23258. ** the value of errno as the first argument. Since a system call has failed,
  23259. ** errno should be non-zero.
  23260. **
  23261. ** Despite this, if errno really is zero, we still don't want to return
  23262. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  23263. ** propagated back to the caller. Commenting this branch out means errno==0
  23264. ** will be handled by the "default:" case below.
  23265. */
  23266. case 0:
  23267. return SQLITE_OK;
  23268. #endif
  23269. case EAGAIN:
  23270. case ETIMEDOUT:
  23271. case EBUSY:
  23272. case EINTR:
  23273. case ENOLCK:
  23274. /* random NFS retry error, unless during file system support
  23275. * introspection, in which it actually means what it says */
  23276. return SQLITE_BUSY;
  23277. case EACCES:
  23278. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  23279. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  23280. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  23281. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  23282. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  23283. return SQLITE_BUSY;
  23284. }
  23285. /* else fall through */
  23286. case EPERM:
  23287. return SQLITE_PERM;
  23288. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  23289. ** this module never makes such a call. And the code in SQLite itself
  23290. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  23291. ** this case is also commented out. If the system does set errno to EDEADLK,
  23292. ** the default SQLITE_IOERR_XXX code will be returned. */
  23293. #if 0
  23294. case EDEADLK:
  23295. return SQLITE_IOERR_BLOCKED;
  23296. #endif
  23297. #if EOPNOTSUPP!=ENOTSUP
  23298. case EOPNOTSUPP:
  23299. /* something went terribly awry, unless during file system support
  23300. * introspection, in which it actually means what it says */
  23301. #endif
  23302. #ifdef ENOTSUP
  23303. case ENOTSUP:
  23304. /* invalid fd, unless during file system support introspection, in which
  23305. * it actually means what it says */
  23306. #endif
  23307. case EIO:
  23308. case EBADF:
  23309. case EINVAL:
  23310. case ENOTCONN:
  23311. case ENODEV:
  23312. case ENXIO:
  23313. case ENOENT:
  23314. case ESTALE:
  23315. case ENOSYS:
  23316. /* these should force the client to close the file and reconnect */
  23317. default:
  23318. return sqliteIOErr;
  23319. }
  23320. }
  23321. /******************************************************************************
  23322. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  23323. **
  23324. ** On most versions of unix, we can get a unique ID for a file by concatenating
  23325. ** the device number and the inode number. But this does not work on VxWorks.
  23326. ** On VxWorks, a unique file id must be based on the canonical filename.
  23327. **
  23328. ** A pointer to an instance of the following structure can be used as a
  23329. ** unique file ID in VxWorks. Each instance of this structure contains
  23330. ** a copy of the canonical filename. There is also a reference count.
  23331. ** The structure is reclaimed when the number of pointers to it drops to
  23332. ** zero.
  23333. **
  23334. ** There are never very many files open at one time and lookups are not
  23335. ** a performance-critical path, so it is sufficient to put these
  23336. ** structures on a linked list.
  23337. */
  23338. struct vxworksFileId {
  23339. struct vxworksFileId *pNext; /* Next in a list of them all */
  23340. int nRef; /* Number of references to this one */
  23341. int nName; /* Length of the zCanonicalName[] string */
  23342. char *zCanonicalName; /* Canonical filename */
  23343. };
  23344. #if OS_VXWORKS
  23345. /*
  23346. ** All unique filenames are held on a linked list headed by this
  23347. ** variable:
  23348. */
  23349. static struct vxworksFileId *vxworksFileList = 0;
  23350. /*
  23351. ** Simplify a filename into its canonical form
  23352. ** by making the following changes:
  23353. **
  23354. ** * removing any trailing and duplicate /
  23355. ** * convert /./ into just /
  23356. ** * convert /A/../ where A is any simple name into just /
  23357. **
  23358. ** Changes are made in-place. Return the new name length.
  23359. **
  23360. ** The original filename is in z[0..n-1]. Return the number of
  23361. ** characters in the simplified name.
  23362. */
  23363. static int vxworksSimplifyName(char *z, int n){
  23364. int i, j;
  23365. while( n>1 && z[n-1]=='/' ){ n--; }
  23366. for(i=j=0; i<n; i++){
  23367. if( z[i]=='/' ){
  23368. if( z[i+1]=='/' ) continue;
  23369. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  23370. i += 1;
  23371. continue;
  23372. }
  23373. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  23374. while( j>0 && z[j-1]!='/' ){ j--; }
  23375. if( j>0 ){ j--; }
  23376. i += 2;
  23377. continue;
  23378. }
  23379. }
  23380. z[j++] = z[i];
  23381. }
  23382. z[j] = 0;
  23383. return j;
  23384. }
  23385. /*
  23386. ** Find a unique file ID for the given absolute pathname. Return
  23387. ** a pointer to the vxworksFileId object. This pointer is the unique
  23388. ** file ID.
  23389. **
  23390. ** The nRef field of the vxworksFileId object is incremented before
  23391. ** the object is returned. A new vxworksFileId object is created
  23392. ** and added to the global list if necessary.
  23393. **
  23394. ** If a memory allocation error occurs, return NULL.
  23395. */
  23396. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  23397. struct vxworksFileId *pNew; /* search key and new file ID */
  23398. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  23399. int n; /* Length of zAbsoluteName string */
  23400. assert( zAbsoluteName[0]=='/' );
  23401. n = (int)strlen(zAbsoluteName);
  23402. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  23403. if( pNew==0 ) return 0;
  23404. pNew->zCanonicalName = (char*)&pNew[1];
  23405. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  23406. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  23407. /* Search for an existing entry that matching the canonical name.
  23408. ** If found, increment the reference count and return a pointer to
  23409. ** the existing file ID.
  23410. */
  23411. unixEnterMutex();
  23412. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  23413. if( pCandidate->nName==n
  23414. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  23415. ){
  23416. sqlite3_free(pNew);
  23417. pCandidate->nRef++;
  23418. unixLeaveMutex();
  23419. return pCandidate;
  23420. }
  23421. }
  23422. /* No match was found. We will make a new file ID */
  23423. pNew->nRef = 1;
  23424. pNew->nName = n;
  23425. pNew->pNext = vxworksFileList;
  23426. vxworksFileList = pNew;
  23427. unixLeaveMutex();
  23428. return pNew;
  23429. }
  23430. /*
  23431. ** Decrement the reference count on a vxworksFileId object. Free
  23432. ** the object when the reference count reaches zero.
  23433. */
  23434. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  23435. unixEnterMutex();
  23436. assert( pId->nRef>0 );
  23437. pId->nRef--;
  23438. if( pId->nRef==0 ){
  23439. struct vxworksFileId **pp;
  23440. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  23441. assert( *pp==pId );
  23442. *pp = pId->pNext;
  23443. sqlite3_free(pId);
  23444. }
  23445. unixLeaveMutex();
  23446. }
  23447. #endif /* OS_VXWORKS */
  23448. /*************** End of Unique File ID Utility Used By VxWorks ****************
  23449. ******************************************************************************/
  23450. /******************************************************************************
  23451. *************************** Posix Advisory Locking ****************************
  23452. **
  23453. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  23454. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  23455. ** sets or clears a lock, that operation overrides any prior locks set
  23456. ** by the same process. It does not explicitly say so, but this implies
  23457. ** that it overrides locks set by the same process using a different
  23458. ** file descriptor. Consider this test case:
  23459. **
  23460. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  23461. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  23462. **
  23463. ** Suppose ./file1 and ./file2 are really the same file (because
  23464. ** one is a hard or symbolic link to the other) then if you set
  23465. ** an exclusive lock on fd1, then try to get an exclusive lock
  23466. ** on fd2, it works. I would have expected the second lock to
  23467. ** fail since there was already a lock on the file due to fd1.
  23468. ** But not so. Since both locks came from the same process, the
  23469. ** second overrides the first, even though they were on different
  23470. ** file descriptors opened on different file names.
  23471. **
  23472. ** This means that we cannot use POSIX locks to synchronize file access
  23473. ** among competing threads of the same process. POSIX locks will work fine
  23474. ** to synchronize access for threads in separate processes, but not
  23475. ** threads within the same process.
  23476. **
  23477. ** To work around the problem, SQLite has to manage file locks internally
  23478. ** on its own. Whenever a new database is opened, we have to find the
  23479. ** specific inode of the database file (the inode is determined by the
  23480. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  23481. ** and check for locks already existing on that inode. When locks are
  23482. ** created or removed, we have to look at our own internal record of the
  23483. ** locks to see if another thread has previously set a lock on that same
  23484. ** inode.
  23485. **
  23486. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  23487. ** For VxWorks, we have to use the alternative unique ID system based on
  23488. ** canonical filename and implemented in the previous division.)
  23489. **
  23490. ** The sqlite3_file structure for POSIX is no longer just an integer file
  23491. ** descriptor. It is now a structure that holds the integer file
  23492. ** descriptor and a pointer to a structure that describes the internal
  23493. ** locks on the corresponding inode. There is one locking structure
  23494. ** per inode, so if the same inode is opened twice, both unixFile structures
  23495. ** point to the same locking structure. The locking structure keeps
  23496. ** a reference count (so we will know when to delete it) and a "cnt"
  23497. ** field that tells us its internal lock status. cnt==0 means the
  23498. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  23499. ** cnt>0 means there are cnt shared locks on the file.
  23500. **
  23501. ** Any attempt to lock or unlock a file first checks the locking
  23502. ** structure. The fcntl() system call is only invoked to set a
  23503. ** POSIX lock if the internal lock structure transitions between
  23504. ** a locked and an unlocked state.
  23505. **
  23506. ** But wait: there are yet more problems with POSIX advisory locks.
  23507. **
  23508. ** If you close a file descriptor that points to a file that has locks,
  23509. ** all locks on that file that are owned by the current process are
  23510. ** released. To work around this problem, each unixInodeInfo object
  23511. ** maintains a count of the number of pending locks on tha inode.
  23512. ** When an attempt is made to close an unixFile, if there are
  23513. ** other unixFile open on the same inode that are holding locks, the call
  23514. ** to close() the file descriptor is deferred until all of the locks clear.
  23515. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  23516. ** be closed and that list is walked (and cleared) when the last lock
  23517. ** clears.
  23518. **
  23519. ** Yet another problem: LinuxThreads do not play well with posix locks.
  23520. **
  23521. ** Many older versions of linux use the LinuxThreads library which is
  23522. ** not posix compliant. Under LinuxThreads, a lock created by thread
  23523. ** A cannot be modified or overridden by a different thread B.
  23524. ** Only thread A can modify the lock. Locking behavior is correct
  23525. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  23526. ** on linux - with NPTL a lock created by thread A can override locks
  23527. ** in thread B. But there is no way to know at compile-time which
  23528. ** threading library is being used. So there is no way to know at
  23529. ** compile-time whether or not thread A can override locks on thread B.
  23530. ** One has to do a run-time check to discover the behavior of the
  23531. ** current process.
  23532. **
  23533. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  23534. ** was dropped beginning with version 3.7.0. SQLite will still work with
  23535. ** LinuxThreads provided that (1) there is no more than one connection
  23536. ** per database file in the same process and (2) database connections
  23537. ** do not move across threads.
  23538. */
  23539. /*
  23540. ** An instance of the following structure serves as the key used
  23541. ** to locate a particular unixInodeInfo object.
  23542. */
  23543. struct unixFileId {
  23544. dev_t dev; /* Device number */
  23545. #if OS_VXWORKS
  23546. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  23547. #else
  23548. ino_t ino; /* Inode number */
  23549. #endif
  23550. };
  23551. /*
  23552. ** An instance of the following structure is allocated for each open
  23553. ** inode. Or, on LinuxThreads, there is one of these structures for
  23554. ** each inode opened by each thread.
  23555. **
  23556. ** A single inode can have multiple file descriptors, so each unixFile
  23557. ** structure contains a pointer to an instance of this object and this
  23558. ** object keeps a count of the number of unixFile pointing to it.
  23559. */
  23560. struct unixInodeInfo {
  23561. struct unixFileId fileId; /* The lookup key */
  23562. int nShared; /* Number of SHARED locks held */
  23563. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  23564. unsigned char bProcessLock; /* An exclusive process lock is held */
  23565. int nRef; /* Number of pointers to this structure */
  23566. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  23567. int nLock; /* Number of outstanding file locks */
  23568. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  23569. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  23570. unixInodeInfo *pPrev; /* .... doubly linked */
  23571. #if defined(SQLITE_ENABLE_LOCKING_STYLE)
  23572. unsigned long long sharedByte; /* for AFP simulated shared lock */
  23573. #endif
  23574. #if OS_VXWORKS
  23575. sem_t *pSem; /* Named POSIX semaphore */
  23576. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  23577. #endif
  23578. };
  23579. /*
  23580. ** A lists of all unixInodeInfo objects.
  23581. */
  23582. static unixInodeInfo *inodeList = 0;
  23583. /*
  23584. **
  23585. ** This function - unixLogError_x(), is only ever called via the macro
  23586. ** unixLogError().
  23587. **
  23588. ** It is invoked after an error occurs in an OS function and errno has been
  23589. ** set. It logs a message using sqlite3_log() containing the current value of
  23590. ** errno and, if possible, the human-readable equivalent from strerror() or
  23591. ** strerror_r().
  23592. **
  23593. ** The first argument passed to the macro should be the error code that
  23594. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  23595. ** The two subsequent arguments should be the name of the OS function that
  23596. ** failed (e.g. "unlink", "open") and the the associated file-system path,
  23597. ** if any.
  23598. */
  23599. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  23600. static int unixLogErrorAtLine(
  23601. int errcode, /* SQLite error code */
  23602. const char *zFunc, /* Name of OS function that failed */
  23603. const char *zPath, /* File path associated with error */
  23604. int iLine /* Source line number where error occurred */
  23605. ){
  23606. char *zErr; /* Message from strerror() or equivalent */
  23607. int iErrno = errno; /* Saved syscall error number */
  23608. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  23609. ** the strerror() function to obtain the human-readable error message
  23610. ** equivalent to errno. Otherwise, use strerror_r().
  23611. */
  23612. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  23613. char aErr[80];
  23614. memset(aErr, 0, sizeof(aErr));
  23615. zErr = aErr;
  23616. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  23617. ** assume that the system provides the the GNU version of strerror_r() that
  23618. ** returns a pointer to a buffer containing the error message. That pointer
  23619. ** may point to aErr[], or it may point to some static storage somewhere.
  23620. ** Otherwise, assume that the system provides the POSIX version of
  23621. ** strerror_r(), which always writes an error message into aErr[].
  23622. **
  23623. ** If the code incorrectly assumes that it is the POSIX version that is
  23624. ** available, the error message will often be an empty string. Not a
  23625. ** huge problem. Incorrectly concluding that the GNU version is available
  23626. ** could lead to a segfault though.
  23627. */
  23628. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  23629. zErr =
  23630. # endif
  23631. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  23632. #elif SQLITE_THREADSAFE
  23633. /* This is a threadsafe build, but strerror_r() is not available. */
  23634. zErr = "";
  23635. #else
  23636. /* Non-threadsafe build, use strerror(). */
  23637. zErr = strerror(iErrno);
  23638. #endif
  23639. assert( errcode!=SQLITE_OK );
  23640. if( zPath==0 ) zPath = "";
  23641. sqlite3_log(errcode,
  23642. "os_unix.c:%d: (%d) %s(%s) - %s",
  23643. iLine, iErrno, zFunc, zPath, zErr
  23644. );
  23645. return errcode;
  23646. }
  23647. /*
  23648. ** Close a file descriptor.
  23649. **
  23650. ** We assume that close() almost always works, since it is only in a
  23651. ** very sick application or on a very sick platform that it might fail.
  23652. ** If it does fail, simply leak the file descriptor, but do log the
  23653. ** error.
  23654. **
  23655. ** Note that it is not safe to retry close() after EINTR since the
  23656. ** file descriptor might have already been reused by another thread.
  23657. ** So we don't even try to recover from an EINTR. Just log the error
  23658. ** and move on.
  23659. */
  23660. static void robust_close(unixFile *pFile, int h, int lineno){
  23661. if( osClose(h) ){
  23662. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  23663. pFile ? pFile->zPath : 0, lineno);
  23664. }
  23665. }
  23666. /*
  23667. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  23668. */
  23669. static void closePendingFds(unixFile *pFile){
  23670. unixInodeInfo *pInode = pFile->pInode;
  23671. UnixUnusedFd *p;
  23672. UnixUnusedFd *pNext;
  23673. for(p=pInode->pUnused; p; p=pNext){
  23674. pNext = p->pNext;
  23675. robust_close(pFile, p->fd, __LINE__);
  23676. sqlite3_free(p);
  23677. }
  23678. pInode->pUnused = 0;
  23679. }
  23680. /*
  23681. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  23682. **
  23683. ** The mutex entered using the unixEnterMutex() function must be held
  23684. ** when this function is called.
  23685. */
  23686. static void releaseInodeInfo(unixFile *pFile){
  23687. unixInodeInfo *pInode = pFile->pInode;
  23688. assert( unixMutexHeld() );
  23689. if( ALWAYS(pInode) ){
  23690. pInode->nRef--;
  23691. if( pInode->nRef==0 ){
  23692. assert( pInode->pShmNode==0 );
  23693. closePendingFds(pFile);
  23694. if( pInode->pPrev ){
  23695. assert( pInode->pPrev->pNext==pInode );
  23696. pInode->pPrev->pNext = pInode->pNext;
  23697. }else{
  23698. assert( inodeList==pInode );
  23699. inodeList = pInode->pNext;
  23700. }
  23701. if( pInode->pNext ){
  23702. assert( pInode->pNext->pPrev==pInode );
  23703. pInode->pNext->pPrev = pInode->pPrev;
  23704. }
  23705. sqlite3_free(pInode);
  23706. }
  23707. }
  23708. }
  23709. /*
  23710. ** Given a file descriptor, locate the unixInodeInfo object that
  23711. ** describes that file descriptor. Create a new one if necessary. The
  23712. ** return value might be uninitialized if an error occurs.
  23713. **
  23714. ** The mutex entered using the unixEnterMutex() function must be held
  23715. ** when this function is called.
  23716. **
  23717. ** Return an appropriate error code.
  23718. */
  23719. static int findInodeInfo(
  23720. unixFile *pFile, /* Unix file with file desc used in the key */
  23721. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  23722. ){
  23723. int rc; /* System call return code */
  23724. int fd; /* The file descriptor for pFile */
  23725. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  23726. struct stat statbuf; /* Low-level file information */
  23727. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  23728. assert( unixMutexHeld() );
  23729. /* Get low-level information about the file that we can used to
  23730. ** create a unique name for the file.
  23731. */
  23732. fd = pFile->h;
  23733. rc = osFstat(fd, &statbuf);
  23734. if( rc!=0 ){
  23735. pFile->lastErrno = errno;
  23736. #ifdef EOVERFLOW
  23737. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  23738. #endif
  23739. return SQLITE_IOERR;
  23740. }
  23741. #ifdef __APPLE__
  23742. /* On OS X on an msdos filesystem, the inode number is reported
  23743. ** incorrectly for zero-size files. See ticket #3260. To work
  23744. ** around this problem (we consider it a bug in OS X, not SQLite)
  23745. ** we always increase the file size to 1 by writing a single byte
  23746. ** prior to accessing the inode number. The one byte written is
  23747. ** an ASCII 'S' character which also happens to be the first byte
  23748. ** in the header of every SQLite database. In this way, if there
  23749. ** is a race condition such that another thread has already populated
  23750. ** the first page of the database, no damage is done.
  23751. */
  23752. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  23753. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  23754. if( rc!=1 ){
  23755. pFile->lastErrno = errno;
  23756. return SQLITE_IOERR;
  23757. }
  23758. rc = osFstat(fd, &statbuf);
  23759. if( rc!=0 ){
  23760. pFile->lastErrno = errno;
  23761. return SQLITE_IOERR;
  23762. }
  23763. }
  23764. #endif
  23765. memset(&fileId, 0, sizeof(fileId));
  23766. fileId.dev = statbuf.st_dev;
  23767. #if OS_VXWORKS
  23768. fileId.pId = pFile->pId;
  23769. #else
  23770. fileId.ino = statbuf.st_ino;
  23771. #endif
  23772. pInode = inodeList;
  23773. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  23774. pInode = pInode->pNext;
  23775. }
  23776. if( pInode==0 ){
  23777. pInode = sqlite3_malloc( sizeof(*pInode) );
  23778. if( pInode==0 ){
  23779. return SQLITE_NOMEM;
  23780. }
  23781. memset(pInode, 0, sizeof(*pInode));
  23782. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  23783. pInode->nRef = 1;
  23784. pInode->pNext = inodeList;
  23785. pInode->pPrev = 0;
  23786. if( inodeList ) inodeList->pPrev = pInode;
  23787. inodeList = pInode;
  23788. }else{
  23789. pInode->nRef++;
  23790. }
  23791. *ppInode = pInode;
  23792. return SQLITE_OK;
  23793. }
  23794. /*
  23795. ** This routine checks if there is a RESERVED lock held on the specified
  23796. ** file by this or any other process. If such a lock is held, set *pResOut
  23797. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23798. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23799. */
  23800. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  23801. int rc = SQLITE_OK;
  23802. int reserved = 0;
  23803. unixFile *pFile = (unixFile*)id;
  23804. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23805. assert( pFile );
  23806. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  23807. /* Check if a thread in this process holds such a lock */
  23808. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  23809. reserved = 1;
  23810. }
  23811. /* Otherwise see if some other process holds it.
  23812. */
  23813. #ifndef __DJGPP__
  23814. if( !reserved && !pFile->pInode->bProcessLock ){
  23815. struct flock lock;
  23816. lock.l_whence = SEEK_SET;
  23817. lock.l_start = RESERVED_BYTE;
  23818. lock.l_len = 1;
  23819. lock.l_type = F_WRLCK;
  23820. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  23821. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  23822. pFile->lastErrno = errno;
  23823. } else if( lock.l_type!=F_UNLCK ){
  23824. reserved = 1;
  23825. }
  23826. }
  23827. #endif
  23828. unixLeaveMutex();
  23829. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  23830. *pResOut = reserved;
  23831. return rc;
  23832. }
  23833. /*
  23834. ** Attempt to set a system-lock on the file pFile. The lock is
  23835. ** described by pLock.
  23836. **
  23837. ** If the pFile was opened read/write from unix-excl, then the only lock
  23838. ** ever obtained is an exclusive lock, and it is obtained exactly once
  23839. ** the first time any lock is attempted. All subsequent system locking
  23840. ** operations become no-ops. Locking operations still happen internally,
  23841. ** in order to coordinate access between separate database connections
  23842. ** within this process, but all of that is handled in memory and the
  23843. ** operating system does not participate.
  23844. **
  23845. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  23846. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  23847. ** and is read-only.
  23848. **
  23849. ** Zero is returned if the call completes successfully, or -1 if a call
  23850. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  23851. */
  23852. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  23853. int rc;
  23854. unixInodeInfo *pInode = pFile->pInode;
  23855. assert( unixMutexHeld() );
  23856. assert( pInode!=0 );
  23857. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  23858. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  23859. ){
  23860. if( pInode->bProcessLock==0 ){
  23861. struct flock lock;
  23862. assert( pInode->nLock==0 );
  23863. lock.l_whence = SEEK_SET;
  23864. lock.l_start = SHARED_FIRST;
  23865. lock.l_len = SHARED_SIZE;
  23866. lock.l_type = F_WRLCK;
  23867. rc = osFcntl(pFile->h, F_SETLK, &lock);
  23868. if( rc<0 ) return rc;
  23869. pInode->bProcessLock = 1;
  23870. pInode->nLock++;
  23871. }else{
  23872. rc = 0;
  23873. }
  23874. }else{
  23875. rc = osFcntl(pFile->h, F_SETLK, pLock);
  23876. }
  23877. return rc;
  23878. }
  23879. /*
  23880. ** Lock the file with the lock specified by parameter eFileLock - one
  23881. ** of the following:
  23882. **
  23883. ** (1) SHARED_LOCK
  23884. ** (2) RESERVED_LOCK
  23885. ** (3) PENDING_LOCK
  23886. ** (4) EXCLUSIVE_LOCK
  23887. **
  23888. ** Sometimes when requesting one lock state, additional lock states
  23889. ** are inserted in between. The locking might fail on one of the later
  23890. ** transitions leaving the lock state different from what it started but
  23891. ** still short of its goal. The following chart shows the allowed
  23892. ** transitions and the inserted intermediate states:
  23893. **
  23894. ** UNLOCKED -> SHARED
  23895. ** SHARED -> RESERVED
  23896. ** SHARED -> (PENDING) -> EXCLUSIVE
  23897. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23898. ** PENDING -> EXCLUSIVE
  23899. **
  23900. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23901. ** routine to lower a locking level.
  23902. */
  23903. static int unixLock(sqlite3_file *id, int eFileLock){
  23904. /* The following describes the implementation of the various locks and
  23905. ** lock transitions in terms of the POSIX advisory shared and exclusive
  23906. ** lock primitives (called read-locks and write-locks below, to avoid
  23907. ** confusion with SQLite lock names). The algorithms are complicated
  23908. ** slightly in order to be compatible with windows systems simultaneously
  23909. ** accessing the same database file, in case that is ever required.
  23910. **
  23911. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  23912. ** byte', each single bytes at well known offsets, and the 'shared byte
  23913. ** range', a range of 510 bytes at a well known offset.
  23914. **
  23915. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  23916. ** byte'. If this is successful, a random byte from the 'shared byte
  23917. ** range' is read-locked and the lock on the 'pending byte' released.
  23918. **
  23919. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  23920. ** A RESERVED lock is implemented by grabbing a write-lock on the
  23921. ** 'reserved byte'.
  23922. **
  23923. ** A process may only obtain a PENDING lock after it has obtained a
  23924. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  23925. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  23926. ** obtained, but existing SHARED locks are allowed to persist. A process
  23927. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  23928. ** This property is used by the algorithm for rolling back a journal file
  23929. ** after a crash.
  23930. **
  23931. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  23932. ** implemented by obtaining a write-lock on the entire 'shared byte
  23933. ** range'. Since all other locks require a read-lock on one of the bytes
  23934. ** within this range, this ensures that no other locks are held on the
  23935. ** database.
  23936. **
  23937. ** The reason a single byte cannot be used instead of the 'shared byte
  23938. ** range' is that some versions of windows do not support read-locks. By
  23939. ** locking a random byte from a range, concurrent SHARED locks may exist
  23940. ** even if the locking primitive used is always a write-lock.
  23941. */
  23942. int rc = SQLITE_OK;
  23943. unixFile *pFile = (unixFile*)id;
  23944. unixInodeInfo *pInode = pFile->pInode;
  23945. struct flock lock;
  23946. int tErrno = 0;
  23947. assert( pFile );
  23948. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  23949. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  23950. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  23951. /* If there is already a lock of this type or more restrictive on the
  23952. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  23953. ** unixEnterMutex() hasn't been called yet.
  23954. */
  23955. if( pFile->eFileLock>=eFileLock ){
  23956. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  23957. azFileLock(eFileLock)));
  23958. return SQLITE_OK;
  23959. }
  23960. /* Make sure the locking sequence is correct.
  23961. ** (1) We never move from unlocked to anything higher than shared lock.
  23962. ** (2) SQLite never explicitly requests a pendig lock.
  23963. ** (3) A shared lock is always held when a reserve lock is requested.
  23964. */
  23965. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  23966. assert( eFileLock!=PENDING_LOCK );
  23967. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  23968. /* This mutex is needed because pFile->pInode is shared across threads
  23969. */
  23970. unixEnterMutex();
  23971. pInode = pFile->pInode;
  23972. /* If some thread using this PID has a lock via a different unixFile*
  23973. ** handle that precludes the requested lock, return BUSY.
  23974. */
  23975. if( (pFile->eFileLock!=pInode->eFileLock &&
  23976. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  23977. ){
  23978. rc = SQLITE_BUSY;
  23979. goto end_lock;
  23980. }
  23981. /* If a SHARED lock is requested, and some thread using this PID already
  23982. ** has a SHARED or RESERVED lock, then increment reference counts and
  23983. ** return SQLITE_OK.
  23984. */
  23985. if( eFileLock==SHARED_LOCK &&
  23986. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  23987. assert( eFileLock==SHARED_LOCK );
  23988. assert( pFile->eFileLock==0 );
  23989. assert( pInode->nShared>0 );
  23990. pFile->eFileLock = SHARED_LOCK;
  23991. pInode->nShared++;
  23992. pInode->nLock++;
  23993. goto end_lock;
  23994. }
  23995. /* A PENDING lock is needed before acquiring a SHARED lock and before
  23996. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  23997. ** be released.
  23998. */
  23999. lock.l_len = 1L;
  24000. lock.l_whence = SEEK_SET;
  24001. if( eFileLock==SHARED_LOCK
  24002. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  24003. ){
  24004. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  24005. lock.l_start = PENDING_BYTE;
  24006. if( unixFileLock(pFile, &lock) ){
  24007. tErrno = errno;
  24008. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24009. if( rc!=SQLITE_BUSY ){
  24010. pFile->lastErrno = tErrno;
  24011. }
  24012. goto end_lock;
  24013. }
  24014. }
  24015. /* If control gets to this point, then actually go ahead and make
  24016. ** operating system calls for the specified lock.
  24017. */
  24018. if( eFileLock==SHARED_LOCK ){
  24019. assert( pInode->nShared==0 );
  24020. assert( pInode->eFileLock==0 );
  24021. assert( rc==SQLITE_OK );
  24022. /* Now get the read-lock */
  24023. lock.l_start = SHARED_FIRST;
  24024. lock.l_len = SHARED_SIZE;
  24025. if( unixFileLock(pFile, &lock) ){
  24026. tErrno = errno;
  24027. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24028. }
  24029. /* Drop the temporary PENDING lock */
  24030. lock.l_start = PENDING_BYTE;
  24031. lock.l_len = 1L;
  24032. lock.l_type = F_UNLCK;
  24033. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  24034. /* This could happen with a network mount */
  24035. tErrno = errno;
  24036. rc = SQLITE_IOERR_UNLOCK;
  24037. }
  24038. if( rc ){
  24039. if( rc!=SQLITE_BUSY ){
  24040. pFile->lastErrno = tErrno;
  24041. }
  24042. goto end_lock;
  24043. }else{
  24044. pFile->eFileLock = SHARED_LOCK;
  24045. pInode->nLock++;
  24046. pInode->nShared = 1;
  24047. }
  24048. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  24049. /* We are trying for an exclusive lock but another thread in this
  24050. ** same process is still holding a shared lock. */
  24051. rc = SQLITE_BUSY;
  24052. }else{
  24053. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  24054. ** assumed that there is a SHARED or greater lock on the file
  24055. ** already.
  24056. */
  24057. assert( 0!=pFile->eFileLock );
  24058. lock.l_type = F_WRLCK;
  24059. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  24060. if( eFileLock==RESERVED_LOCK ){
  24061. lock.l_start = RESERVED_BYTE;
  24062. lock.l_len = 1L;
  24063. }else{
  24064. lock.l_start = SHARED_FIRST;
  24065. lock.l_len = SHARED_SIZE;
  24066. }
  24067. if( unixFileLock(pFile, &lock) ){
  24068. tErrno = errno;
  24069. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24070. if( rc!=SQLITE_BUSY ){
  24071. pFile->lastErrno = tErrno;
  24072. }
  24073. }
  24074. }
  24075. #ifndef NDEBUG
  24076. /* Set up the transaction-counter change checking flags when
  24077. ** transitioning from a SHARED to a RESERVED lock. The change
  24078. ** from SHARED to RESERVED marks the beginning of a normal
  24079. ** write operation (not a hot journal rollback).
  24080. */
  24081. if( rc==SQLITE_OK
  24082. && pFile->eFileLock<=SHARED_LOCK
  24083. && eFileLock==RESERVED_LOCK
  24084. ){
  24085. pFile->transCntrChng = 0;
  24086. pFile->dbUpdate = 0;
  24087. pFile->inNormalWrite = 1;
  24088. }
  24089. #endif
  24090. if( rc==SQLITE_OK ){
  24091. pFile->eFileLock = eFileLock;
  24092. pInode->eFileLock = eFileLock;
  24093. }else if( eFileLock==EXCLUSIVE_LOCK ){
  24094. pFile->eFileLock = PENDING_LOCK;
  24095. pInode->eFileLock = PENDING_LOCK;
  24096. }
  24097. end_lock:
  24098. unixLeaveMutex();
  24099. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  24100. rc==SQLITE_OK ? "ok" : "failed"));
  24101. return rc;
  24102. }
  24103. /*
  24104. ** Add the file descriptor used by file handle pFile to the corresponding
  24105. ** pUnused list.
  24106. */
  24107. static void setPendingFd(unixFile *pFile){
  24108. unixInodeInfo *pInode = pFile->pInode;
  24109. UnixUnusedFd *p = pFile->pUnused;
  24110. p->pNext = pInode->pUnused;
  24111. pInode->pUnused = p;
  24112. pFile->h = -1;
  24113. pFile->pUnused = 0;
  24114. }
  24115. /*
  24116. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24117. ** must be either NO_LOCK or SHARED_LOCK.
  24118. **
  24119. ** If the locking level of the file descriptor is already at or below
  24120. ** the requested locking level, this routine is a no-op.
  24121. **
  24122. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  24123. ** the byte range is divided into 2 parts and the first part is unlocked then
  24124. ** set to a read lock, then the other part is simply unlocked. This works
  24125. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  24126. ** remove the write lock on a region when a read lock is set.
  24127. */
  24128. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  24129. unixFile *pFile = (unixFile*)id;
  24130. unixInodeInfo *pInode;
  24131. struct flock lock;
  24132. int rc = SQLITE_OK;
  24133. int h;
  24134. assert( pFile );
  24135. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  24136. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  24137. getpid()));
  24138. assert( eFileLock<=SHARED_LOCK );
  24139. if( pFile->eFileLock<=eFileLock ){
  24140. return SQLITE_OK;
  24141. }
  24142. unixEnterMutex();
  24143. h = pFile->h;
  24144. pInode = pFile->pInode;
  24145. assert( pInode->nShared!=0 );
  24146. if( pFile->eFileLock>SHARED_LOCK ){
  24147. assert( pInode->eFileLock==pFile->eFileLock );
  24148. SimulateIOErrorBenign(1);
  24149. SimulateIOError( h=(-1) )
  24150. SimulateIOErrorBenign(0);
  24151. #ifndef NDEBUG
  24152. /* When reducing a lock such that other processes can start
  24153. ** reading the database file again, make sure that the
  24154. ** transaction counter was updated if any part of the database
  24155. ** file changed. If the transaction counter is not updated,
  24156. ** other connections to the same file might not realize that
  24157. ** the file has changed and hence might not know to flush their
  24158. ** cache. The use of a stale cache can lead to database corruption.
  24159. */
  24160. #if 0
  24161. assert( pFile->inNormalWrite==0
  24162. || pFile->dbUpdate==0
  24163. || pFile->transCntrChng==1 );
  24164. #endif
  24165. pFile->inNormalWrite = 0;
  24166. #endif
  24167. /* downgrading to a shared lock on NFS involves clearing the write lock
  24168. ** before establishing the readlock - to avoid a race condition we downgrade
  24169. ** the lock in 2 blocks, so that part of the range will be covered by a
  24170. ** write lock until the rest is covered by a read lock:
  24171. ** 1: [WWWWW]
  24172. ** 2: [....W]
  24173. ** 3: [RRRRW]
  24174. ** 4: [RRRR.]
  24175. */
  24176. if( eFileLock==SHARED_LOCK ){
  24177. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  24178. (void)handleNFSUnlock;
  24179. assert( handleNFSUnlock==0 );
  24180. #endif
  24181. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24182. if( handleNFSUnlock ){
  24183. int tErrno; /* Error code from system call errors */
  24184. off_t divSize = SHARED_SIZE - 1;
  24185. lock.l_type = F_UNLCK;
  24186. lock.l_whence = SEEK_SET;
  24187. lock.l_start = SHARED_FIRST;
  24188. lock.l_len = divSize;
  24189. if( unixFileLock(pFile, &lock)==(-1) ){
  24190. tErrno = errno;
  24191. rc = SQLITE_IOERR_UNLOCK;
  24192. if( IS_LOCK_ERROR(rc) ){
  24193. pFile->lastErrno = tErrno;
  24194. }
  24195. goto end_unlock;
  24196. }
  24197. lock.l_type = F_RDLCK;
  24198. lock.l_whence = SEEK_SET;
  24199. lock.l_start = SHARED_FIRST;
  24200. lock.l_len = divSize;
  24201. if( unixFileLock(pFile, &lock)==(-1) ){
  24202. tErrno = errno;
  24203. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  24204. if( IS_LOCK_ERROR(rc) ){
  24205. pFile->lastErrno = tErrno;
  24206. }
  24207. goto end_unlock;
  24208. }
  24209. lock.l_type = F_UNLCK;
  24210. lock.l_whence = SEEK_SET;
  24211. lock.l_start = SHARED_FIRST+divSize;
  24212. lock.l_len = SHARED_SIZE-divSize;
  24213. if( unixFileLock(pFile, &lock)==(-1) ){
  24214. tErrno = errno;
  24215. rc = SQLITE_IOERR_UNLOCK;
  24216. if( IS_LOCK_ERROR(rc) ){
  24217. pFile->lastErrno = tErrno;
  24218. }
  24219. goto end_unlock;
  24220. }
  24221. }else
  24222. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  24223. {
  24224. lock.l_type = F_RDLCK;
  24225. lock.l_whence = SEEK_SET;
  24226. lock.l_start = SHARED_FIRST;
  24227. lock.l_len = SHARED_SIZE;
  24228. if( unixFileLock(pFile, &lock) ){
  24229. /* In theory, the call to unixFileLock() cannot fail because another
  24230. ** process is holding an incompatible lock. If it does, this
  24231. ** indicates that the other process is not following the locking
  24232. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  24233. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  24234. ** an assert to fail). */
  24235. rc = SQLITE_IOERR_RDLOCK;
  24236. pFile->lastErrno = errno;
  24237. goto end_unlock;
  24238. }
  24239. }
  24240. }
  24241. lock.l_type = F_UNLCK;
  24242. lock.l_whence = SEEK_SET;
  24243. lock.l_start = PENDING_BYTE;
  24244. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  24245. if( unixFileLock(pFile, &lock)==0 ){
  24246. pInode->eFileLock = SHARED_LOCK;
  24247. }else{
  24248. rc = SQLITE_IOERR_UNLOCK;
  24249. pFile->lastErrno = errno;
  24250. goto end_unlock;
  24251. }
  24252. }
  24253. if( eFileLock==NO_LOCK ){
  24254. /* Decrement the shared lock counter. Release the lock using an
  24255. ** OS call only when all threads in this same process have released
  24256. ** the lock.
  24257. */
  24258. pInode->nShared--;
  24259. if( pInode->nShared==0 ){
  24260. lock.l_type = F_UNLCK;
  24261. lock.l_whence = SEEK_SET;
  24262. lock.l_start = lock.l_len = 0L;
  24263. SimulateIOErrorBenign(1);
  24264. SimulateIOError( h=(-1) )
  24265. SimulateIOErrorBenign(0);
  24266. if( unixFileLock(pFile, &lock)==0 ){
  24267. pInode->eFileLock = NO_LOCK;
  24268. }else{
  24269. rc = SQLITE_IOERR_UNLOCK;
  24270. pFile->lastErrno = errno;
  24271. pInode->eFileLock = NO_LOCK;
  24272. pFile->eFileLock = NO_LOCK;
  24273. }
  24274. }
  24275. /* Decrement the count of locks against this same file. When the
  24276. ** count reaches zero, close any other file descriptors whose close
  24277. ** was deferred because of outstanding locks.
  24278. */
  24279. pInode->nLock--;
  24280. assert( pInode->nLock>=0 );
  24281. if( pInode->nLock==0 ){
  24282. closePendingFds(pFile);
  24283. }
  24284. }
  24285. end_unlock:
  24286. unixLeaveMutex();
  24287. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  24288. return rc;
  24289. }
  24290. /*
  24291. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24292. ** must be either NO_LOCK or SHARED_LOCK.
  24293. **
  24294. ** If the locking level of the file descriptor is already at or below
  24295. ** the requested locking level, this routine is a no-op.
  24296. */
  24297. static int unixUnlock(sqlite3_file *id, int eFileLock){
  24298. return posixUnlock(id, eFileLock, 0);
  24299. }
  24300. /*
  24301. ** This function performs the parts of the "close file" operation
  24302. ** common to all locking schemes. It closes the directory and file
  24303. ** handles, if they are valid, and sets all fields of the unixFile
  24304. ** structure to 0.
  24305. **
  24306. ** It is *not* necessary to hold the mutex when this routine is called,
  24307. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  24308. ** vxworksReleaseFileId() routine.
  24309. */
  24310. static int closeUnixFile(sqlite3_file *id){
  24311. unixFile *pFile = (unixFile*)id;
  24312. if( pFile->dirfd>=0 ){
  24313. robust_close(pFile, pFile->dirfd, __LINE__);
  24314. pFile->dirfd=-1;
  24315. }
  24316. if( pFile->h>=0 ){
  24317. robust_close(pFile, pFile->h, __LINE__);
  24318. pFile->h = -1;
  24319. }
  24320. #if OS_VXWORKS
  24321. if( pFile->pId ){
  24322. if( pFile->isDelete ){
  24323. unlink(pFile->pId->zCanonicalName);
  24324. }
  24325. vxworksReleaseFileId(pFile->pId);
  24326. pFile->pId = 0;
  24327. }
  24328. #endif
  24329. OSTRACE(("CLOSE %-3d\n", pFile->h));
  24330. OpenCounter(-1);
  24331. sqlite3_free(pFile->pUnused);
  24332. memset(pFile, 0, sizeof(unixFile));
  24333. return SQLITE_OK;
  24334. }
  24335. /*
  24336. ** Close a file.
  24337. */
  24338. static int unixClose(sqlite3_file *id){
  24339. int rc = SQLITE_OK;
  24340. unixFile *pFile = (unixFile *)id;
  24341. unixUnlock(id, NO_LOCK);
  24342. unixEnterMutex();
  24343. /* unixFile.pInode is always valid here. Otherwise, a different close
  24344. ** routine (e.g. nolockClose()) would be called instead.
  24345. */
  24346. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  24347. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  24348. /* If there are outstanding locks, do not actually close the file just
  24349. ** yet because that would clear those locks. Instead, add the file
  24350. ** descriptor to pInode->pUnused list. It will be automatically closed
  24351. ** when the last lock is cleared.
  24352. */
  24353. setPendingFd(pFile);
  24354. }
  24355. releaseInodeInfo(pFile);
  24356. rc = closeUnixFile(id);
  24357. unixLeaveMutex();
  24358. return rc;
  24359. }
  24360. /************** End of the posix advisory lock implementation *****************
  24361. ******************************************************************************/
  24362. /******************************************************************************
  24363. ****************************** No-op Locking **********************************
  24364. **
  24365. ** Of the various locking implementations available, this is by far the
  24366. ** simplest: locking is ignored. No attempt is made to lock the database
  24367. ** file for reading or writing.
  24368. **
  24369. ** This locking mode is appropriate for use on read-only databases
  24370. ** (ex: databases that are burned into CD-ROM, for example.) It can
  24371. ** also be used if the application employs some external mechanism to
  24372. ** prevent simultaneous access of the same database by two or more
  24373. ** database connections. But there is a serious risk of database
  24374. ** corruption if this locking mode is used in situations where multiple
  24375. ** database connections are accessing the same database file at the same
  24376. ** time and one or more of those connections are writing.
  24377. */
  24378. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  24379. UNUSED_PARAMETER(NotUsed);
  24380. *pResOut = 0;
  24381. return SQLITE_OK;
  24382. }
  24383. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  24384. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  24385. return SQLITE_OK;
  24386. }
  24387. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  24388. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  24389. return SQLITE_OK;
  24390. }
  24391. /*
  24392. ** Close the file.
  24393. */
  24394. static int nolockClose(sqlite3_file *id) {
  24395. return closeUnixFile(id);
  24396. }
  24397. /******************* End of the no-op lock implementation *********************
  24398. ******************************************************************************/
  24399. /******************************************************************************
  24400. ************************* Begin dot-file Locking ******************************
  24401. **
  24402. ** The dotfile locking implementation uses the existance of separate lock
  24403. ** files in order to control access to the database. This works on just
  24404. ** about every filesystem imaginable. But there are serious downsides:
  24405. **
  24406. ** (1) There is zero concurrency. A single reader blocks all other
  24407. ** connections from reading or writing the database.
  24408. **
  24409. ** (2) An application crash or power loss can leave stale lock files
  24410. ** sitting around that need to be cleared manually.
  24411. **
  24412. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  24413. ** other locking strategy is available.
  24414. **
  24415. ** Dotfile locking works by creating a file in the same directory as the
  24416. ** database and with the same name but with a ".lock" extension added.
  24417. ** The existance of a lock file implies an EXCLUSIVE lock. All other lock
  24418. ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  24419. */
  24420. /*
  24421. ** The file suffix added to the data base filename in order to create the
  24422. ** lock file.
  24423. */
  24424. #define DOTLOCK_SUFFIX ".lock"
  24425. /*
  24426. ** This routine checks if there is a RESERVED lock held on the specified
  24427. ** file by this or any other process. If such a lock is held, set *pResOut
  24428. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24429. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24430. **
  24431. ** In dotfile locking, either a lock exists or it does not. So in this
  24432. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  24433. ** is held on the file and false if the file is unlocked.
  24434. */
  24435. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24436. int rc = SQLITE_OK;
  24437. int reserved = 0;
  24438. unixFile *pFile = (unixFile*)id;
  24439. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24440. assert( pFile );
  24441. /* Check if a thread in this process holds such a lock */
  24442. if( pFile->eFileLock>SHARED_LOCK ){
  24443. /* Either this connection or some other connection in the same process
  24444. ** holds a lock on the file. No need to check further. */
  24445. reserved = 1;
  24446. }else{
  24447. /* The lock is held if and only if the lockfile exists */
  24448. const char *zLockFile = (const char*)pFile->lockingContext;
  24449. reserved = osAccess(zLockFile, 0)==0;
  24450. }
  24451. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  24452. *pResOut = reserved;
  24453. return rc;
  24454. }
  24455. /*
  24456. ** Lock the file with the lock specified by parameter eFileLock - one
  24457. ** of the following:
  24458. **
  24459. ** (1) SHARED_LOCK
  24460. ** (2) RESERVED_LOCK
  24461. ** (3) PENDING_LOCK
  24462. ** (4) EXCLUSIVE_LOCK
  24463. **
  24464. ** Sometimes when requesting one lock state, additional lock states
  24465. ** are inserted in between. The locking might fail on one of the later
  24466. ** transitions leaving the lock state different from what it started but
  24467. ** still short of its goal. The following chart shows the allowed
  24468. ** transitions and the inserted intermediate states:
  24469. **
  24470. ** UNLOCKED -> SHARED
  24471. ** SHARED -> RESERVED
  24472. ** SHARED -> (PENDING) -> EXCLUSIVE
  24473. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24474. ** PENDING -> EXCLUSIVE
  24475. **
  24476. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24477. ** routine to lower a locking level.
  24478. **
  24479. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  24480. ** But we track the other locking levels internally.
  24481. */
  24482. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  24483. unixFile *pFile = (unixFile*)id;
  24484. int fd;
  24485. char *zLockFile = (char *)pFile->lockingContext;
  24486. int rc = SQLITE_OK;
  24487. /* If we have any lock, then the lock file already exists. All we have
  24488. ** to do is adjust our internal record of the lock level.
  24489. */
  24490. if( pFile->eFileLock > NO_LOCK ){
  24491. pFile->eFileLock = eFileLock;
  24492. #if !OS_VXWORKS
  24493. /* Always update the timestamp on the old file */
  24494. utimes(zLockFile, NULL);
  24495. #endif
  24496. return SQLITE_OK;
  24497. }
  24498. /* grab an exclusive lock */
  24499. fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
  24500. if( fd<0 ){
  24501. /* failed to open/create the file, someone else may have stolen the lock */
  24502. int tErrno = errno;
  24503. if( EEXIST == tErrno ){
  24504. rc = SQLITE_BUSY;
  24505. } else {
  24506. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24507. if( IS_LOCK_ERROR(rc) ){
  24508. pFile->lastErrno = tErrno;
  24509. }
  24510. }
  24511. return rc;
  24512. }
  24513. robust_close(pFile, fd, __LINE__);
  24514. /* got it, set the type and return ok */
  24515. pFile->eFileLock = eFileLock;
  24516. return rc;
  24517. }
  24518. /*
  24519. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24520. ** must be either NO_LOCK or SHARED_LOCK.
  24521. **
  24522. ** If the locking level of the file descriptor is already at or below
  24523. ** the requested locking level, this routine is a no-op.
  24524. **
  24525. ** When the locking level reaches NO_LOCK, delete the lock file.
  24526. */
  24527. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  24528. unixFile *pFile = (unixFile*)id;
  24529. char *zLockFile = (char *)pFile->lockingContext;
  24530. assert( pFile );
  24531. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  24532. pFile->eFileLock, getpid()));
  24533. assert( eFileLock<=SHARED_LOCK );
  24534. /* no-op if possible */
  24535. if( pFile->eFileLock==eFileLock ){
  24536. return SQLITE_OK;
  24537. }
  24538. /* To downgrade to shared, simply update our internal notion of the
  24539. ** lock state. No need to mess with the file on disk.
  24540. */
  24541. if( eFileLock==SHARED_LOCK ){
  24542. pFile->eFileLock = SHARED_LOCK;
  24543. return SQLITE_OK;
  24544. }
  24545. /* To fully unlock the database, delete the lock file */
  24546. assert( eFileLock==NO_LOCK );
  24547. if( unlink(zLockFile) ){
  24548. int rc = 0;
  24549. int tErrno = errno;
  24550. if( ENOENT != tErrno ){
  24551. rc = SQLITE_IOERR_UNLOCK;
  24552. }
  24553. if( IS_LOCK_ERROR(rc) ){
  24554. pFile->lastErrno = tErrno;
  24555. }
  24556. return rc;
  24557. }
  24558. pFile->eFileLock = NO_LOCK;
  24559. return SQLITE_OK;
  24560. }
  24561. /*
  24562. ** Close a file. Make sure the lock has been released before closing.
  24563. */
  24564. static int dotlockClose(sqlite3_file *id) {
  24565. int rc;
  24566. if( id ){
  24567. unixFile *pFile = (unixFile*)id;
  24568. dotlockUnlock(id, NO_LOCK);
  24569. sqlite3_free(pFile->lockingContext);
  24570. }
  24571. rc = closeUnixFile(id);
  24572. return rc;
  24573. }
  24574. /****************** End of the dot-file lock implementation *******************
  24575. ******************************************************************************/
  24576. /******************************************************************************
  24577. ************************** Begin flock Locking ********************************
  24578. **
  24579. ** Use the flock() system call to do file locking.
  24580. **
  24581. ** flock() locking is like dot-file locking in that the various
  24582. ** fine-grain locking levels supported by SQLite are collapsed into
  24583. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  24584. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  24585. ** still works when you do this, but concurrency is reduced since
  24586. ** only a single process can be reading the database at a time.
  24587. **
  24588. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  24589. ** compiling for VXWORKS.
  24590. */
  24591. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  24592. /*
  24593. ** Retry flock() calls that fail with EINTR
  24594. */
  24595. #ifdef EINTR
  24596. static int robust_flock(int fd, int op){
  24597. int rc;
  24598. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  24599. return rc;
  24600. }
  24601. #else
  24602. # define robust_flock(a,b) flock(a,b)
  24603. #endif
  24604. /*
  24605. ** This routine checks if there is a RESERVED lock held on the specified
  24606. ** file by this or any other process. If such a lock is held, set *pResOut
  24607. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24608. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24609. */
  24610. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  24611. int rc = SQLITE_OK;
  24612. int reserved = 0;
  24613. unixFile *pFile = (unixFile*)id;
  24614. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24615. assert( pFile );
  24616. /* Check if a thread in this process holds such a lock */
  24617. if( pFile->eFileLock>SHARED_LOCK ){
  24618. reserved = 1;
  24619. }
  24620. /* Otherwise see if some other process holds it. */
  24621. if( !reserved ){
  24622. /* attempt to get the lock */
  24623. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  24624. if( !lrc ){
  24625. /* got the lock, unlock it */
  24626. lrc = robust_flock(pFile->h, LOCK_UN);
  24627. if ( lrc ) {
  24628. int tErrno = errno;
  24629. /* unlock failed with an error */
  24630. lrc = SQLITE_IOERR_UNLOCK;
  24631. if( IS_LOCK_ERROR(lrc) ){
  24632. pFile->lastErrno = tErrno;
  24633. rc = lrc;
  24634. }
  24635. }
  24636. } else {
  24637. int tErrno = errno;
  24638. reserved = 1;
  24639. /* someone else might have it reserved */
  24640. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24641. if( IS_LOCK_ERROR(lrc) ){
  24642. pFile->lastErrno = tErrno;
  24643. rc = lrc;
  24644. }
  24645. }
  24646. }
  24647. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  24648. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24649. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24650. rc = SQLITE_OK;
  24651. reserved=1;
  24652. }
  24653. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24654. *pResOut = reserved;
  24655. return rc;
  24656. }
  24657. /*
  24658. ** Lock the file with the lock specified by parameter eFileLock - one
  24659. ** of the following:
  24660. **
  24661. ** (1) SHARED_LOCK
  24662. ** (2) RESERVED_LOCK
  24663. ** (3) PENDING_LOCK
  24664. ** (4) EXCLUSIVE_LOCK
  24665. **
  24666. ** Sometimes when requesting one lock state, additional lock states
  24667. ** are inserted in between. The locking might fail on one of the later
  24668. ** transitions leaving the lock state different from what it started but
  24669. ** still short of its goal. The following chart shows the allowed
  24670. ** transitions and the inserted intermediate states:
  24671. **
  24672. ** UNLOCKED -> SHARED
  24673. ** SHARED -> RESERVED
  24674. ** SHARED -> (PENDING) -> EXCLUSIVE
  24675. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24676. ** PENDING -> EXCLUSIVE
  24677. **
  24678. ** flock() only really support EXCLUSIVE locks. We track intermediate
  24679. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24680. ** above are really EXCLUSIVE locks and exclude all other processes from
  24681. ** access the file.
  24682. **
  24683. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24684. ** routine to lower a locking level.
  24685. */
  24686. static int flockLock(sqlite3_file *id, int eFileLock) {
  24687. int rc = SQLITE_OK;
  24688. unixFile *pFile = (unixFile*)id;
  24689. assert( pFile );
  24690. /* if we already have a lock, it is exclusive.
  24691. ** Just adjust level and punt on outta here. */
  24692. if (pFile->eFileLock > NO_LOCK) {
  24693. pFile->eFileLock = eFileLock;
  24694. return SQLITE_OK;
  24695. }
  24696. /* grab an exclusive lock */
  24697. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  24698. int tErrno = errno;
  24699. /* didn't get, must be busy */
  24700. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24701. if( IS_LOCK_ERROR(rc) ){
  24702. pFile->lastErrno = tErrno;
  24703. }
  24704. } else {
  24705. /* got it, set the type and return ok */
  24706. pFile->eFileLock = eFileLock;
  24707. }
  24708. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  24709. rc==SQLITE_OK ? "ok" : "failed"));
  24710. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24711. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24712. rc = SQLITE_BUSY;
  24713. }
  24714. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24715. return rc;
  24716. }
  24717. /*
  24718. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24719. ** must be either NO_LOCK or SHARED_LOCK.
  24720. **
  24721. ** If the locking level of the file descriptor is already at or below
  24722. ** the requested locking level, this routine is a no-op.
  24723. */
  24724. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  24725. unixFile *pFile = (unixFile*)id;
  24726. assert( pFile );
  24727. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  24728. pFile->eFileLock, getpid()));
  24729. assert( eFileLock<=SHARED_LOCK );
  24730. /* no-op if possible */
  24731. if( pFile->eFileLock==eFileLock ){
  24732. return SQLITE_OK;
  24733. }
  24734. /* shared can just be set because we always have an exclusive */
  24735. if (eFileLock==SHARED_LOCK) {
  24736. pFile->eFileLock = eFileLock;
  24737. return SQLITE_OK;
  24738. }
  24739. /* no, really, unlock. */
  24740. if( robust_flock(pFile->h, LOCK_UN) ){
  24741. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24742. return SQLITE_OK;
  24743. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24744. return SQLITE_IOERR_UNLOCK;
  24745. }else{
  24746. pFile->eFileLock = NO_LOCK;
  24747. return SQLITE_OK;
  24748. }
  24749. }
  24750. /*
  24751. ** Close a file.
  24752. */
  24753. static int flockClose(sqlite3_file *id) {
  24754. if( id ){
  24755. flockUnlock(id, NO_LOCK);
  24756. }
  24757. return closeUnixFile(id);
  24758. }
  24759. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  24760. /******************* End of the flock lock implementation *********************
  24761. ******************************************************************************/
  24762. /******************************************************************************
  24763. ************************ Begin Named Semaphore Locking ************************
  24764. **
  24765. ** Named semaphore locking is only supported on VxWorks.
  24766. **
  24767. ** Semaphore locking is like dot-lock and flock in that it really only
  24768. ** supports EXCLUSIVE locking. Only a single process can read or write
  24769. ** the database file at a time. This reduces potential concurrency, but
  24770. ** makes the lock implementation much easier.
  24771. */
  24772. #if OS_VXWORKS
  24773. /*
  24774. ** This routine checks if there is a RESERVED lock held on the specified
  24775. ** file by this or any other process. If such a lock is held, set *pResOut
  24776. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24777. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24778. */
  24779. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24780. int rc = SQLITE_OK;
  24781. int reserved = 0;
  24782. unixFile *pFile = (unixFile*)id;
  24783. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24784. assert( pFile );
  24785. /* Check if a thread in this process holds such a lock */
  24786. if( pFile->eFileLock>SHARED_LOCK ){
  24787. reserved = 1;
  24788. }
  24789. /* Otherwise see if some other process holds it. */
  24790. if( !reserved ){
  24791. sem_t *pSem = pFile->pInode->pSem;
  24792. struct stat statBuf;
  24793. if( sem_trywait(pSem)==-1 ){
  24794. int tErrno = errno;
  24795. if( EAGAIN != tErrno ){
  24796. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  24797. pFile->lastErrno = tErrno;
  24798. } else {
  24799. /* someone else has the lock when we are in NO_LOCK */
  24800. reserved = (pFile->eFileLock < SHARED_LOCK);
  24801. }
  24802. }else{
  24803. /* we could have it if we want it */
  24804. sem_post(pSem);
  24805. }
  24806. }
  24807. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  24808. *pResOut = reserved;
  24809. return rc;
  24810. }
  24811. /*
  24812. ** Lock the file with the lock specified by parameter eFileLock - one
  24813. ** of the following:
  24814. **
  24815. ** (1) SHARED_LOCK
  24816. ** (2) RESERVED_LOCK
  24817. ** (3) PENDING_LOCK
  24818. ** (4) EXCLUSIVE_LOCK
  24819. **
  24820. ** Sometimes when requesting one lock state, additional lock states
  24821. ** are inserted in between. The locking might fail on one of the later
  24822. ** transitions leaving the lock state different from what it started but
  24823. ** still short of its goal. The following chart shows the allowed
  24824. ** transitions and the inserted intermediate states:
  24825. **
  24826. ** UNLOCKED -> SHARED
  24827. ** SHARED -> RESERVED
  24828. ** SHARED -> (PENDING) -> EXCLUSIVE
  24829. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24830. ** PENDING -> EXCLUSIVE
  24831. **
  24832. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  24833. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24834. ** above are really EXCLUSIVE locks and exclude all other processes from
  24835. ** access the file.
  24836. **
  24837. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24838. ** routine to lower a locking level.
  24839. */
  24840. static int semLock(sqlite3_file *id, int eFileLock) {
  24841. unixFile *pFile = (unixFile*)id;
  24842. int fd;
  24843. sem_t *pSem = pFile->pInode->pSem;
  24844. int rc = SQLITE_OK;
  24845. /* if we already have a lock, it is exclusive.
  24846. ** Just adjust level and punt on outta here. */
  24847. if (pFile->eFileLock > NO_LOCK) {
  24848. pFile->eFileLock = eFileLock;
  24849. rc = SQLITE_OK;
  24850. goto sem_end_lock;
  24851. }
  24852. /* lock semaphore now but bail out when already locked. */
  24853. if( sem_trywait(pSem)==-1 ){
  24854. rc = SQLITE_BUSY;
  24855. goto sem_end_lock;
  24856. }
  24857. /* got it, set the type and return ok */
  24858. pFile->eFileLock = eFileLock;
  24859. sem_end_lock:
  24860. return rc;
  24861. }
  24862. /*
  24863. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24864. ** must be either NO_LOCK or SHARED_LOCK.
  24865. **
  24866. ** If the locking level of the file descriptor is already at or below
  24867. ** the requested locking level, this routine is a no-op.
  24868. */
  24869. static int semUnlock(sqlite3_file *id, int eFileLock) {
  24870. unixFile *pFile = (unixFile*)id;
  24871. sem_t *pSem = pFile->pInode->pSem;
  24872. assert( pFile );
  24873. assert( pSem );
  24874. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  24875. pFile->eFileLock, getpid()));
  24876. assert( eFileLock<=SHARED_LOCK );
  24877. /* no-op if possible */
  24878. if( pFile->eFileLock==eFileLock ){
  24879. return SQLITE_OK;
  24880. }
  24881. /* shared can just be set because we always have an exclusive */
  24882. if (eFileLock==SHARED_LOCK) {
  24883. pFile->eFileLock = eFileLock;
  24884. return SQLITE_OK;
  24885. }
  24886. /* no, really unlock. */
  24887. if ( sem_post(pSem)==-1 ) {
  24888. int rc, tErrno = errno;
  24889. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  24890. if( IS_LOCK_ERROR(rc) ){
  24891. pFile->lastErrno = tErrno;
  24892. }
  24893. return rc;
  24894. }
  24895. pFile->eFileLock = NO_LOCK;
  24896. return SQLITE_OK;
  24897. }
  24898. /*
  24899. ** Close a file.
  24900. */
  24901. static int semClose(sqlite3_file *id) {
  24902. if( id ){
  24903. unixFile *pFile = (unixFile*)id;
  24904. semUnlock(id, NO_LOCK);
  24905. assert( pFile );
  24906. unixEnterMutex();
  24907. releaseInodeInfo(pFile);
  24908. unixLeaveMutex();
  24909. closeUnixFile(id);
  24910. }
  24911. return SQLITE_OK;
  24912. }
  24913. #endif /* OS_VXWORKS */
  24914. /*
  24915. ** Named semaphore locking is only available on VxWorks.
  24916. **
  24917. *************** End of the named semaphore lock implementation ****************
  24918. ******************************************************************************/
  24919. /******************************************************************************
  24920. *************************** Begin AFP Locking *********************************
  24921. **
  24922. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  24923. ** on Apple Macintosh computers - both OS9 and OSX.
  24924. **
  24925. ** Third-party implementations of AFP are available. But this code here
  24926. ** only works on OSX.
  24927. */
  24928. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24929. /*
  24930. ** The afpLockingContext structure contains all afp lock specific state
  24931. */
  24932. typedef struct afpLockingContext afpLockingContext;
  24933. struct afpLockingContext {
  24934. int reserved;
  24935. const char *dbPath; /* Name of the open file */
  24936. };
  24937. struct ByteRangeLockPB2
  24938. {
  24939. unsigned long long offset; /* offset to first byte to lock */
  24940. unsigned long long length; /* nbr of bytes to lock */
  24941. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  24942. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  24943. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  24944. int fd; /* file desc to assoc this lock with */
  24945. };
  24946. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  24947. /*
  24948. ** This is a utility for setting or clearing a bit-range lock on an
  24949. ** AFP filesystem.
  24950. **
  24951. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  24952. */
  24953. static int afpSetLock(
  24954. const char *path, /* Name of the file to be locked or unlocked */
  24955. unixFile *pFile, /* Open file descriptor on path */
  24956. unsigned long long offset, /* First byte to be locked */
  24957. unsigned long long length, /* Number of bytes to lock */
  24958. int setLockFlag /* True to set lock. False to clear lock */
  24959. ){
  24960. struct ByteRangeLockPB2 pb;
  24961. int err;
  24962. pb.unLockFlag = setLockFlag ? 0 : 1;
  24963. pb.startEndFlag = 0;
  24964. pb.offset = offset;
  24965. pb.length = length;
  24966. pb.fd = pFile->h;
  24967. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  24968. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  24969. offset, length));
  24970. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  24971. if ( err==-1 ) {
  24972. int rc;
  24973. int tErrno = errno;
  24974. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  24975. path, tErrno, strerror(tErrno)));
  24976. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  24977. rc = SQLITE_BUSY;
  24978. #else
  24979. rc = sqliteErrorFromPosixError(tErrno,
  24980. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  24981. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  24982. if( IS_LOCK_ERROR(rc) ){
  24983. pFile->lastErrno = tErrno;
  24984. }
  24985. return rc;
  24986. } else {
  24987. return SQLITE_OK;
  24988. }
  24989. }
  24990. /*
  24991. ** This routine checks if there is a RESERVED lock held on the specified
  24992. ** file by this or any other process. If such a lock is held, set *pResOut
  24993. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24994. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24995. */
  24996. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  24997. int rc = SQLITE_OK;
  24998. int reserved = 0;
  24999. unixFile *pFile = (unixFile*)id;
  25000. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25001. assert( pFile );
  25002. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  25003. if( context->reserved ){
  25004. *pResOut = 1;
  25005. return SQLITE_OK;
  25006. }
  25007. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  25008. /* Check if a thread in this process holds such a lock */
  25009. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  25010. reserved = 1;
  25011. }
  25012. /* Otherwise see if some other process holds it.
  25013. */
  25014. if( !reserved ){
  25015. /* lock the RESERVED byte */
  25016. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  25017. if( SQLITE_OK==lrc ){
  25018. /* if we succeeded in taking the reserved lock, unlock it to restore
  25019. ** the original state */
  25020. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  25021. } else {
  25022. /* if we failed to get the lock then someone else must have it */
  25023. reserved = 1;
  25024. }
  25025. if( IS_LOCK_ERROR(lrc) ){
  25026. rc=lrc;
  25027. }
  25028. }
  25029. unixLeaveMutex();
  25030. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  25031. *pResOut = reserved;
  25032. return rc;
  25033. }
  25034. /*
  25035. ** Lock the file with the lock specified by parameter eFileLock - one
  25036. ** of the following:
  25037. **
  25038. ** (1) SHARED_LOCK
  25039. ** (2) RESERVED_LOCK
  25040. ** (3) PENDING_LOCK
  25041. ** (4) EXCLUSIVE_LOCK
  25042. **
  25043. ** Sometimes when requesting one lock state, additional lock states
  25044. ** are inserted in between. The locking might fail on one of the later
  25045. ** transitions leaving the lock state different from what it started but
  25046. ** still short of its goal. The following chart shows the allowed
  25047. ** transitions and the inserted intermediate states:
  25048. **
  25049. ** UNLOCKED -> SHARED
  25050. ** SHARED -> RESERVED
  25051. ** SHARED -> (PENDING) -> EXCLUSIVE
  25052. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25053. ** PENDING -> EXCLUSIVE
  25054. **
  25055. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25056. ** routine to lower a locking level.
  25057. */
  25058. static int afpLock(sqlite3_file *id, int eFileLock){
  25059. int rc = SQLITE_OK;
  25060. unixFile *pFile = (unixFile*)id;
  25061. unixInodeInfo *pInode = pFile->pInode;
  25062. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  25063. assert( pFile );
  25064. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  25065. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  25066. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  25067. /* If there is already a lock of this type or more restrictive on the
  25068. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  25069. ** unixEnterMutex() hasn't been called yet.
  25070. */
  25071. if( pFile->eFileLock>=eFileLock ){
  25072. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  25073. azFileLock(eFileLock)));
  25074. return SQLITE_OK;
  25075. }
  25076. /* Make sure the locking sequence is correct
  25077. ** (1) We never move from unlocked to anything higher than shared lock.
  25078. ** (2) SQLite never explicitly requests a pendig lock.
  25079. ** (3) A shared lock is always held when a reserve lock is requested.
  25080. */
  25081. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  25082. assert( eFileLock!=PENDING_LOCK );
  25083. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  25084. /* This mutex is needed because pFile->pInode is shared across threads
  25085. */
  25086. unixEnterMutex();
  25087. pInode = pFile->pInode;
  25088. /* If some thread using this PID has a lock via a different unixFile*
  25089. ** handle that precludes the requested lock, return BUSY.
  25090. */
  25091. if( (pFile->eFileLock!=pInode->eFileLock &&
  25092. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  25093. ){
  25094. rc = SQLITE_BUSY;
  25095. goto afp_end_lock;
  25096. }
  25097. /* If a SHARED lock is requested, and some thread using this PID already
  25098. ** has a SHARED or RESERVED lock, then increment reference counts and
  25099. ** return SQLITE_OK.
  25100. */
  25101. if( eFileLock==SHARED_LOCK &&
  25102. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  25103. assert( eFileLock==SHARED_LOCK );
  25104. assert( pFile->eFileLock==0 );
  25105. assert( pInode->nShared>0 );
  25106. pFile->eFileLock = SHARED_LOCK;
  25107. pInode->nShared++;
  25108. pInode->nLock++;
  25109. goto afp_end_lock;
  25110. }
  25111. /* A PENDING lock is needed before acquiring a SHARED lock and before
  25112. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  25113. ** be released.
  25114. */
  25115. if( eFileLock==SHARED_LOCK
  25116. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  25117. ){
  25118. int failed;
  25119. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  25120. if (failed) {
  25121. rc = failed;
  25122. goto afp_end_lock;
  25123. }
  25124. }
  25125. /* If control gets to this point, then actually go ahead and make
  25126. ** operating system calls for the specified lock.
  25127. */
  25128. if( eFileLock==SHARED_LOCK ){
  25129. int lrc1, lrc2, lrc1Errno;
  25130. long lk, mask;
  25131. assert( pInode->nShared==0 );
  25132. assert( pInode->eFileLock==0 );
  25133. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  25134. /* Now get the read-lock SHARED_LOCK */
  25135. /* note that the quality of the randomness doesn't matter that much */
  25136. lk = random();
  25137. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  25138. lrc1 = afpSetLock(context->dbPath, pFile,
  25139. SHARED_FIRST+pInode->sharedByte, 1, 1);
  25140. if( IS_LOCK_ERROR(lrc1) ){
  25141. lrc1Errno = pFile->lastErrno;
  25142. }
  25143. /* Drop the temporary PENDING lock */
  25144. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  25145. if( IS_LOCK_ERROR(lrc1) ) {
  25146. pFile->lastErrno = lrc1Errno;
  25147. rc = lrc1;
  25148. goto afp_end_lock;
  25149. } else if( IS_LOCK_ERROR(lrc2) ){
  25150. rc = lrc2;
  25151. goto afp_end_lock;
  25152. } else if( lrc1 != SQLITE_OK ) {
  25153. rc = lrc1;
  25154. } else {
  25155. pFile->eFileLock = SHARED_LOCK;
  25156. pInode->nLock++;
  25157. pInode->nShared = 1;
  25158. }
  25159. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  25160. /* We are trying for an exclusive lock but another thread in this
  25161. ** same process is still holding a shared lock. */
  25162. rc = SQLITE_BUSY;
  25163. }else{
  25164. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  25165. ** assumed that there is a SHARED or greater lock on the file
  25166. ** already.
  25167. */
  25168. int failed = 0;
  25169. assert( 0!=pFile->eFileLock );
  25170. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  25171. /* Acquire a RESERVED lock */
  25172. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  25173. if( !failed ){
  25174. context->reserved = 1;
  25175. }
  25176. }
  25177. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  25178. /* Acquire an EXCLUSIVE lock */
  25179. /* Remove the shared lock before trying the range. we'll need to
  25180. ** reestablish the shared lock if we can't get the afpUnlock
  25181. */
  25182. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  25183. pInode->sharedByte, 1, 0)) ){
  25184. int failed2 = SQLITE_OK;
  25185. /* now attemmpt to get the exclusive lock range */
  25186. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  25187. SHARED_SIZE, 1);
  25188. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  25189. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  25190. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  25191. ** a critical I/O error
  25192. */
  25193. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  25194. SQLITE_IOERR_LOCK;
  25195. goto afp_end_lock;
  25196. }
  25197. }else{
  25198. rc = failed;
  25199. }
  25200. }
  25201. if( failed ){
  25202. rc = failed;
  25203. }
  25204. }
  25205. if( rc==SQLITE_OK ){
  25206. pFile->eFileLock = eFileLock;
  25207. pInode->eFileLock = eFileLock;
  25208. }else if( eFileLock==EXCLUSIVE_LOCK ){
  25209. pFile->eFileLock = PENDING_LOCK;
  25210. pInode->eFileLock = PENDING_LOCK;
  25211. }
  25212. afp_end_lock:
  25213. unixLeaveMutex();
  25214. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  25215. rc==SQLITE_OK ? "ok" : "failed"));
  25216. return rc;
  25217. }
  25218. /*
  25219. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25220. ** must be either NO_LOCK or SHARED_LOCK.
  25221. **
  25222. ** If the locking level of the file descriptor is already at or below
  25223. ** the requested locking level, this routine is a no-op.
  25224. */
  25225. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  25226. int rc = SQLITE_OK;
  25227. unixFile *pFile = (unixFile*)id;
  25228. unixInodeInfo *pInode;
  25229. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  25230. int skipShared = 0;
  25231. #ifdef SQLITE_TEST
  25232. int h = pFile->h;
  25233. #endif
  25234. assert( pFile );
  25235. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  25236. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  25237. getpid()));
  25238. assert( eFileLock<=SHARED_LOCK );
  25239. if( pFile->eFileLock<=eFileLock ){
  25240. return SQLITE_OK;
  25241. }
  25242. unixEnterMutex();
  25243. pInode = pFile->pInode;
  25244. assert( pInode->nShared!=0 );
  25245. if( pFile->eFileLock>SHARED_LOCK ){
  25246. assert( pInode->eFileLock==pFile->eFileLock );
  25247. SimulateIOErrorBenign(1);
  25248. SimulateIOError( h=(-1) )
  25249. SimulateIOErrorBenign(0);
  25250. #ifndef NDEBUG
  25251. /* When reducing a lock such that other processes can start
  25252. ** reading the database file again, make sure that the
  25253. ** transaction counter was updated if any part of the database
  25254. ** file changed. If the transaction counter is not updated,
  25255. ** other connections to the same file might not realize that
  25256. ** the file has changed and hence might not know to flush their
  25257. ** cache. The use of a stale cache can lead to database corruption.
  25258. */
  25259. assert( pFile->inNormalWrite==0
  25260. || pFile->dbUpdate==0
  25261. || pFile->transCntrChng==1 );
  25262. pFile->inNormalWrite = 0;
  25263. #endif
  25264. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  25265. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  25266. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  25267. /* only re-establish the shared lock if necessary */
  25268. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  25269. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  25270. } else {
  25271. skipShared = 1;
  25272. }
  25273. }
  25274. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  25275. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  25276. }
  25277. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  25278. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  25279. if( !rc ){
  25280. context->reserved = 0;
  25281. }
  25282. }
  25283. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  25284. pInode->eFileLock = SHARED_LOCK;
  25285. }
  25286. }
  25287. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  25288. /* Decrement the shared lock counter. Release the lock using an
  25289. ** OS call only when all threads in this same process have released
  25290. ** the lock.
  25291. */
  25292. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  25293. pInode->nShared--;
  25294. if( pInode->nShared==0 ){
  25295. SimulateIOErrorBenign(1);
  25296. SimulateIOError( h=(-1) )
  25297. SimulateIOErrorBenign(0);
  25298. if( !skipShared ){
  25299. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  25300. }
  25301. if( !rc ){
  25302. pInode->eFileLock = NO_LOCK;
  25303. pFile->eFileLock = NO_LOCK;
  25304. }
  25305. }
  25306. if( rc==SQLITE_OK ){
  25307. pInode->nLock--;
  25308. assert( pInode->nLock>=0 );
  25309. if( pInode->nLock==0 ){
  25310. closePendingFds(pFile);
  25311. }
  25312. }
  25313. }
  25314. unixLeaveMutex();
  25315. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  25316. return rc;
  25317. }
  25318. /*
  25319. ** Close a file & cleanup AFP specific locking context
  25320. */
  25321. static int afpClose(sqlite3_file *id) {
  25322. int rc = SQLITE_OK;
  25323. if( id ){
  25324. unixFile *pFile = (unixFile*)id;
  25325. afpUnlock(id, NO_LOCK);
  25326. unixEnterMutex();
  25327. if( pFile->pInode && pFile->pInode->nLock ){
  25328. /* If there are outstanding locks, do not actually close the file just
  25329. ** yet because that would clear those locks. Instead, add the file
  25330. ** descriptor to pInode->aPending. It will be automatically closed when
  25331. ** the last lock is cleared.
  25332. */
  25333. setPendingFd(pFile);
  25334. }
  25335. releaseInodeInfo(pFile);
  25336. sqlite3_free(pFile->lockingContext);
  25337. rc = closeUnixFile(id);
  25338. unixLeaveMutex();
  25339. }
  25340. return rc;
  25341. }
  25342. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25343. /*
  25344. ** The code above is the AFP lock implementation. The code is specific
  25345. ** to MacOSX and does not work on other unix platforms. No alternative
  25346. ** is available. If you don't compile for a mac, then the "unix-afp"
  25347. ** VFS is not available.
  25348. **
  25349. ********************* End of the AFP lock implementation **********************
  25350. ******************************************************************************/
  25351. /******************************************************************************
  25352. *************************** Begin NFS Locking ********************************/
  25353. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25354. /*
  25355. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25356. ** must be either NO_LOCK or SHARED_LOCK.
  25357. **
  25358. ** If the locking level of the file descriptor is already at or below
  25359. ** the requested locking level, this routine is a no-op.
  25360. */
  25361. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  25362. return posixUnlock(id, eFileLock, 1);
  25363. }
  25364. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25365. /*
  25366. ** The code above is the NFS lock implementation. The code is specific
  25367. ** to MacOSX and does not work on other unix platforms. No alternative
  25368. ** is available.
  25369. **
  25370. ********************* End of the NFS lock implementation **********************
  25371. ******************************************************************************/
  25372. /******************************************************************************
  25373. **************** Non-locking sqlite3_file methods *****************************
  25374. **
  25375. ** The next division contains implementations for all methods of the
  25376. ** sqlite3_file object other than the locking methods. The locking
  25377. ** methods were defined in divisions above (one locking method per
  25378. ** division). Those methods that are common to all locking modes
  25379. ** are gather together into this division.
  25380. */
  25381. /*
  25382. ** Seek to the offset passed as the second argument, then read cnt
  25383. ** bytes into pBuf. Return the number of bytes actually read.
  25384. **
  25385. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  25386. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  25387. ** one system to another. Since SQLite does not define USE_PREAD
  25388. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  25389. ** See tickets #2741 and #2681.
  25390. **
  25391. ** To avoid stomping the errno value on a failed read the lastErrno value
  25392. ** is set before returning.
  25393. */
  25394. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  25395. int got;
  25396. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  25397. i64 newOffset;
  25398. #endif
  25399. TIMER_START;
  25400. #if defined(USE_PREAD)
  25401. do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
  25402. SimulateIOError( got = -1 );
  25403. #elif defined(USE_PREAD64)
  25404. do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
  25405. SimulateIOError( got = -1 );
  25406. #else
  25407. newOffset = lseek(id->h, offset, SEEK_SET);
  25408. SimulateIOError( newOffset-- );
  25409. if( newOffset!=offset ){
  25410. if( newOffset == -1 ){
  25411. ((unixFile*)id)->lastErrno = errno;
  25412. }else{
  25413. ((unixFile*)id)->lastErrno = 0;
  25414. }
  25415. return -1;
  25416. }
  25417. do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
  25418. #endif
  25419. TIMER_END;
  25420. if( got<0 ){
  25421. ((unixFile*)id)->lastErrno = errno;
  25422. }
  25423. OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
  25424. return got;
  25425. }
  25426. /*
  25427. ** Read data from a file into a buffer. Return SQLITE_OK if all
  25428. ** bytes were read successfully and SQLITE_IOERR if anything goes
  25429. ** wrong.
  25430. */
  25431. static int unixRead(
  25432. sqlite3_file *id,
  25433. void *pBuf,
  25434. int amt,
  25435. sqlite3_int64 offset
  25436. ){
  25437. unixFile *pFile = (unixFile *)id;
  25438. int got;
  25439. assert( id );
  25440. /* If this is a database file (not a journal, master-journal or temp
  25441. ** file), the bytes in the locking range should never be read or written. */
  25442. #if 0
  25443. assert( pFile->pUnused==0
  25444. || offset>=PENDING_BYTE+512
  25445. || offset+amt<=PENDING_BYTE
  25446. );
  25447. #endif
  25448. got = seekAndRead(pFile, offset, pBuf, amt);
  25449. if( got==amt ){
  25450. return SQLITE_OK;
  25451. }else if( got<0 ){
  25452. /* lastErrno set by seekAndRead */
  25453. return SQLITE_IOERR_READ;
  25454. }else{
  25455. pFile->lastErrno = 0; /* not a system error */
  25456. /* Unread parts of the buffer must be zero-filled */
  25457. memset(&((char*)pBuf)[got], 0, amt-got);
  25458. return SQLITE_IOERR_SHORT_READ;
  25459. }
  25460. }
  25461. /*
  25462. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  25463. ** Return the number of bytes actually read. Update the offset.
  25464. **
  25465. ** To avoid stomping the errno value on a failed write the lastErrno value
  25466. ** is set before returning.
  25467. */
  25468. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  25469. int got;
  25470. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  25471. i64 newOffset;
  25472. #endif
  25473. TIMER_START;
  25474. #if defined(USE_PREAD)
  25475. do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
  25476. #elif defined(USE_PREAD64)
  25477. do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
  25478. #else
  25479. newOffset = lseek(id->h, offset, SEEK_SET);
  25480. SimulateIOError( newOffset-- );
  25481. if( newOffset!=offset ){
  25482. if( newOffset == -1 ){
  25483. ((unixFile*)id)->lastErrno = errno;
  25484. }else{
  25485. ((unixFile*)id)->lastErrno = 0;
  25486. }
  25487. return -1;
  25488. }
  25489. do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
  25490. #endif
  25491. TIMER_END;
  25492. if( got<0 ){
  25493. ((unixFile*)id)->lastErrno = errno;
  25494. }
  25495. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
  25496. return got;
  25497. }
  25498. /*
  25499. ** Write data from a buffer into a file. Return SQLITE_OK on success
  25500. ** or some other error code on failure.
  25501. */
  25502. static int unixWrite(
  25503. sqlite3_file *id,
  25504. const void *pBuf,
  25505. int amt,
  25506. sqlite3_int64 offset
  25507. ){
  25508. unixFile *pFile = (unixFile*)id;
  25509. int wrote = 0;
  25510. assert( id );
  25511. assert( amt>0 );
  25512. /* If this is a database file (not a journal, master-journal or temp
  25513. ** file), the bytes in the locking range should never be read or written. */
  25514. #if 0
  25515. assert( pFile->pUnused==0
  25516. || offset>=PENDING_BYTE+512
  25517. || offset+amt<=PENDING_BYTE
  25518. );
  25519. #endif
  25520. #ifndef NDEBUG
  25521. /* If we are doing a normal write to a database file (as opposed to
  25522. ** doing a hot-journal rollback or a write to some file other than a
  25523. ** normal database file) then record the fact that the database
  25524. ** has changed. If the transaction counter is modified, record that
  25525. ** fact too.
  25526. */
  25527. if( pFile->inNormalWrite ){
  25528. pFile->dbUpdate = 1; /* The database has been modified */
  25529. if( offset<=24 && offset+amt>=27 ){
  25530. int rc;
  25531. char oldCntr[4];
  25532. SimulateIOErrorBenign(1);
  25533. rc = seekAndRead(pFile, 24, oldCntr, 4);
  25534. SimulateIOErrorBenign(0);
  25535. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  25536. pFile->transCntrChng = 1; /* The transaction counter has changed */
  25537. }
  25538. }
  25539. }
  25540. #endif
  25541. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  25542. amt -= wrote;
  25543. offset += wrote;
  25544. pBuf = &((char*)pBuf)[wrote];
  25545. }
  25546. SimulateIOError(( wrote=(-1), amt=1 ));
  25547. SimulateDiskfullError(( wrote=0, amt=1 ));
  25548. if( amt>0 ){
  25549. if( wrote<0 ){
  25550. /* lastErrno set by seekAndWrite */
  25551. return SQLITE_IOERR_WRITE;
  25552. }else{
  25553. pFile->lastErrno = 0; /* not a system error */
  25554. return SQLITE_FULL;
  25555. }
  25556. }
  25557. return SQLITE_OK;
  25558. }
  25559. #ifdef SQLITE_TEST
  25560. /*
  25561. ** Count the number of fullsyncs and normal syncs. This is used to test
  25562. ** that syncs and fullsyncs are occurring at the right times.
  25563. */
  25564. SQLITE_API int sqlite3_sync_count = 0;
  25565. SQLITE_API int sqlite3_fullsync_count = 0;
  25566. #endif
  25567. /*
  25568. ** We do not trust systems to provide a working fdatasync(). Some do.
  25569. ** Others do no. To be safe, we will stick with the (slower) fsync().
  25570. ** If you know that your system does support fdatasync() correctly,
  25571. ** then simply compile with -Dfdatasync=fdatasync
  25572. */
  25573. #if !defined(fdatasync) && !defined(__linux__)
  25574. # define fdatasync fsync
  25575. #endif
  25576. /*
  25577. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  25578. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  25579. ** only available on Mac OS X. But that could change.
  25580. */
  25581. #ifdef F_FULLFSYNC
  25582. # define HAVE_FULLFSYNC 1
  25583. #else
  25584. # define HAVE_FULLFSYNC 0
  25585. #endif
  25586. /*
  25587. ** The fsync() system call does not work as advertised on many
  25588. ** unix systems. The following procedure is an attempt to make
  25589. ** it work better.
  25590. **
  25591. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  25592. ** for testing when we want to run through the test suite quickly.
  25593. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  25594. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  25595. ** or power failure will likely corrupt the database file.
  25596. **
  25597. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  25598. ** The idea behind dataOnly is that it should only write the file content
  25599. ** to disk, not the inode. We only set dataOnly if the file size is
  25600. ** unchanged since the file size is part of the inode. However,
  25601. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  25602. ** file size has changed. The only real difference between fdatasync()
  25603. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  25604. ** inode if the mtime or owner or other inode attributes have changed.
  25605. ** We only care about the file size, not the other file attributes, so
  25606. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  25607. ** So, we always use fdatasync() if it is available, regardless of
  25608. ** the value of the dataOnly flag.
  25609. */
  25610. static int full_fsync(int fd, int fullSync, int dataOnly){
  25611. int rc;
  25612. /* The following "ifdef/elif/else/" block has the same structure as
  25613. ** the one below. It is replicated here solely to avoid cluttering
  25614. ** up the real code with the UNUSED_PARAMETER() macros.
  25615. */
  25616. #ifdef SQLITE_NO_SYNC
  25617. UNUSED_PARAMETER(fd);
  25618. UNUSED_PARAMETER(fullSync);
  25619. UNUSED_PARAMETER(dataOnly);
  25620. #elif HAVE_FULLFSYNC
  25621. UNUSED_PARAMETER(dataOnly);
  25622. #else
  25623. UNUSED_PARAMETER(fullSync);
  25624. UNUSED_PARAMETER(dataOnly);
  25625. #endif
  25626. /* Record the number of times that we do a normal fsync() and
  25627. ** FULLSYNC. This is used during testing to verify that this procedure
  25628. ** gets called with the correct arguments.
  25629. */
  25630. #ifdef SQLITE_TEST
  25631. if( fullSync ) sqlite3_fullsync_count++;
  25632. sqlite3_sync_count++;
  25633. #endif
  25634. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  25635. ** no-op
  25636. */
  25637. #ifdef SQLITE_NO_SYNC
  25638. rc = SQLITE_OK;
  25639. #elif HAVE_FULLFSYNC
  25640. if( fullSync ){
  25641. rc = osFcntl(fd, F_FULLFSYNC, 0);
  25642. }else{
  25643. rc = 1;
  25644. }
  25645. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  25646. ** It shouldn't be possible for fullfsync to fail on the local
  25647. ** file system (on OSX), so failure indicates that FULLFSYNC
  25648. ** isn't supported for this file system. So, attempt an fsync
  25649. ** and (for now) ignore the overhead of a superfluous fcntl call.
  25650. ** It'd be better to detect fullfsync support once and avoid
  25651. ** the fcntl call every time sync is called.
  25652. */
  25653. if( rc ) rc = fsync(fd);
  25654. #elif defined(__APPLE__)
  25655. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  25656. ** so currently we default to the macro that redefines fdatasync to fsync
  25657. */
  25658. rc = fsync(fd);
  25659. #else
  25660. rc = fdatasync(fd);
  25661. #if OS_VXWORKS
  25662. if( rc==-1 && errno==ENOTSUP ){
  25663. rc = fsync(fd);
  25664. }
  25665. #endif /* OS_VXWORKS */
  25666. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  25667. if( OS_VXWORKS && rc!= -1 ){
  25668. rc = 0;
  25669. }
  25670. return rc;
  25671. }
  25672. /*
  25673. ** Make sure all writes to a particular file are committed to disk.
  25674. **
  25675. ** If dataOnly==0 then both the file itself and its metadata (file
  25676. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  25677. ** file data is synced.
  25678. **
  25679. ** Under Unix, also make sure that the directory entry for the file
  25680. ** has been created by fsync-ing the directory that contains the file.
  25681. ** If we do not do this and we encounter a power failure, the directory
  25682. ** entry for the journal might not exist after we reboot. The next
  25683. ** SQLite to access the file will not know that the journal exists (because
  25684. ** the directory entry for the journal was never created) and the transaction
  25685. ** will not roll back - possibly leading to database corruption.
  25686. */
  25687. static int unixSync(sqlite3_file *id, int flags){
  25688. int rc;
  25689. unixFile *pFile = (unixFile*)id;
  25690. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  25691. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  25692. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  25693. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  25694. || (flags&0x0F)==SQLITE_SYNC_FULL
  25695. );
  25696. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  25697. ** line is to test that doing so does not cause any problems.
  25698. */
  25699. SimulateDiskfullError( return SQLITE_FULL );
  25700. assert( pFile );
  25701. OSTRACE(("SYNC %-3d\n", pFile->h));
  25702. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  25703. SimulateIOError( rc=1 );
  25704. if( rc ){
  25705. pFile->lastErrno = errno;
  25706. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  25707. }
  25708. if( pFile->dirfd>=0 ){
  25709. OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
  25710. HAVE_FULLFSYNC, isFullsync));
  25711. #ifndef SQLITE_DISABLE_DIRSYNC
  25712. /* The directory sync is only attempted if full_fsync is
  25713. ** turned off or unavailable. If a full_fsync occurred above,
  25714. ** then the directory sync is superfluous.
  25715. */
  25716. if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
  25717. /*
  25718. ** We have received multiple reports of fsync() returning
  25719. ** errors when applied to directories on certain file systems.
  25720. ** A failed directory sync is not a big deal. So it seems
  25721. ** better to ignore the error. Ticket #1657
  25722. */
  25723. /* pFile->lastErrno = errno; */
  25724. /* return SQLITE_IOERR; */
  25725. }
  25726. #endif
  25727. /* Only need to sync once, so close the directory when we are done */
  25728. robust_close(pFile, pFile->dirfd, __LINE__);
  25729. pFile->dirfd = -1;
  25730. }
  25731. return rc;
  25732. }
  25733. /*
  25734. ** Truncate an open file to a specified size
  25735. */
  25736. static int unixTruncate(sqlite3_file *id, i64 nByte){
  25737. unixFile *pFile = (unixFile *)id;
  25738. int rc;
  25739. assert( pFile );
  25740. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  25741. /* If the user has configured a chunk-size for this file, truncate the
  25742. ** file so that it consists of an integer number of chunks (i.e. the
  25743. ** actual file size after the operation may be larger than the requested
  25744. ** size).
  25745. */
  25746. if( pFile->szChunk ){
  25747. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  25748. }
  25749. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  25750. if( rc ){
  25751. pFile->lastErrno = errno;
  25752. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25753. }else{
  25754. #ifndef NDEBUG
  25755. /* If we are doing a normal write to a database file (as opposed to
  25756. ** doing a hot-journal rollback or a write to some file other than a
  25757. ** normal database file) and we truncate the file to zero length,
  25758. ** that effectively updates the change counter. This might happen
  25759. ** when restoring a database using the backup API from a zero-length
  25760. ** source.
  25761. */
  25762. if( pFile->inNormalWrite && nByte==0 ){
  25763. pFile->transCntrChng = 1;
  25764. }
  25765. #endif
  25766. return SQLITE_OK;
  25767. }
  25768. }
  25769. /*
  25770. ** Determine the current size of a file in bytes
  25771. */
  25772. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  25773. int rc;
  25774. struct stat buf;
  25775. assert( id );
  25776. rc = osFstat(((unixFile*)id)->h, &buf);
  25777. SimulateIOError( rc=1 );
  25778. if( rc!=0 ){
  25779. ((unixFile*)id)->lastErrno = errno;
  25780. return SQLITE_IOERR_FSTAT;
  25781. }
  25782. *pSize = buf.st_size;
  25783. /* When opening a zero-size database, the findInodeInfo() procedure
  25784. ** writes a single byte into that file in order to work around a bug
  25785. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  25786. ** layers, we need to report this file size as zero even though it is
  25787. ** really 1. Ticket #3260.
  25788. */
  25789. if( *pSize==1 ) *pSize = 0;
  25790. return SQLITE_OK;
  25791. }
  25792. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25793. /*
  25794. ** Handler for proxy-locking file-control verbs. Defined below in the
  25795. ** proxying locking division.
  25796. */
  25797. static int proxyFileControl(sqlite3_file*,int,void*);
  25798. #endif
  25799. /*
  25800. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  25801. ** file-control operation.
  25802. **
  25803. ** If the user has configured a chunk-size for this file, it could be
  25804. ** that the file needs to be extended at this point. Otherwise, the
  25805. ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
  25806. */
  25807. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  25808. if( pFile->szChunk ){
  25809. i64 nSize; /* Required file size */
  25810. struct stat buf; /* Used to hold return values of fstat() */
  25811. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  25812. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  25813. if( nSize>(i64)buf.st_size ){
  25814. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  25815. /* The code below is handling the return value of osFallocate()
  25816. ** correctly. posix_fallocate() is defined to "returns zero on success,
  25817. ** or an error number on failure". See the manpage for details. */
  25818. int err;
  25819. do{
  25820. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  25821. }while( err==EINTR );
  25822. if( err ) return SQLITE_IOERR_WRITE;
  25823. #else
  25824. /* If the OS does not have posix_fallocate(), fake it. First use
  25825. ** ftruncate() to set the file size, then write a single byte to
  25826. ** the last byte in each block within the extended region. This
  25827. ** is the same technique used by glibc to implement posix_fallocate()
  25828. ** on systems that do not have a real fallocate() system call.
  25829. */
  25830. int nBlk = buf.st_blksize; /* File-system block size */
  25831. i64 iWrite; /* Next offset to write to */
  25832. if( robust_ftruncate(pFile->h, nSize) ){
  25833. pFile->lastErrno = errno;
  25834. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25835. }
  25836. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  25837. while( iWrite<nSize ){
  25838. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  25839. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  25840. iWrite += nBlk;
  25841. }
  25842. #endif
  25843. }
  25844. }
  25845. return SQLITE_OK;
  25846. }
  25847. /*
  25848. ** Information and control of an open file handle.
  25849. */
  25850. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  25851. switch( op ){
  25852. case SQLITE_FCNTL_LOCKSTATE: {
  25853. *(int*)pArg = ((unixFile*)id)->eFileLock;
  25854. return SQLITE_OK;
  25855. }
  25856. case SQLITE_LAST_ERRNO: {
  25857. *(int*)pArg = ((unixFile*)id)->lastErrno;
  25858. return SQLITE_OK;
  25859. }
  25860. case SQLITE_FCNTL_CHUNK_SIZE: {
  25861. ((unixFile*)id)->szChunk = *(int *)pArg;
  25862. return SQLITE_OK;
  25863. }
  25864. case SQLITE_FCNTL_SIZE_HINT: {
  25865. return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
  25866. }
  25867. #ifndef NDEBUG
  25868. /* The pager calls this method to signal that it has done
  25869. ** a rollback and that the database is therefore unchanged and
  25870. ** it hence it is OK for the transaction change counter to be
  25871. ** unchanged.
  25872. */
  25873. case SQLITE_FCNTL_DB_UNCHANGED: {
  25874. ((unixFile*)id)->dbUpdate = 0;
  25875. return SQLITE_OK;
  25876. }
  25877. #endif
  25878. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25879. case SQLITE_SET_LOCKPROXYFILE:
  25880. case SQLITE_GET_LOCKPROXYFILE: {
  25881. return proxyFileControl(id,op,pArg);
  25882. }
  25883. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  25884. case SQLITE_FCNTL_SYNC_OMITTED: {
  25885. return SQLITE_OK; /* A no-op */
  25886. }
  25887. }
  25888. return SQLITE_NOTFOUND;
  25889. }
  25890. /*
  25891. ** Return the sector size in bytes of the underlying block device for
  25892. ** the specified file. This is almost always 512 bytes, but may be
  25893. ** larger for some devices.
  25894. **
  25895. ** SQLite code assumes this function cannot fail. It also assumes that
  25896. ** if two files are created in the same file-system directory (i.e.
  25897. ** a database and its journal file) that the sector size will be the
  25898. ** same for both.
  25899. */
  25900. static int unixSectorSize(sqlite3_file *NotUsed){
  25901. UNUSED_PARAMETER(NotUsed);
  25902. return SQLITE_DEFAULT_SECTOR_SIZE;
  25903. }
  25904. /*
  25905. ** Return the device characteristics for the file. This is always 0 for unix.
  25906. */
  25907. static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
  25908. UNUSED_PARAMETER(NotUsed);
  25909. return 0;
  25910. }
  25911. #ifndef SQLITE_OMIT_WAL
  25912. /*
  25913. ** Object used to represent an shared memory buffer.
  25914. **
  25915. ** When multiple threads all reference the same wal-index, each thread
  25916. ** has its own unixShm object, but they all point to a single instance
  25917. ** of this unixShmNode object. In other words, each wal-index is opened
  25918. ** only once per process.
  25919. **
  25920. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  25921. ** We could coalesce this object into unixInodeInfo, but that would mean
  25922. ** every open file that does not use shared memory (in other words, most
  25923. ** open files) would have to carry around this extra information. So
  25924. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  25925. ** and the unixShmNode object is created only when needed.
  25926. **
  25927. ** unixMutexHeld() must be true when creating or destroying
  25928. ** this object or while reading or writing the following fields:
  25929. **
  25930. ** nRef
  25931. **
  25932. ** The following fields are read-only after the object is created:
  25933. **
  25934. ** fid
  25935. ** zFilename
  25936. **
  25937. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  25938. ** unixMutexHeld() is true when reading or writing any other field
  25939. ** in this structure.
  25940. */
  25941. struct unixShmNode {
  25942. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  25943. sqlite3_mutex *mutex; /* Mutex to access this object */
  25944. char *zFilename; /* Name of the mmapped file */
  25945. int h; /* Open file descriptor */
  25946. int szRegion; /* Size of shared-memory regions */
  25947. int nRegion; /* Size of array apRegion */
  25948. char **apRegion; /* Array of mapped shared-memory regions */
  25949. int nRef; /* Number of unixShm objects pointing to this */
  25950. unixShm *pFirst; /* All unixShm objects pointing to this */
  25951. #ifdef SQLITE_DEBUG
  25952. u8 exclMask; /* Mask of exclusive locks held */
  25953. u8 sharedMask; /* Mask of shared locks held */
  25954. u8 nextShmId; /* Next available unixShm.id value */
  25955. #endif
  25956. };
  25957. /*
  25958. ** Structure used internally by this VFS to record the state of an
  25959. ** open shared memory connection.
  25960. **
  25961. ** The following fields are initialized when this object is created and
  25962. ** are read-only thereafter:
  25963. **
  25964. ** unixShm.pFile
  25965. ** unixShm.id
  25966. **
  25967. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  25968. ** while accessing any read/write fields.
  25969. */
  25970. struct unixShm {
  25971. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  25972. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  25973. u8 hasMutex; /* True if holding the unixShmNode mutex */
  25974. u16 sharedMask; /* Mask of shared locks held */
  25975. u16 exclMask; /* Mask of exclusive locks held */
  25976. #ifdef SQLITE_DEBUG
  25977. u8 id; /* Id of this connection within its unixShmNode */
  25978. #endif
  25979. };
  25980. /*
  25981. ** Constants used for locking
  25982. */
  25983. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  25984. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  25985. /*
  25986. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  25987. **
  25988. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  25989. ** otherwise.
  25990. */
  25991. static int unixShmSystemLock(
  25992. unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
  25993. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  25994. int ofst, /* First byte of the locking range */
  25995. int n /* Number of bytes to lock */
  25996. ){
  25997. struct flock f; /* The posix advisory locking structure */
  25998. int rc = SQLITE_OK; /* Result code form fcntl() */
  25999. /* Access to the unixShmNode object is serialized by the caller */
  26000. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  26001. /* Shared locks never span more than one byte */
  26002. assert( n==1 || lockType!=F_RDLCK );
  26003. /* Locks are within range */
  26004. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  26005. if( pShmNode->h>=0 ){
  26006. /* Initialize the locking parameters */
  26007. memset(&f, 0, sizeof(f));
  26008. f.l_type = lockType;
  26009. f.l_whence = SEEK_SET;
  26010. f.l_start = ofst;
  26011. f.l_len = n;
  26012. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  26013. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  26014. }
  26015. /* Update the global lock state and do debug tracing */
  26016. #ifdef SQLITE_DEBUG
  26017. { u16 mask;
  26018. OSTRACE(("SHM-LOCK "));
  26019. mask = (1<<(ofst+n)) - (1<<ofst);
  26020. if( rc==SQLITE_OK ){
  26021. if( lockType==F_UNLCK ){
  26022. OSTRACE(("unlock %d ok", ofst));
  26023. pShmNode->exclMask &= ~mask;
  26024. pShmNode->sharedMask &= ~mask;
  26025. }else if( lockType==F_RDLCK ){
  26026. OSTRACE(("read-lock %d ok", ofst));
  26027. pShmNode->exclMask &= ~mask;
  26028. pShmNode->sharedMask |= mask;
  26029. }else{
  26030. assert( lockType==F_WRLCK );
  26031. OSTRACE(("write-lock %d ok", ofst));
  26032. pShmNode->exclMask |= mask;
  26033. pShmNode->sharedMask &= ~mask;
  26034. }
  26035. }else{
  26036. if( lockType==F_UNLCK ){
  26037. OSTRACE(("unlock %d failed", ofst));
  26038. }else if( lockType==F_RDLCK ){
  26039. OSTRACE(("read-lock failed"));
  26040. }else{
  26041. assert( lockType==F_WRLCK );
  26042. OSTRACE(("write-lock %d failed", ofst));
  26043. }
  26044. }
  26045. OSTRACE((" - afterwards %03x,%03x\n",
  26046. pShmNode->sharedMask, pShmNode->exclMask));
  26047. }
  26048. #endif
  26049. return rc;
  26050. }
  26051. /*
  26052. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  26053. **
  26054. ** This is not a VFS shared-memory method; it is a utility function called
  26055. ** by VFS shared-memory methods.
  26056. */
  26057. static void unixShmPurge(unixFile *pFd){
  26058. unixShmNode *p = pFd->pInode->pShmNode;
  26059. assert( unixMutexHeld() );
  26060. if( p && p->nRef==0 ){
  26061. int i;
  26062. assert( p->pInode==pFd->pInode );
  26063. if( p->mutex ) sqlite3_mutex_free(p->mutex);
  26064. for(i=0; i<p->nRegion; i++){
  26065. if( p->h>=0 ){
  26066. munmap(p->apRegion[i], p->szRegion);
  26067. }else{
  26068. sqlite3_free(p->apRegion[i]);
  26069. }
  26070. }
  26071. sqlite3_free(p->apRegion);
  26072. if( p->h>=0 ){
  26073. robust_close(pFd, p->h, __LINE__);
  26074. p->h = -1;
  26075. }
  26076. p->pInode->pShmNode = 0;
  26077. sqlite3_free(p);
  26078. }
  26079. }
  26080. /*
  26081. ** Open a shared-memory area associated with open database file pDbFd.
  26082. ** This particular implementation uses mmapped files.
  26083. **
  26084. ** The file used to implement shared-memory is in the same directory
  26085. ** as the open database file and has the same name as the open database
  26086. ** file with the "-shm" suffix added. For example, if the database file
  26087. ** is "/home/user1/config.db" then the file that is created and mmapped
  26088. ** for shared memory will be called "/home/user1/config.db-shm".
  26089. **
  26090. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  26091. ** some other tmpfs mount. But if a file in a different directory
  26092. ** from the database file is used, then differing access permissions
  26093. ** or a chroot() might cause two different processes on the same
  26094. ** database to end up using different files for shared memory -
  26095. ** meaning that their memory would not really be shared - resulting
  26096. ** in database corruption. Nevertheless, this tmpfs file usage
  26097. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  26098. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  26099. ** option results in an incompatible build of SQLite; builds of SQLite
  26100. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  26101. ** same database file at the same time, database corruption will likely
  26102. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  26103. ** "unsupported" and may go away in a future SQLite release.
  26104. **
  26105. ** When opening a new shared-memory file, if no other instances of that
  26106. ** file are currently open, in this process or in other processes, then
  26107. ** the file must be truncated to zero length or have its header cleared.
  26108. **
  26109. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  26110. ** that means that an exclusive lock is held on the database file and
  26111. ** that no other processes are able to read or write the database. In
  26112. ** that case, we do not really need shared memory. No shared memory
  26113. ** file is created. The shared memory will be simulated with heap memory.
  26114. */
  26115. static int unixOpenSharedMemory(unixFile *pDbFd){
  26116. struct unixShm *p = 0; /* The connection to be opened */
  26117. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  26118. int rc; /* Result code */
  26119. unixInodeInfo *pInode; /* The inode of fd */
  26120. char *zShmFilename; /* Name of the file used for SHM */
  26121. int nShmFilename; /* Size of the SHM filename in bytes */
  26122. /* Allocate space for the new unixShm object. */
  26123. p = sqlite3_malloc( sizeof(*p) );
  26124. if( p==0 ) return SQLITE_NOMEM;
  26125. memset(p, 0, sizeof(*p));
  26126. assert( pDbFd->pShm==0 );
  26127. /* Check to see if a unixShmNode object already exists. Reuse an existing
  26128. ** one if present. Create a new one if necessary.
  26129. */
  26130. unixEnterMutex();
  26131. pInode = pDbFd->pInode;
  26132. pShmNode = pInode->pShmNode;
  26133. if( pShmNode==0 ){
  26134. struct stat sStat; /* fstat() info for database file */
  26135. /* Call fstat() to figure out the permissions on the database file. If
  26136. ** a new *-shm file is created, an attempt will be made to create it
  26137. ** with the same permissions. The actual permissions the file is created
  26138. ** with are subject to the current umask setting.
  26139. */
  26140. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  26141. rc = SQLITE_IOERR_FSTAT;
  26142. goto shm_open_err;
  26143. }
  26144. #ifdef SQLITE_SHM_DIRECTORY
  26145. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
  26146. #else
  26147. nShmFilename = 5 + (int)strlen(pDbFd->zPath);
  26148. #endif
  26149. pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  26150. if( pShmNode==0 ){
  26151. rc = SQLITE_NOMEM;
  26152. goto shm_open_err;
  26153. }
  26154. memset(pShmNode, 0, sizeof(*pShmNode));
  26155. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  26156. #ifdef SQLITE_SHM_DIRECTORY
  26157. sqlite3_snprintf(nShmFilename, zShmFilename,
  26158. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  26159. (u32)sStat.st_ino, (u32)sStat.st_dev);
  26160. #else
  26161. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
  26162. #endif
  26163. pShmNode->h = -1;
  26164. pDbFd->pInode->pShmNode = pShmNode;
  26165. pShmNode->pInode = pDbFd->pInode;
  26166. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  26167. if( pShmNode->mutex==0 ){
  26168. rc = SQLITE_NOMEM;
  26169. goto shm_open_err;
  26170. }
  26171. if( pInode->bProcessLock==0 ){
  26172. pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
  26173. (sStat.st_mode & 0777));
  26174. if( pShmNode->h<0 ){
  26175. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  26176. goto shm_open_err;
  26177. }
  26178. /* Check to see if another process is holding the dead-man switch.
  26179. ** If not, truncate the file to zero length.
  26180. */
  26181. rc = SQLITE_OK;
  26182. if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  26183. if( robust_ftruncate(pShmNode->h, 0) ){
  26184. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  26185. }
  26186. }
  26187. if( rc==SQLITE_OK ){
  26188. rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
  26189. }
  26190. if( rc ) goto shm_open_err;
  26191. }
  26192. }
  26193. /* Make the new connection a child of the unixShmNode */
  26194. p->pShmNode = pShmNode;
  26195. #ifdef SQLITE_DEBUG
  26196. p->id = pShmNode->nextShmId++;
  26197. #endif
  26198. pShmNode->nRef++;
  26199. pDbFd->pShm = p;
  26200. unixLeaveMutex();
  26201. /* The reference count on pShmNode has already been incremented under
  26202. ** the cover of the unixEnterMutex() mutex and the pointer from the
  26203. ** new (struct unixShm) object to the pShmNode has been set. All that is
  26204. ** left to do is to link the new object into the linked list starting
  26205. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  26206. ** mutex.
  26207. */
  26208. sqlite3_mutex_enter(pShmNode->mutex);
  26209. p->pNext = pShmNode->pFirst;
  26210. pShmNode->pFirst = p;
  26211. sqlite3_mutex_leave(pShmNode->mutex);
  26212. return SQLITE_OK;
  26213. /* Jump here on any error */
  26214. shm_open_err:
  26215. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  26216. sqlite3_free(p);
  26217. unixLeaveMutex();
  26218. return rc;
  26219. }
  26220. /*
  26221. ** This function is called to obtain a pointer to region iRegion of the
  26222. ** shared-memory associated with the database file fd. Shared-memory regions
  26223. ** are numbered starting from zero. Each shared-memory region is szRegion
  26224. ** bytes in size.
  26225. **
  26226. ** If an error occurs, an error code is returned and *pp is set to NULL.
  26227. **
  26228. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  26229. ** region has not been allocated (by any client, including one running in a
  26230. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  26231. ** bExtend is non-zero and the requested shared-memory region has not yet
  26232. ** been allocated, it is allocated by this function.
  26233. **
  26234. ** If the shared-memory region has already been allocated or is allocated by
  26235. ** this call as described above, then it is mapped into this processes
  26236. ** address space (if it is not already), *pp is set to point to the mapped
  26237. ** memory and SQLITE_OK returned.
  26238. */
  26239. static int unixShmMap(
  26240. sqlite3_file *fd, /* Handle open on database file */
  26241. int iRegion, /* Region to retrieve */
  26242. int szRegion, /* Size of regions */
  26243. int bExtend, /* True to extend file if necessary */
  26244. void volatile **pp /* OUT: Mapped memory */
  26245. ){
  26246. unixFile *pDbFd = (unixFile*)fd;
  26247. unixShm *p;
  26248. unixShmNode *pShmNode;
  26249. int rc = SQLITE_OK;
  26250. /* If the shared-memory file has not yet been opened, open it now. */
  26251. if( pDbFd->pShm==0 ){
  26252. rc = unixOpenSharedMemory(pDbFd);
  26253. if( rc!=SQLITE_OK ) return rc;
  26254. }
  26255. p = pDbFd->pShm;
  26256. pShmNode = p->pShmNode;
  26257. sqlite3_mutex_enter(pShmNode->mutex);
  26258. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  26259. assert( pShmNode->pInode==pDbFd->pInode );
  26260. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  26261. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  26262. if( pShmNode->nRegion<=iRegion ){
  26263. char **apNew; /* New apRegion[] array */
  26264. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  26265. struct stat sStat; /* Used by fstat() */
  26266. pShmNode->szRegion = szRegion;
  26267. if( pShmNode->h>=0 ){
  26268. /* The requested region is not mapped into this processes address space.
  26269. ** Check to see if it has been allocated (i.e. if the wal-index file is
  26270. ** large enough to contain the requested region).
  26271. */
  26272. if( osFstat(pShmNode->h, &sStat) ){
  26273. rc = SQLITE_IOERR_SHMSIZE;
  26274. goto shmpage_out;
  26275. }
  26276. if( sStat.st_size<nByte ){
  26277. /* The requested memory region does not exist. If bExtend is set to
  26278. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  26279. **
  26280. ** Alternatively, if bExtend is true, use ftruncate() to allocate
  26281. ** the requested memory region.
  26282. */
  26283. if( !bExtend ) goto shmpage_out;
  26284. if( robust_ftruncate(pShmNode->h, nByte) ){
  26285. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
  26286. pShmNode->zFilename);
  26287. goto shmpage_out;
  26288. }
  26289. }
  26290. }
  26291. /* Map the requested memory region into this processes address space. */
  26292. apNew = (char **)sqlite3_realloc(
  26293. pShmNode->apRegion, (iRegion+1)*sizeof(char *)
  26294. );
  26295. if( !apNew ){
  26296. rc = SQLITE_IOERR_NOMEM;
  26297. goto shmpage_out;
  26298. }
  26299. pShmNode->apRegion = apNew;
  26300. while(pShmNode->nRegion<=iRegion){
  26301. void *pMem;
  26302. if( pShmNode->h>=0 ){
  26303. pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
  26304. MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
  26305. );
  26306. if( pMem==MAP_FAILED ){
  26307. rc = SQLITE_IOERR;
  26308. goto shmpage_out;
  26309. }
  26310. }else{
  26311. pMem = sqlite3_malloc(szRegion);
  26312. if( pMem==0 ){
  26313. rc = SQLITE_NOMEM;
  26314. goto shmpage_out;
  26315. }
  26316. memset(pMem, 0, szRegion);
  26317. }
  26318. pShmNode->apRegion[pShmNode->nRegion] = pMem;
  26319. pShmNode->nRegion++;
  26320. }
  26321. }
  26322. shmpage_out:
  26323. if( pShmNode->nRegion>iRegion ){
  26324. *pp = pShmNode->apRegion[iRegion];
  26325. }else{
  26326. *pp = 0;
  26327. }
  26328. sqlite3_mutex_leave(pShmNode->mutex);
  26329. return rc;
  26330. }
  26331. /*
  26332. ** Change the lock state for a shared-memory segment.
  26333. **
  26334. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  26335. ** different here than in posix. In xShmLock(), one can go from unlocked
  26336. ** to shared and back or from unlocked to exclusive and back. But one may
  26337. ** not go from shared to exclusive or from exclusive to shared.
  26338. */
  26339. static int unixShmLock(
  26340. sqlite3_file *fd, /* Database file holding the shared memory */
  26341. int ofst, /* First lock to acquire or release */
  26342. int n, /* Number of locks to acquire or release */
  26343. int flags /* What to do with the lock */
  26344. ){
  26345. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  26346. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  26347. unixShm *pX; /* For looping over all siblings */
  26348. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  26349. int rc = SQLITE_OK; /* Result code */
  26350. u16 mask; /* Mask of locks to take or release */
  26351. assert( pShmNode==pDbFd->pInode->pShmNode );
  26352. assert( pShmNode->pInode==pDbFd->pInode );
  26353. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  26354. assert( n>=1 );
  26355. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  26356. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  26357. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  26358. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  26359. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  26360. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  26361. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  26362. mask = (1<<(ofst+n)) - (1<<ofst);
  26363. assert( n>1 || mask==(1<<ofst) );
  26364. sqlite3_mutex_enter(pShmNode->mutex);
  26365. if( flags & SQLITE_SHM_UNLOCK ){
  26366. u16 allMask = 0; /* Mask of locks held by siblings */
  26367. /* See if any siblings hold this same lock */
  26368. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26369. if( pX==p ) continue;
  26370. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  26371. allMask |= pX->sharedMask;
  26372. }
  26373. /* Unlock the system-level locks */
  26374. if( (mask & allMask)==0 ){
  26375. rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  26376. }else{
  26377. rc = SQLITE_OK;
  26378. }
  26379. /* Undo the local locks */
  26380. if( rc==SQLITE_OK ){
  26381. p->exclMask &= ~mask;
  26382. p->sharedMask &= ~mask;
  26383. }
  26384. }else if( flags & SQLITE_SHM_SHARED ){
  26385. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  26386. /* Find out which shared locks are already held by sibling connections.
  26387. ** If any sibling already holds an exclusive lock, go ahead and return
  26388. ** SQLITE_BUSY.
  26389. */
  26390. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26391. if( (pX->exclMask & mask)!=0 ){
  26392. rc = SQLITE_BUSY;
  26393. break;
  26394. }
  26395. allShared |= pX->sharedMask;
  26396. }
  26397. /* Get shared locks at the system level, if necessary */
  26398. if( rc==SQLITE_OK ){
  26399. if( (allShared & mask)==0 ){
  26400. rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  26401. }else{
  26402. rc = SQLITE_OK;
  26403. }
  26404. }
  26405. /* Get the local shared locks */
  26406. if( rc==SQLITE_OK ){
  26407. p->sharedMask |= mask;
  26408. }
  26409. }else{
  26410. /* Make sure no sibling connections hold locks that will block this
  26411. ** lock. If any do, return SQLITE_BUSY right away.
  26412. */
  26413. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26414. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  26415. rc = SQLITE_BUSY;
  26416. break;
  26417. }
  26418. }
  26419. /* Get the exclusive locks at the system level. Then if successful
  26420. ** also mark the local connection as being locked.
  26421. */
  26422. if( rc==SQLITE_OK ){
  26423. rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  26424. if( rc==SQLITE_OK ){
  26425. assert( (p->sharedMask & mask)==0 );
  26426. p->exclMask |= mask;
  26427. }
  26428. }
  26429. }
  26430. sqlite3_mutex_leave(pShmNode->mutex);
  26431. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  26432. p->id, getpid(), p->sharedMask, p->exclMask));
  26433. return rc;
  26434. }
  26435. /*
  26436. ** Implement a memory barrier or memory fence on shared memory.
  26437. **
  26438. ** All loads and stores begun before the barrier must complete before
  26439. ** any load or store begun after the barrier.
  26440. */
  26441. static void unixShmBarrier(
  26442. sqlite3_file *fd /* Database file holding the shared memory */
  26443. ){
  26444. UNUSED_PARAMETER(fd);
  26445. unixEnterMutex();
  26446. unixLeaveMutex();
  26447. }
  26448. /*
  26449. ** Close a connection to shared-memory. Delete the underlying
  26450. ** storage if deleteFlag is true.
  26451. **
  26452. ** If there is no shared memory associated with the connection then this
  26453. ** routine is a harmless no-op.
  26454. */
  26455. static int unixShmUnmap(
  26456. sqlite3_file *fd, /* The underlying database file */
  26457. int deleteFlag /* Delete shared-memory if true */
  26458. ){
  26459. unixShm *p; /* The connection to be closed */
  26460. unixShmNode *pShmNode; /* The underlying shared-memory file */
  26461. unixShm **pp; /* For looping over sibling connections */
  26462. unixFile *pDbFd; /* The underlying database file */
  26463. pDbFd = (unixFile*)fd;
  26464. p = pDbFd->pShm;
  26465. if( p==0 ) return SQLITE_OK;
  26466. pShmNode = p->pShmNode;
  26467. assert( pShmNode==pDbFd->pInode->pShmNode );
  26468. assert( pShmNode->pInode==pDbFd->pInode );
  26469. /* Remove connection p from the set of connections associated
  26470. ** with pShmNode */
  26471. sqlite3_mutex_enter(pShmNode->mutex);
  26472. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  26473. *pp = p->pNext;
  26474. /* Free the connection p */
  26475. sqlite3_free(p);
  26476. pDbFd->pShm = 0;
  26477. sqlite3_mutex_leave(pShmNode->mutex);
  26478. /* If pShmNode->nRef has reached 0, then close the underlying
  26479. ** shared-memory file, too */
  26480. unixEnterMutex();
  26481. assert( pShmNode->nRef>0 );
  26482. pShmNode->nRef--;
  26483. if( pShmNode->nRef==0 ){
  26484. if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
  26485. unixShmPurge(pDbFd);
  26486. }
  26487. unixLeaveMutex();
  26488. return SQLITE_OK;
  26489. }
  26490. #else
  26491. # define unixShmMap 0
  26492. # define unixShmLock 0
  26493. # define unixShmBarrier 0
  26494. # define unixShmUnmap 0
  26495. #endif /* #ifndef SQLITE_OMIT_WAL */
  26496. /*
  26497. ** Here ends the implementation of all sqlite3_file methods.
  26498. **
  26499. ********************** End sqlite3_file Methods *******************************
  26500. ******************************************************************************/
  26501. /*
  26502. ** This division contains definitions of sqlite3_io_methods objects that
  26503. ** implement various file locking strategies. It also contains definitions
  26504. ** of "finder" functions. A finder-function is used to locate the appropriate
  26505. ** sqlite3_io_methods object for a particular database file. The pAppData
  26506. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  26507. ** the correct finder-function for that VFS.
  26508. **
  26509. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  26510. ** object. The only interesting finder-function is autolockIoFinder, which
  26511. ** looks at the filesystem type and tries to guess the best locking
  26512. ** strategy from that.
  26513. **
  26514. ** For finder-funtion F, two objects are created:
  26515. **
  26516. ** (1) The real finder-function named "FImpt()".
  26517. **
  26518. ** (2) A constant pointer to this function named just "F".
  26519. **
  26520. **
  26521. ** A pointer to the F pointer is used as the pAppData value for VFS
  26522. ** objects. We have to do this instead of letting pAppData point
  26523. ** directly at the finder-function since C90 rules prevent a void*
  26524. ** from be cast into a function pointer.
  26525. **
  26526. **
  26527. ** Each instance of this macro generates two objects:
  26528. **
  26529. ** * A constant sqlite3_io_methods object call METHOD that has locking
  26530. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  26531. **
  26532. ** * An I/O method finder function called FINDER that returns a pointer
  26533. ** to the METHOD object in the previous bullet.
  26534. */
  26535. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  26536. static const sqlite3_io_methods METHOD = { \
  26537. VERSION, /* iVersion */ \
  26538. CLOSE, /* xClose */ \
  26539. unixRead, /* xRead */ \
  26540. unixWrite, /* xWrite */ \
  26541. unixTruncate, /* xTruncate */ \
  26542. unixSync, /* xSync */ \
  26543. unixFileSize, /* xFileSize */ \
  26544. LOCK, /* xLock */ \
  26545. UNLOCK, /* xUnlock */ \
  26546. CKLOCK, /* xCheckReservedLock */ \
  26547. unixFileControl, /* xFileControl */ \
  26548. unixSectorSize, /* xSectorSize */ \
  26549. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  26550. unixShmMap, /* xShmMap */ \
  26551. unixShmLock, /* xShmLock */ \
  26552. unixShmBarrier, /* xShmBarrier */ \
  26553. unixShmUnmap /* xShmUnmap */ \
  26554. }; \
  26555. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  26556. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  26557. return &METHOD; \
  26558. } \
  26559. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  26560. = FINDER##Impl;
  26561. /*
  26562. ** Here are all of the sqlite3_io_methods objects for each of the
  26563. ** locking strategies. Functions that return pointers to these methods
  26564. ** are also created.
  26565. */
  26566. IOMETHODS(
  26567. posixIoFinder, /* Finder function name */
  26568. posixIoMethods, /* sqlite3_io_methods object name */
  26569. 2, /* shared memory is enabled */
  26570. unixClose, /* xClose method */
  26571. unixLock, /* xLock method */
  26572. unixUnlock, /* xUnlock method */
  26573. unixCheckReservedLock /* xCheckReservedLock method */
  26574. )
  26575. IOMETHODS(
  26576. nolockIoFinder, /* Finder function name */
  26577. nolockIoMethods, /* sqlite3_io_methods object name */
  26578. 1, /* shared memory is disabled */
  26579. nolockClose, /* xClose method */
  26580. nolockLock, /* xLock method */
  26581. nolockUnlock, /* xUnlock method */
  26582. nolockCheckReservedLock /* xCheckReservedLock method */
  26583. )
  26584. IOMETHODS(
  26585. dotlockIoFinder, /* Finder function name */
  26586. dotlockIoMethods, /* sqlite3_io_methods object name */
  26587. 1, /* shared memory is disabled */
  26588. dotlockClose, /* xClose method */
  26589. dotlockLock, /* xLock method */
  26590. dotlockUnlock, /* xUnlock method */
  26591. dotlockCheckReservedLock /* xCheckReservedLock method */
  26592. )
  26593. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  26594. IOMETHODS(
  26595. flockIoFinder, /* Finder function name */
  26596. flockIoMethods, /* sqlite3_io_methods object name */
  26597. 1, /* shared memory is disabled */
  26598. flockClose, /* xClose method */
  26599. flockLock, /* xLock method */
  26600. flockUnlock, /* xUnlock method */
  26601. flockCheckReservedLock /* xCheckReservedLock method */
  26602. )
  26603. #endif
  26604. #if OS_VXWORKS
  26605. IOMETHODS(
  26606. semIoFinder, /* Finder function name */
  26607. semIoMethods, /* sqlite3_io_methods object name */
  26608. 1, /* shared memory is disabled */
  26609. semClose, /* xClose method */
  26610. semLock, /* xLock method */
  26611. semUnlock, /* xUnlock method */
  26612. semCheckReservedLock /* xCheckReservedLock method */
  26613. )
  26614. #endif
  26615. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26616. IOMETHODS(
  26617. afpIoFinder, /* Finder function name */
  26618. afpIoMethods, /* sqlite3_io_methods object name */
  26619. 1, /* shared memory is disabled */
  26620. afpClose, /* xClose method */
  26621. afpLock, /* xLock method */
  26622. afpUnlock, /* xUnlock method */
  26623. afpCheckReservedLock /* xCheckReservedLock method */
  26624. )
  26625. #endif
  26626. /*
  26627. ** The proxy locking method is a "super-method" in the sense that it
  26628. ** opens secondary file descriptors for the conch and lock files and
  26629. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  26630. ** secondary files. For this reason, the division that implements
  26631. ** proxy locking is located much further down in the file. But we need
  26632. ** to go ahead and define the sqlite3_io_methods and finder function
  26633. ** for proxy locking here. So we forward declare the I/O methods.
  26634. */
  26635. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26636. static int proxyClose(sqlite3_file*);
  26637. static int proxyLock(sqlite3_file*, int);
  26638. static int proxyUnlock(sqlite3_file*, int);
  26639. static int proxyCheckReservedLock(sqlite3_file*, int*);
  26640. IOMETHODS(
  26641. proxyIoFinder, /* Finder function name */
  26642. proxyIoMethods, /* sqlite3_io_methods object name */
  26643. 1, /* shared memory is disabled */
  26644. proxyClose, /* xClose method */
  26645. proxyLock, /* xLock method */
  26646. proxyUnlock, /* xUnlock method */
  26647. proxyCheckReservedLock /* xCheckReservedLock method */
  26648. )
  26649. #endif
  26650. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  26651. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26652. IOMETHODS(
  26653. nfsIoFinder, /* Finder function name */
  26654. nfsIoMethods, /* sqlite3_io_methods object name */
  26655. 1, /* shared memory is disabled */
  26656. unixClose, /* xClose method */
  26657. unixLock, /* xLock method */
  26658. nfsUnlock, /* xUnlock method */
  26659. unixCheckReservedLock /* xCheckReservedLock method */
  26660. )
  26661. #endif
  26662. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26663. /*
  26664. ** This "finder" function attempts to determine the best locking strategy
  26665. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26666. ** object that implements that strategy.
  26667. **
  26668. ** This is for MacOSX only.
  26669. */
  26670. static const sqlite3_io_methods *autolockIoFinderImpl(
  26671. const char *filePath, /* name of the database file */
  26672. unixFile *pNew /* open file object for the database file */
  26673. ){
  26674. static const struct Mapping {
  26675. const char *zFilesystem; /* Filesystem type name */
  26676. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  26677. } aMap[] = {
  26678. { "hfs", &posixIoMethods },
  26679. { "ufs", &posixIoMethods },
  26680. { "afpfs", &afpIoMethods },
  26681. { "smbfs", &afpIoMethods },
  26682. { "webdav", &nolockIoMethods },
  26683. { 0, 0 }
  26684. };
  26685. int i;
  26686. struct statfs fsInfo;
  26687. struct flock lockInfo;
  26688. if( !filePath ){
  26689. /* If filePath==NULL that means we are dealing with a transient file
  26690. ** that does not need to be locked. */
  26691. return &nolockIoMethods;
  26692. }
  26693. if( statfs(filePath, &fsInfo) != -1 ){
  26694. if( fsInfo.f_flags & MNT_RDONLY ){
  26695. return &nolockIoMethods;
  26696. }
  26697. for(i=0; aMap[i].zFilesystem; i++){
  26698. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  26699. return aMap[i].pMethods;
  26700. }
  26701. }
  26702. }
  26703. /* Default case. Handles, amongst others, "nfs".
  26704. ** Test byte-range lock using fcntl(). If the call succeeds,
  26705. ** assume that the file-system supports POSIX style locks.
  26706. */
  26707. lockInfo.l_len = 1;
  26708. lockInfo.l_start = 0;
  26709. lockInfo.l_whence = SEEK_SET;
  26710. lockInfo.l_type = F_RDLCK;
  26711. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26712. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  26713. return &nfsIoMethods;
  26714. } else {
  26715. return &posixIoMethods;
  26716. }
  26717. }else{
  26718. return &dotlockIoMethods;
  26719. }
  26720. }
  26721. static const sqlite3_io_methods
  26722. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26723. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26724. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  26725. /*
  26726. ** This "finder" function attempts to determine the best locking strategy
  26727. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26728. ** object that implements that strategy.
  26729. **
  26730. ** This is for VXWorks only.
  26731. */
  26732. static const sqlite3_io_methods *autolockIoFinderImpl(
  26733. const char *filePath, /* name of the database file */
  26734. unixFile *pNew /* the open file object */
  26735. ){
  26736. struct flock lockInfo;
  26737. if( !filePath ){
  26738. /* If filePath==NULL that means we are dealing with a transient file
  26739. ** that does not need to be locked. */
  26740. return &nolockIoMethods;
  26741. }
  26742. /* Test if fcntl() is supported and use POSIX style locks.
  26743. ** Otherwise fall back to the named semaphore method.
  26744. */
  26745. lockInfo.l_len = 1;
  26746. lockInfo.l_start = 0;
  26747. lockInfo.l_whence = SEEK_SET;
  26748. lockInfo.l_type = F_RDLCK;
  26749. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26750. return &posixIoMethods;
  26751. }else{
  26752. return &semIoMethods;
  26753. }
  26754. }
  26755. static const sqlite3_io_methods
  26756. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26757. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  26758. /*
  26759. ** An abstract type for a pointer to a IO method finder function:
  26760. */
  26761. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  26762. /****************************************************************************
  26763. **************************** sqlite3_vfs methods ****************************
  26764. **
  26765. ** This division contains the implementation of methods on the
  26766. ** sqlite3_vfs object.
  26767. */
  26768. /*
  26769. ** Initialize the contents of the unixFile structure pointed to by pId.
  26770. */
  26771. static int fillInUnixFile(
  26772. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  26773. int h, /* Open file descriptor of file being opened */
  26774. int dirfd, /* Directory file descriptor */
  26775. sqlite3_file *pId, /* Write to the unixFile structure here */
  26776. const char *zFilename, /* Name of the file being opened */
  26777. int noLock, /* Omit locking if true */
  26778. int isDelete, /* Delete on close if true */
  26779. int isReadOnly /* True if the file is opened read-only */
  26780. ){
  26781. const sqlite3_io_methods *pLockingStyle;
  26782. unixFile *pNew = (unixFile *)pId;
  26783. int rc = SQLITE_OK;
  26784. assert( pNew->pInode==NULL );
  26785. /* Parameter isDelete is only used on vxworks. Express this explicitly
  26786. ** here to prevent compiler warnings about unused parameters.
  26787. */
  26788. UNUSED_PARAMETER(isDelete);
  26789. /* Usually the path zFilename should not be a relative pathname. The
  26790. ** exception is when opening the proxy "conch" file in builds that
  26791. ** include the special Apple locking styles.
  26792. */
  26793. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26794. assert( zFilename==0 || zFilename[0]=='/'
  26795. || pVfs->pAppData==(void*)&autolockIoFinder );
  26796. #else
  26797. assert( zFilename==0 || zFilename[0]=='/' );
  26798. #endif
  26799. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  26800. pNew->h = h;
  26801. pNew->dirfd = dirfd;
  26802. pNew->zPath = zFilename;
  26803. if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
  26804. pNew->ctrlFlags = UNIXFILE_EXCL;
  26805. }else{
  26806. pNew->ctrlFlags = 0;
  26807. }
  26808. if( isReadOnly ){
  26809. pNew->ctrlFlags |= UNIXFILE_RDONLY;
  26810. }
  26811. #if OS_VXWORKS
  26812. pNew->pId = vxworksFindFileId(zFilename);
  26813. if( pNew->pId==0 ){
  26814. noLock = 1;
  26815. rc = SQLITE_NOMEM;
  26816. }
  26817. #endif
  26818. if( noLock ){
  26819. pLockingStyle = &nolockIoMethods;
  26820. }else{
  26821. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  26822. #if SQLITE_ENABLE_LOCKING_STYLE
  26823. /* Cache zFilename in the locking context (AFP and dotlock override) for
  26824. ** proxyLock activation is possible (remote proxy is based on db name)
  26825. ** zFilename remains valid until file is closed, to support */
  26826. pNew->lockingContext = (void*)zFilename;
  26827. #endif
  26828. }
  26829. if( pLockingStyle == &posixIoMethods
  26830. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26831. || pLockingStyle == &nfsIoMethods
  26832. #endif
  26833. ){
  26834. unixEnterMutex();
  26835. rc = findInodeInfo(pNew, &pNew->pInode);
  26836. if( rc!=SQLITE_OK ){
  26837. /* If an error occured in findInodeInfo(), close the file descriptor
  26838. ** immediately, before releasing the mutex. findInodeInfo() may fail
  26839. ** in two scenarios:
  26840. **
  26841. ** (a) A call to fstat() failed.
  26842. ** (b) A malloc failed.
  26843. **
  26844. ** Scenario (b) may only occur if the process is holding no other
  26845. ** file descriptors open on the same file. If there were other file
  26846. ** descriptors on this file, then no malloc would be required by
  26847. ** findInodeInfo(). If this is the case, it is quite safe to close
  26848. ** handle h - as it is guaranteed that no posix locks will be released
  26849. ** by doing so.
  26850. **
  26851. ** If scenario (a) caused the error then things are not so safe. The
  26852. ** implicit assumption here is that if fstat() fails, things are in
  26853. ** such bad shape that dropping a lock or two doesn't matter much.
  26854. */
  26855. robust_close(pNew, h, __LINE__);
  26856. h = -1;
  26857. }
  26858. unixLeaveMutex();
  26859. }
  26860. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26861. else if( pLockingStyle == &afpIoMethods ){
  26862. /* AFP locking uses the file path so it needs to be included in
  26863. ** the afpLockingContext.
  26864. */
  26865. afpLockingContext *pCtx;
  26866. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  26867. if( pCtx==0 ){
  26868. rc = SQLITE_NOMEM;
  26869. }else{
  26870. /* NB: zFilename exists and remains valid until the file is closed
  26871. ** according to requirement F11141. So we do not need to make a
  26872. ** copy of the filename. */
  26873. pCtx->dbPath = zFilename;
  26874. pCtx->reserved = 0;
  26875. srandomdev();
  26876. unixEnterMutex();
  26877. rc = findInodeInfo(pNew, &pNew->pInode);
  26878. if( rc!=SQLITE_OK ){
  26879. sqlite3_free(pNew->lockingContext);
  26880. robust_close(pNew, h, __LINE__);
  26881. h = -1;
  26882. }
  26883. unixLeaveMutex();
  26884. }
  26885. }
  26886. #endif
  26887. else if( pLockingStyle == &dotlockIoMethods ){
  26888. /* Dotfile locking uses the file path so it needs to be included in
  26889. ** the dotlockLockingContext
  26890. */
  26891. char *zLockFile;
  26892. int nFilename;
  26893. nFilename = (int)strlen(zFilename) + 6;
  26894. zLockFile = (char *)sqlite3_malloc(nFilename);
  26895. if( zLockFile==0 ){
  26896. rc = SQLITE_NOMEM;
  26897. }else{
  26898. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  26899. }
  26900. pNew->lockingContext = zLockFile;
  26901. }
  26902. #if OS_VXWORKS
  26903. else if( pLockingStyle == &semIoMethods ){
  26904. /* Named semaphore locking uses the file path so it needs to be
  26905. ** included in the semLockingContext
  26906. */
  26907. unixEnterMutex();
  26908. rc = findInodeInfo(pNew, &pNew->pInode);
  26909. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  26910. char *zSemName = pNew->pInode->aSemName;
  26911. int n;
  26912. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  26913. pNew->pId->zCanonicalName);
  26914. for( n=1; zSemName[n]; n++ )
  26915. if( zSemName[n]=='/' ) zSemName[n] = '_';
  26916. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  26917. if( pNew->pInode->pSem == SEM_FAILED ){
  26918. rc = SQLITE_NOMEM;
  26919. pNew->pInode->aSemName[0] = '\0';
  26920. }
  26921. }
  26922. unixLeaveMutex();
  26923. }
  26924. #endif
  26925. pNew->lastErrno = 0;
  26926. #if OS_VXWORKS
  26927. if( rc!=SQLITE_OK ){
  26928. if( h>=0 ) robust_close(pNew, h, __LINE__);
  26929. h = -1;
  26930. unlink(zFilename);
  26931. isDelete = 0;
  26932. }
  26933. pNew->isDelete = isDelete;
  26934. #endif
  26935. if( rc!=SQLITE_OK ){
  26936. if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
  26937. if( h>=0 ) robust_close(pNew, h, __LINE__);
  26938. }else{
  26939. pNew->pMethod = pLockingStyle;
  26940. OpenCounter(+1);
  26941. }
  26942. return rc;
  26943. }
  26944. /*
  26945. ** Open a file descriptor to the directory containing file zFilename.
  26946. ** If successful, *pFd is set to the opened file descriptor and
  26947. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  26948. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  26949. ** value.
  26950. **
  26951. ** If SQLITE_OK is returned, the caller is responsible for closing
  26952. ** the file descriptor *pFd using close().
  26953. */
  26954. static int openDirectory(const char *zFilename, int *pFd){
  26955. int ii;
  26956. int fd = -1;
  26957. char zDirname[MAX_PATHNAME+1];
  26958. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  26959. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  26960. if( ii>0 ){
  26961. zDirname[ii] = '\0';
  26962. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  26963. if( fd>=0 ){
  26964. #ifdef FD_CLOEXEC
  26965. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  26966. #endif
  26967. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  26968. }
  26969. }
  26970. *pFd = fd;
  26971. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  26972. }
  26973. /*
  26974. ** Return the name of a directory in which to put temporary files.
  26975. ** If no suitable temporary file directory can be found, return NULL.
  26976. */
  26977. static const char *unixTempFileDir(void){
  26978. static const char *azDirs[] = {
  26979. 0,
  26980. 0,
  26981. "/var/tmp",
  26982. "/usr/tmp",
  26983. "/tmp",
  26984. 0 /* List terminator */
  26985. };
  26986. unsigned int i;
  26987. struct stat buf;
  26988. const char *zDir = 0;
  26989. azDirs[0] = sqlite3_temp_directory;
  26990. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  26991. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  26992. if( zDir==0 ) continue;
  26993. if( osStat(zDir, &buf) ) continue;
  26994. if( !S_ISDIR(buf.st_mode) ) continue;
  26995. if( osAccess(zDir, 07) ) continue;
  26996. break;
  26997. }
  26998. return zDir;
  26999. }
  27000. /*
  27001. ** Create a temporary file name in zBuf. zBuf must be allocated
  27002. ** by the calling process and must be big enough to hold at least
  27003. ** pVfs->mxPathname bytes.
  27004. */
  27005. static int unixGetTempname(int nBuf, char *zBuf){
  27006. static const unsigned char zChars[] =
  27007. "abcdefghijklmnopqrstuvwxyz"
  27008. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  27009. "0123456789";
  27010. unsigned int i, j;
  27011. const char *zDir;
  27012. /* It's odd to simulate an io-error here, but really this is just
  27013. ** using the io-error infrastructure to test that SQLite handles this
  27014. ** function failing.
  27015. */
  27016. SimulateIOError( return SQLITE_IOERR );
  27017. zDir = unixTempFileDir();
  27018. if( zDir==0 ) zDir = ".";
  27019. /* Check that the output buffer is large enough for the temporary file
  27020. ** name. If it is not, return SQLITE_ERROR.
  27021. */
  27022. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
  27023. return SQLITE_ERROR;
  27024. }
  27025. do{
  27026. sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  27027. j = (int)strlen(zBuf);
  27028. sqlite3_randomness(15, &zBuf[j]);
  27029. for(i=0; i<15; i++, j++){
  27030. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  27031. }
  27032. zBuf[j] = 0;
  27033. }while( osAccess(zBuf,0)==0 );
  27034. return SQLITE_OK;
  27035. }
  27036. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27037. /*
  27038. ** Routine to transform a unixFile into a proxy-locking unixFile.
  27039. ** Implementation in the proxy-lock division, but used by unixOpen()
  27040. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  27041. */
  27042. static int proxyTransformUnixFile(unixFile*, const char*);
  27043. #endif
  27044. /*
  27045. ** Search for an unused file descriptor that was opened on the database
  27046. ** file (not a journal or master-journal file) identified by pathname
  27047. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  27048. ** argument to this function.
  27049. **
  27050. ** Such a file descriptor may exist if a database connection was closed
  27051. ** but the associated file descriptor could not be closed because some
  27052. ** other file descriptor open on the same file is holding a file-lock.
  27053. ** Refer to comments in the unixClose() function and the lengthy comment
  27054. ** describing "Posix Advisory Locking" at the start of this file for
  27055. ** further details. Also, ticket #4018.
  27056. **
  27057. ** If a suitable file descriptor is found, then it is returned. If no
  27058. ** such file descriptor is located, -1 is returned.
  27059. */
  27060. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  27061. UnixUnusedFd *pUnused = 0;
  27062. /* Do not search for an unused file descriptor on vxworks. Not because
  27063. ** vxworks would not benefit from the change (it might, we're not sure),
  27064. ** but because no way to test it is currently available. It is better
  27065. ** not to risk breaking vxworks support for the sake of such an obscure
  27066. ** feature. */
  27067. #if !OS_VXWORKS
  27068. struct stat sStat; /* Results of stat() call */
  27069. /* A stat() call may fail for various reasons. If this happens, it is
  27070. ** almost certain that an open() call on the same path will also fail.
  27071. ** For this reason, if an error occurs in the stat() call here, it is
  27072. ** ignored and -1 is returned. The caller will try to open a new file
  27073. ** descriptor on the same path, fail, and return an error to SQLite.
  27074. **
  27075. ** Even if a subsequent open() call does succeed, the consequences of
  27076. ** not searching for a resusable file descriptor are not dire. */
  27077. if( 0==stat(zPath, &sStat) ){
  27078. unixInodeInfo *pInode;
  27079. unixEnterMutex();
  27080. pInode = inodeList;
  27081. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  27082. || pInode->fileId.ino!=sStat.st_ino) ){
  27083. pInode = pInode->pNext;
  27084. }
  27085. if( pInode ){
  27086. UnixUnusedFd **pp;
  27087. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  27088. pUnused = *pp;
  27089. if( pUnused ){
  27090. *pp = pUnused->pNext;
  27091. }
  27092. }
  27093. unixLeaveMutex();
  27094. }
  27095. #endif /* if !OS_VXWORKS */
  27096. return pUnused;
  27097. }
  27098. /*
  27099. ** This function is called by unixOpen() to determine the unix permissions
  27100. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  27101. ** and a value suitable for passing as the third argument to open(2) is
  27102. ** written to *pMode. If an IO error occurs, an SQLite error code is
  27103. ** returned and the value of *pMode is not modified.
  27104. **
  27105. ** If the file being opened is a temporary file, it is always created with
  27106. ** the octal permissions 0600 (read/writable by owner only). If the file
  27107. ** is a database or master journal file, it is created with the permissions
  27108. ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
  27109. **
  27110. ** Finally, if the file being opened is a WAL or regular journal file, then
  27111. ** this function queries the file-system for the permissions on the
  27112. ** corresponding database file and sets *pMode to this value. Whenever
  27113. ** possible, WAL and journal files are created using the same permissions
  27114. ** as the associated database file.
  27115. */
  27116. static int findCreateFileMode(
  27117. const char *zPath, /* Path of file (possibly) being created */
  27118. int flags, /* Flags passed as 4th argument to xOpen() */
  27119. mode_t *pMode /* OUT: Permissions to open file with */
  27120. ){
  27121. int rc = SQLITE_OK; /* Return Code */
  27122. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  27123. char zDb[MAX_PATHNAME+1]; /* Database file path */
  27124. int nDb; /* Number of valid bytes in zDb */
  27125. struct stat sStat; /* Output of stat() on database file */
  27126. /* zPath is a path to a WAL or journal file. The following block derives
  27127. ** the path to the associated database file from zPath. This block handles
  27128. ** the following naming conventions:
  27129. **
  27130. ** "<path to db>-journal"
  27131. ** "<path to db>-wal"
  27132. ** "<path to db>-journal-NNNN"
  27133. ** "<path to db>-wal-NNNN"
  27134. **
  27135. ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
  27136. ** used by the test_multiplex.c module.
  27137. */
  27138. nDb = sqlite3Strlen30(zPath) - 1;
  27139. while( nDb>0 && zPath[nDb]!='l' ) nDb--;
  27140. nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
  27141. memcpy(zDb, zPath, nDb);
  27142. zDb[nDb] = '\0';
  27143. if( 0==stat(zDb, &sStat) ){
  27144. *pMode = sStat.st_mode & 0777;
  27145. }else{
  27146. rc = SQLITE_IOERR_FSTAT;
  27147. }
  27148. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  27149. *pMode = 0600;
  27150. }else{
  27151. *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
  27152. }
  27153. return rc;
  27154. }
  27155. /*
  27156. ** Open the file zPath.
  27157. **
  27158. ** Previously, the SQLite OS layer used three functions in place of this
  27159. ** one:
  27160. **
  27161. ** sqlite3OsOpenReadWrite();
  27162. ** sqlite3OsOpenReadOnly();
  27163. ** sqlite3OsOpenExclusive();
  27164. **
  27165. ** These calls correspond to the following combinations of flags:
  27166. **
  27167. ** ReadWrite() -> (READWRITE | CREATE)
  27168. ** ReadOnly() -> (READONLY)
  27169. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  27170. **
  27171. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  27172. ** true, the file was configured to be automatically deleted when the
  27173. ** file handle closed. To achieve the same effect using this new
  27174. ** interface, add the DELETEONCLOSE flag to those specified above for
  27175. ** OpenExclusive().
  27176. */
  27177. static int unixOpen(
  27178. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  27179. const char *zPath, /* Pathname of file to be opened */
  27180. sqlite3_file *pFile, /* The file descriptor to be filled in */
  27181. int flags, /* Input flags to control the opening */
  27182. int *pOutFlags /* Output flags returned to SQLite core */
  27183. ){
  27184. unixFile *p = (unixFile *)pFile;
  27185. int fd = -1; /* File descriptor returned by open() */
  27186. int dirfd = -1; /* Directory file descriptor */
  27187. int openFlags = 0; /* Flags to pass to open() */
  27188. int eType = flags&0xFFFFFF00; /* Type of file to open */
  27189. int noLock; /* True to omit locking primitives */
  27190. int rc = SQLITE_OK; /* Function Return Code */
  27191. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  27192. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  27193. int isCreate = (flags & SQLITE_OPEN_CREATE);
  27194. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  27195. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  27196. #if SQLITE_ENABLE_LOCKING_STYLE
  27197. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  27198. #endif
  27199. /* If creating a master or main-file journal, this function will open
  27200. ** a file-descriptor on the directory too. The first time unixSync()
  27201. ** is called the directory file descriptor will be fsync()ed and close()d.
  27202. */
  27203. int isOpenDirectory = (isCreate && (
  27204. eType==SQLITE_OPEN_MASTER_JOURNAL
  27205. || eType==SQLITE_OPEN_MAIN_JOURNAL
  27206. || eType==SQLITE_OPEN_WAL
  27207. ));
  27208. /* If argument zPath is a NULL pointer, this function is required to open
  27209. ** a temporary file. Use this buffer to store the file name in.
  27210. */
  27211. char zTmpname[MAX_PATHNAME+1];
  27212. const char *zName = zPath;
  27213. /* Check the following statements are true:
  27214. **
  27215. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  27216. ** (b) if CREATE is set, then READWRITE must also be set, and
  27217. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  27218. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  27219. */
  27220. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  27221. assert(isCreate==0 || isReadWrite);
  27222. assert(isExclusive==0 || isCreate);
  27223. assert(isDelete==0 || isCreate);
  27224. /* The main DB, main journal, WAL file and master journal are never
  27225. ** automatically deleted. Nor are they ever temporary files. */
  27226. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  27227. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  27228. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  27229. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  27230. /* Assert that the upper layer has set one of the "file-type" flags. */
  27231. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  27232. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  27233. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  27234. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  27235. );
  27236. memset(p, 0, sizeof(unixFile));
  27237. if( eType==SQLITE_OPEN_MAIN_DB ){
  27238. UnixUnusedFd *pUnused;
  27239. pUnused = findReusableFd(zName, flags);
  27240. if( pUnused ){
  27241. fd = pUnused->fd;
  27242. }else{
  27243. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27244. if( !pUnused ){
  27245. return SQLITE_NOMEM;
  27246. }
  27247. }
  27248. p->pUnused = pUnused;
  27249. }else if( !zName ){
  27250. /* If zName is NULL, the upper layer is requesting a temp file. */
  27251. assert(isDelete && !isOpenDirectory);
  27252. rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
  27253. if( rc!=SQLITE_OK ){
  27254. return rc;
  27255. }
  27256. zName = zTmpname;
  27257. }
  27258. /* Determine the value of the flags parameter passed to POSIX function
  27259. ** open(). These must be calculated even if open() is not called, as
  27260. ** they may be stored as part of the file handle and used by the
  27261. ** 'conch file' locking functions later on. */
  27262. if( isReadonly ) openFlags |= O_RDONLY;
  27263. if( isReadWrite ) openFlags |= O_RDWR;
  27264. if( isCreate ) openFlags |= O_CREAT;
  27265. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  27266. openFlags |= (O_LARGEFILE|O_BINARY);
  27267. if( fd<0 ){
  27268. mode_t openMode; /* Permissions to create file with */
  27269. rc = findCreateFileMode(zName, flags, &openMode);
  27270. if( rc!=SQLITE_OK ){
  27271. assert( !p->pUnused );
  27272. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  27273. return rc;
  27274. }
  27275. fd = robust_open(zName, openFlags, openMode);
  27276. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  27277. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  27278. /* Failed to open the file for read/write access. Try read-only. */
  27279. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  27280. openFlags &= ~(O_RDWR|O_CREAT);
  27281. flags |= SQLITE_OPEN_READONLY;
  27282. openFlags |= O_RDONLY;
  27283. isReadonly = 1;
  27284. fd = robust_open(zName, openFlags, openMode);
  27285. }
  27286. if( fd<0 ){
  27287. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  27288. goto open_finished;
  27289. }
  27290. }
  27291. assert( fd>=0 );
  27292. if( pOutFlags ){
  27293. *pOutFlags = flags;
  27294. }
  27295. if( p->pUnused ){
  27296. p->pUnused->fd = fd;
  27297. p->pUnused->flags = flags;
  27298. }
  27299. if( isDelete ){
  27300. #if OS_VXWORKS
  27301. zPath = zName;
  27302. #else
  27303. unlink(zName);
  27304. #endif
  27305. }
  27306. #if SQLITE_ENABLE_LOCKING_STYLE
  27307. else{
  27308. p->openFlags = openFlags;
  27309. }
  27310. #endif
  27311. if( isOpenDirectory ){
  27312. rc = openDirectory(zPath, &dirfd);
  27313. if( rc!=SQLITE_OK ){
  27314. /* It is safe to close fd at this point, because it is guaranteed not
  27315. ** to be open on a database file. If it were open on a database file,
  27316. ** it would not be safe to close as this would release any locks held
  27317. ** on the file by this process. */
  27318. assert( eType!=SQLITE_OPEN_MAIN_DB );
  27319. robust_close(p, fd, __LINE__);
  27320. goto open_finished;
  27321. }
  27322. }
  27323. #ifdef FD_CLOEXEC
  27324. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  27325. #endif
  27326. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  27327. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27328. struct statfs fsInfo;
  27329. if( fstatfs(fd, &fsInfo) == -1 ){
  27330. ((unixFile*)pFile)->lastErrno = errno;
  27331. if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
  27332. robust_close(p, fd, __LINE__);
  27333. return SQLITE_IOERR_ACCESS;
  27334. }
  27335. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  27336. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  27337. }
  27338. #endif
  27339. #if SQLITE_ENABLE_LOCKING_STYLE
  27340. #if SQLITE_PREFER_PROXY_LOCKING
  27341. isAutoProxy = 1;
  27342. #endif
  27343. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  27344. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  27345. int useProxy = 0;
  27346. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  27347. ** never use proxy, NULL means use proxy for non-local files only. */
  27348. if( envforce!=NULL ){
  27349. useProxy = atoi(envforce)>0;
  27350. }else{
  27351. struct statfs fsInfo;
  27352. if( statfs(zPath, &fsInfo) == -1 ){
  27353. /* In theory, the close(fd) call is sub-optimal. If the file opened
  27354. ** with fd is a database file, and there are other connections open
  27355. ** on that file that are currently holding advisory locks on it,
  27356. ** then the call to close() will cancel those locks. In practice,
  27357. ** we're assuming that statfs() doesn't fail very often. At least
  27358. ** not while other file descriptors opened by the same process on
  27359. ** the same file are working. */
  27360. p->lastErrno = errno;
  27361. if( dirfd>=0 ){
  27362. robust_close(p, dirfd, __LINE__);
  27363. }
  27364. robust_close(p, fd, __LINE__);
  27365. rc = SQLITE_IOERR_ACCESS;
  27366. goto open_finished;
  27367. }
  27368. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  27369. }
  27370. if( useProxy ){
  27371. rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
  27372. isDelete, isReadonly);
  27373. if( rc==SQLITE_OK ){
  27374. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  27375. if( rc!=SQLITE_OK ){
  27376. /* Use unixClose to clean up the resources added in fillInUnixFile
  27377. ** and clear all the structure's references. Specifically,
  27378. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  27379. */
  27380. unixClose(pFile);
  27381. return rc;
  27382. }
  27383. }
  27384. goto open_finished;
  27385. }
  27386. }
  27387. #endif
  27388. rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
  27389. isDelete, isReadonly);
  27390. open_finished:
  27391. if( rc!=SQLITE_OK ){
  27392. sqlite3_free(p->pUnused);
  27393. }
  27394. return rc;
  27395. }
  27396. /*
  27397. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  27398. ** the directory after deleting the file.
  27399. */
  27400. static int unixDelete(
  27401. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  27402. const char *zPath, /* Name of file to be deleted */
  27403. int dirSync /* If true, fsync() directory after deleting file */
  27404. ){
  27405. int rc = SQLITE_OK;
  27406. UNUSED_PARAMETER(NotUsed);
  27407. SimulateIOError(return SQLITE_IOERR_DELETE);
  27408. if( unlink(zPath)==(-1) && errno!=ENOENT ){
  27409. return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  27410. }
  27411. #ifndef SQLITE_DISABLE_DIRSYNC
  27412. if( dirSync ){
  27413. int fd;
  27414. rc = openDirectory(zPath, &fd);
  27415. if( rc==SQLITE_OK ){
  27416. #if OS_VXWORKS
  27417. if( fsync(fd)==-1 )
  27418. #else
  27419. if( fsync(fd) )
  27420. #endif
  27421. {
  27422. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  27423. }
  27424. robust_close(0, fd, __LINE__);
  27425. }
  27426. }
  27427. #endif
  27428. return rc;
  27429. }
  27430. /*
  27431. ** Test the existance of or access permissions of file zPath. The
  27432. ** test performed depends on the value of flags:
  27433. **
  27434. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  27435. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  27436. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  27437. **
  27438. ** Otherwise return 0.
  27439. */
  27440. static int unixAccess(
  27441. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  27442. const char *zPath, /* Path of the file to examine */
  27443. int flags, /* What do we want to learn about the zPath file? */
  27444. int *pResOut /* Write result boolean here */
  27445. ){
  27446. int amode = 0;
  27447. UNUSED_PARAMETER(NotUsed);
  27448. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  27449. switch( flags ){
  27450. case SQLITE_ACCESS_EXISTS:
  27451. amode = F_OK;
  27452. break;
  27453. case SQLITE_ACCESS_READWRITE:
  27454. amode = W_OK|R_OK;
  27455. break;
  27456. case SQLITE_ACCESS_READ:
  27457. amode = R_OK;
  27458. break;
  27459. default:
  27460. assert(!"Invalid flags argument");
  27461. }
  27462. *pResOut = (osAccess(zPath, amode)==0);
  27463. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  27464. struct stat buf;
  27465. if( 0==stat(zPath, &buf) && buf.st_size==0 ){
  27466. *pResOut = 0;
  27467. }
  27468. }
  27469. return SQLITE_OK;
  27470. }
  27471. /*
  27472. ** Turn a relative pathname into a full pathname. The relative path
  27473. ** is stored as a nul-terminated string in the buffer pointed to by
  27474. ** zPath.
  27475. **
  27476. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  27477. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  27478. ** this buffer before returning.
  27479. */
  27480. static int unixFullPathname(
  27481. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  27482. const char *zPath, /* Possibly relative input path */
  27483. int nOut, /* Size of output buffer in bytes */
  27484. char *zOut /* Output buffer */
  27485. ){
  27486. /* It's odd to simulate an io-error here, but really this is just
  27487. ** using the io-error infrastructure to test that SQLite handles this
  27488. ** function failing. This function could fail if, for example, the
  27489. ** current working directory has been unlinked.
  27490. */
  27491. SimulateIOError( return SQLITE_ERROR );
  27492. assert( pVfs->mxPathname==MAX_PATHNAME );
  27493. UNUSED_PARAMETER(pVfs);
  27494. zOut[nOut-1] = '\0';
  27495. if( zPath[0]=='/' ){
  27496. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  27497. }else{
  27498. int nCwd;
  27499. if( osGetcwd(zOut, nOut-1)==0 ){
  27500. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  27501. }
  27502. nCwd = (int)strlen(zOut);
  27503. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  27504. }
  27505. return SQLITE_OK;
  27506. }
  27507. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  27508. /*
  27509. ** Interfaces for opening a shared library, finding entry points
  27510. ** within the shared library, and closing the shared library.
  27511. */
  27512. #include <dlfcn.h>
  27513. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  27514. UNUSED_PARAMETER(NotUsed);
  27515. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  27516. }
  27517. /*
  27518. ** SQLite calls this function immediately after a call to unixDlSym() or
  27519. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  27520. ** message is available, it is written to zBufOut. If no error message
  27521. ** is available, zBufOut is left unmodified and SQLite uses a default
  27522. ** error message.
  27523. */
  27524. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  27525. const char *zErr;
  27526. UNUSED_PARAMETER(NotUsed);
  27527. unixEnterMutex();
  27528. zErr = dlerror();
  27529. if( zErr ){
  27530. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  27531. }
  27532. unixLeaveMutex();
  27533. }
  27534. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  27535. /*
  27536. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  27537. ** cast into a pointer to a function. And yet the library dlsym() routine
  27538. ** returns a void* which is really a pointer to a function. So how do we
  27539. ** use dlsym() with -pedantic-errors?
  27540. **
  27541. ** Variable x below is defined to be a pointer to a function taking
  27542. ** parameters void* and const char* and returning a pointer to a function.
  27543. ** We initialize x by assigning it a pointer to the dlsym() function.
  27544. ** (That assignment requires a cast.) Then we call the function that
  27545. ** x points to.
  27546. **
  27547. ** This work-around is unlikely to work correctly on any system where
  27548. ** you really cannot cast a function pointer into void*. But then, on the
  27549. ** other hand, dlsym() will not work on such a system either, so we have
  27550. ** not really lost anything.
  27551. */
  27552. void (*(*x)(void*,const char*))(void);
  27553. UNUSED_PARAMETER(NotUsed);
  27554. x = (void(*(*)(void*,const char*))(void))dlsym;
  27555. return (*x)(p, zSym);
  27556. }
  27557. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  27558. UNUSED_PARAMETER(NotUsed);
  27559. dlclose(pHandle);
  27560. }
  27561. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  27562. #define unixDlOpen 0
  27563. #define unixDlError 0
  27564. #define unixDlSym 0
  27565. #define unixDlClose 0
  27566. #endif
  27567. /*
  27568. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  27569. */
  27570. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  27571. UNUSED_PARAMETER(NotUsed);
  27572. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  27573. /* We have to initialize zBuf to prevent valgrind from reporting
  27574. ** errors. The reports issued by valgrind are incorrect - we would
  27575. ** prefer that the randomness be increased by making use of the
  27576. ** uninitialized space in zBuf - but valgrind errors tend to worry
  27577. ** some users. Rather than argue, it seems easier just to initialize
  27578. ** the whole array and silence valgrind, even if that means less randomness
  27579. ** in the random seed.
  27580. **
  27581. ** When testing, initializing zBuf[] to zero is all we do. That means
  27582. ** that we always use the same random number sequence. This makes the
  27583. ** tests repeatable.
  27584. */
  27585. memset(zBuf, 0, nBuf);
  27586. #if !defined(SQLITE_TEST)
  27587. {
  27588. int pid, fd;
  27589. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  27590. if( fd<0 ){
  27591. time_t t;
  27592. time(&t);
  27593. memcpy(zBuf, &t, sizeof(t));
  27594. pid = getpid();
  27595. memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  27596. assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
  27597. nBuf = sizeof(t) + sizeof(pid);
  27598. }else{
  27599. do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
  27600. robust_close(0, fd, __LINE__);
  27601. }
  27602. }
  27603. #endif
  27604. return nBuf;
  27605. }
  27606. /*
  27607. ** Sleep for a little while. Return the amount of time slept.
  27608. ** The argument is the number of microseconds we want to sleep.
  27609. ** The return value is the number of microseconds of sleep actually
  27610. ** requested from the underlying operating system, a number which
  27611. ** might be greater than or equal to the argument, but not less
  27612. ** than the argument.
  27613. */
  27614. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  27615. #if OS_VXWORKS
  27616. struct timespec sp;
  27617. sp.tv_sec = microseconds / 1000000;
  27618. sp.tv_nsec = (microseconds % 1000000) * 1000;
  27619. nanosleep(&sp, NULL);
  27620. UNUSED_PARAMETER(NotUsed);
  27621. return microseconds;
  27622. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  27623. usleep(microseconds);
  27624. UNUSED_PARAMETER(NotUsed);
  27625. return microseconds;
  27626. #else
  27627. int seconds = (microseconds+999999)/1000000;
  27628. sleep(seconds);
  27629. UNUSED_PARAMETER(NotUsed);
  27630. return seconds*1000000;
  27631. #endif
  27632. }
  27633. /*
  27634. ** The following variable, if set to a non-zero value, is interpreted as
  27635. ** the number of seconds since 1970 and is used to set the result of
  27636. ** sqlite3OsCurrentTime() during testing.
  27637. */
  27638. #ifdef SQLITE_TEST
  27639. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  27640. #endif
  27641. /*
  27642. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  27643. ** the current time and date as a Julian Day number times 86_400_000. In
  27644. ** other words, write into *piNow the number of milliseconds since the Julian
  27645. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  27646. ** proleptic Gregorian calendar.
  27647. **
  27648. ** On success, return 0. Return 1 if the time and date cannot be found.
  27649. */
  27650. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  27651. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  27652. #if defined(NO_GETTOD)
  27653. time_t t;
  27654. time(&t);
  27655. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  27656. #elif OS_VXWORKS
  27657. struct timespec sNow;
  27658. clock_gettime(CLOCK_REALTIME, &sNow);
  27659. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  27660. #else
  27661. struct timeval sNow;
  27662. gettimeofday(&sNow, 0);
  27663. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  27664. #endif
  27665. #ifdef SQLITE_TEST
  27666. if( sqlite3_current_time ){
  27667. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  27668. }
  27669. #endif
  27670. UNUSED_PARAMETER(NotUsed);
  27671. return 0;
  27672. }
  27673. /*
  27674. ** Find the current time (in Universal Coordinated Time). Write the
  27675. ** current time and date as a Julian Day number into *prNow and
  27676. ** return 0. Return 1 if the time and date cannot be found.
  27677. */
  27678. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  27679. sqlite3_int64 i;
  27680. UNUSED_PARAMETER(NotUsed);
  27681. unixCurrentTimeInt64(0, &i);
  27682. *prNow = i/86400000.0;
  27683. return 0;
  27684. }
  27685. /*
  27686. ** We added the xGetLastError() method with the intention of providing
  27687. ** better low-level error messages when operating-system problems come up
  27688. ** during SQLite operation. But so far, none of that has been implemented
  27689. ** in the core. So this routine is never called. For now, it is merely
  27690. ** a place-holder.
  27691. */
  27692. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  27693. UNUSED_PARAMETER(NotUsed);
  27694. UNUSED_PARAMETER(NotUsed2);
  27695. UNUSED_PARAMETER(NotUsed3);
  27696. return 0;
  27697. }
  27698. /*
  27699. ************************ End of sqlite3_vfs methods ***************************
  27700. ******************************************************************************/
  27701. /******************************************************************************
  27702. ************************** Begin Proxy Locking ********************************
  27703. **
  27704. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  27705. ** other locking methods on secondary lock files. Proxy locking is a
  27706. ** meta-layer over top of the primitive locking implemented above. For
  27707. ** this reason, the division that implements of proxy locking is deferred
  27708. ** until late in the file (here) after all of the other I/O methods have
  27709. ** been defined - so that the primitive locking methods are available
  27710. ** as services to help with the implementation of proxy locking.
  27711. **
  27712. ****
  27713. **
  27714. ** The default locking schemes in SQLite use byte-range locks on the
  27715. ** database file to coordinate safe, concurrent access by multiple readers
  27716. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  27717. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  27718. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  27719. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  27720. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  27721. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  27722. ** address in the shared range is taken for a SHARED lock, the entire
  27723. ** shared range is taken for an EXCLUSIVE lock):
  27724. **
  27725. ** PENDING_BYTE 0x40000000
  27726. ** RESERVED_BYTE 0x40000001
  27727. ** SHARED_RANGE 0x40000002 -> 0x40000200
  27728. **
  27729. ** This works well on the local file system, but shows a nearly 100x
  27730. ** slowdown in read performance on AFP because the AFP client disables
  27731. ** the read cache when byte-range locks are present. Enabling the read
  27732. ** cache exposes a cache coherency problem that is present on all OS X
  27733. ** supported network file systems. NFS and AFP both observe the
  27734. ** close-to-open semantics for ensuring cache coherency
  27735. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  27736. ** address the requirements for concurrent database access by multiple
  27737. ** readers and writers
  27738. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  27739. **
  27740. ** To address the performance and cache coherency issues, proxy file locking
  27741. ** changes the way database access is controlled by limiting access to a
  27742. ** single host at a time and moving file locks off of the database file
  27743. ** and onto a proxy file on the local file system.
  27744. **
  27745. **
  27746. ** Using proxy locks
  27747. ** -----------------
  27748. **
  27749. ** C APIs
  27750. **
  27751. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  27752. ** <proxy_path> | ":auto:");
  27753. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  27754. **
  27755. **
  27756. ** SQL pragmas
  27757. **
  27758. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  27759. ** PRAGMA [database.]lock_proxy_file
  27760. **
  27761. ** Specifying ":auto:" means that if there is a conch file with a matching
  27762. ** host ID in it, the proxy path in the conch file will be used, otherwise
  27763. ** a proxy path based on the user's temp dir
  27764. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  27765. ** actual proxy file name is generated from the name and path of the
  27766. ** database file. For example:
  27767. **
  27768. ** For database path "/Users/me/foo.db"
  27769. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  27770. **
  27771. ** Once a lock proxy is configured for a database connection, it can not
  27772. ** be removed, however it may be switched to a different proxy path via
  27773. ** the above APIs (assuming the conch file is not being held by another
  27774. ** connection or process).
  27775. **
  27776. **
  27777. ** How proxy locking works
  27778. ** -----------------------
  27779. **
  27780. ** Proxy file locking relies primarily on two new supporting files:
  27781. **
  27782. ** * conch file to limit access to the database file to a single host
  27783. ** at a time
  27784. **
  27785. ** * proxy file to act as a proxy for the advisory locks normally
  27786. ** taken on the database
  27787. **
  27788. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  27789. ** by taking an sqlite-style shared lock on the conch file, reading the
  27790. ** contents and comparing the host's unique host ID (see below) and lock
  27791. ** proxy path against the values stored in the conch. The conch file is
  27792. ** stored in the same directory as the database file and the file name
  27793. ** is patterned after the database file name as ".<databasename>-conch".
  27794. ** If the conch file does not exist, or it's contents do not match the
  27795. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  27796. ** lock and the conch file contents is updated with the host ID and proxy
  27797. ** path and the lock is downgraded to a shared lock again. If the conch
  27798. ** is held by another process (with a shared lock), the exclusive lock
  27799. ** will fail and SQLITE_BUSY is returned.
  27800. **
  27801. ** The proxy file - a single-byte file used for all advisory file locks
  27802. ** normally taken on the database file. This allows for safe sharing
  27803. ** of the database file for multiple readers and writers on the same
  27804. ** host (the conch ensures that they all use the same local lock file).
  27805. **
  27806. ** Requesting the lock proxy does not immediately take the conch, it is
  27807. ** only taken when the first request to lock database file is made.
  27808. ** This matches the semantics of the traditional locking behavior, where
  27809. ** opening a connection to a database file does not take a lock on it.
  27810. ** The shared lock and an open file descriptor are maintained until
  27811. ** the connection to the database is closed.
  27812. **
  27813. ** The proxy file and the lock file are never deleted so they only need
  27814. ** to be created the first time they are used.
  27815. **
  27816. ** Configuration options
  27817. ** ---------------------
  27818. **
  27819. ** SQLITE_PREFER_PROXY_LOCKING
  27820. **
  27821. ** Database files accessed on non-local file systems are
  27822. ** automatically configured for proxy locking, lock files are
  27823. ** named automatically using the same logic as
  27824. ** PRAGMA lock_proxy_file=":auto:"
  27825. **
  27826. ** SQLITE_PROXY_DEBUG
  27827. **
  27828. ** Enables the logging of error messages during host id file
  27829. ** retrieval and creation
  27830. **
  27831. ** LOCKPROXYDIR
  27832. **
  27833. ** Overrides the default directory used for lock proxy files that
  27834. ** are named automatically via the ":auto:" setting
  27835. **
  27836. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  27837. **
  27838. ** Permissions to use when creating a directory for storing the
  27839. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  27840. **
  27841. **
  27842. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  27843. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  27844. ** force proxy locking to be used for every database file opened, and 0
  27845. ** will force automatic proxy locking to be disabled for all database
  27846. ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
  27847. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  27848. */
  27849. /*
  27850. ** Proxy locking is only available on MacOSX
  27851. */
  27852. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27853. /*
  27854. ** The proxyLockingContext has the path and file structures for the remote
  27855. ** and local proxy files in it
  27856. */
  27857. typedef struct proxyLockingContext proxyLockingContext;
  27858. struct proxyLockingContext {
  27859. unixFile *conchFile; /* Open conch file */
  27860. char *conchFilePath; /* Name of the conch file */
  27861. unixFile *lockProxy; /* Open proxy lock file */
  27862. char *lockProxyPath; /* Name of the proxy lock file */
  27863. char *dbPath; /* Name of the open file */
  27864. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  27865. void *oldLockingContext; /* Original lockingcontext to restore on close */
  27866. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  27867. };
  27868. /*
  27869. ** The proxy lock file path for the database at dbPath is written into lPath,
  27870. ** which must point to valid, writable memory large enough for a maxLen length
  27871. ** file path.
  27872. */
  27873. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  27874. int len;
  27875. int dbLen;
  27876. int i;
  27877. #ifdef LOCKPROXYDIR
  27878. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  27879. #else
  27880. # ifdef _CS_DARWIN_USER_TEMP_DIR
  27881. {
  27882. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  27883. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  27884. lPath, errno, getpid()));
  27885. return SQLITE_IOERR_LOCK;
  27886. }
  27887. len = strlcat(lPath, "sqliteplocks", maxLen);
  27888. }
  27889. # else
  27890. len = strlcpy(lPath, "/tmp/", maxLen);
  27891. # endif
  27892. #endif
  27893. if( lPath[len-1]!='/' ){
  27894. len = strlcat(lPath, "/", maxLen);
  27895. }
  27896. /* transform the db path to a unique cache name */
  27897. dbLen = (int)strlen(dbPath);
  27898. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  27899. char c = dbPath[i];
  27900. lPath[i+len] = (c=='/')?'_':c;
  27901. }
  27902. lPath[i+len]='\0';
  27903. strlcat(lPath, ":auto:", maxLen);
  27904. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
  27905. return SQLITE_OK;
  27906. }
  27907. /*
  27908. ** Creates the lock file and any missing directories in lockPath
  27909. */
  27910. static int proxyCreateLockPath(const char *lockPath){
  27911. int i, len;
  27912. char buf[MAXPATHLEN];
  27913. int start = 0;
  27914. assert(lockPath!=NULL);
  27915. /* try to create all the intermediate directories */
  27916. len = (int)strlen(lockPath);
  27917. buf[0] = lockPath[0];
  27918. for( i=1; i<len; i++ ){
  27919. if( lockPath[i] == '/' && (i - start > 0) ){
  27920. /* only mkdir if leaf dir != "." or "/" or ".." */
  27921. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  27922. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  27923. buf[i]='\0';
  27924. if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  27925. int err=errno;
  27926. if( err!=EEXIST ) {
  27927. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  27928. "'%s' proxy lock path=%s pid=%d\n",
  27929. buf, strerror(err), lockPath, getpid()));
  27930. return err;
  27931. }
  27932. }
  27933. }
  27934. start=i+1;
  27935. }
  27936. buf[i] = lockPath[i];
  27937. }
  27938. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
  27939. return 0;
  27940. }
  27941. /*
  27942. ** Create a new VFS file descriptor (stored in memory obtained from
  27943. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  27944. **
  27945. ** The caller is responsible not only for closing the file descriptor
  27946. ** but also for freeing the memory associated with the file descriptor.
  27947. */
  27948. static int proxyCreateUnixFile(
  27949. const char *path, /* path for the new unixFile */
  27950. unixFile **ppFile, /* unixFile created and returned by ref */
  27951. int islockfile /* if non zero missing dirs will be created */
  27952. ) {
  27953. int fd = -1;
  27954. int dirfd = -1;
  27955. unixFile *pNew;
  27956. int rc = SQLITE_OK;
  27957. int openFlags = O_RDWR | O_CREAT;
  27958. sqlite3_vfs dummyVfs;
  27959. int terrno = 0;
  27960. UnixUnusedFd *pUnused = NULL;
  27961. /* 1. first try to open/create the file
  27962. ** 2. if that fails, and this is a lock file (not-conch), try creating
  27963. ** the parent directories and then try again.
  27964. ** 3. if that fails, try to open the file read-only
  27965. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  27966. */
  27967. pUnused = findReusableFd(path, openFlags);
  27968. if( pUnused ){
  27969. fd = pUnused->fd;
  27970. }else{
  27971. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27972. if( !pUnused ){
  27973. return SQLITE_NOMEM;
  27974. }
  27975. }
  27976. if( fd<0 ){
  27977. fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
  27978. terrno = errno;
  27979. if( fd<0 && errno==ENOENT && islockfile ){
  27980. if( proxyCreateLockPath(path) == SQLITE_OK ){
  27981. fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
  27982. }
  27983. }
  27984. }
  27985. if( fd<0 ){
  27986. openFlags = O_RDONLY;
  27987. fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
  27988. terrno = errno;
  27989. }
  27990. if( fd<0 ){
  27991. if( islockfile ){
  27992. return SQLITE_BUSY;
  27993. }
  27994. switch (terrno) {
  27995. case EACCES:
  27996. return SQLITE_PERM;
  27997. case EIO:
  27998. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  27999. default:
  28000. return SQLITE_CANTOPEN_BKPT;
  28001. }
  28002. }
  28003. pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
  28004. if( pNew==NULL ){
  28005. rc = SQLITE_NOMEM;
  28006. goto end_create_proxy;
  28007. }
  28008. memset(pNew, 0, sizeof(unixFile));
  28009. pNew->openFlags = openFlags;
  28010. memset(&dummyVfs, 0, sizeof(dummyVfs));
  28011. dummyVfs.pAppData = (void*)&autolockIoFinder;
  28012. dummyVfs.zName = "dummy";
  28013. pUnused->fd = fd;
  28014. pUnused->flags = openFlags;
  28015. pNew->pUnused = pUnused;
  28016. rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
  28017. if( rc==SQLITE_OK ){
  28018. *ppFile = pNew;
  28019. return SQLITE_OK;
  28020. }
  28021. end_create_proxy:
  28022. robust_close(pNew, fd, __LINE__);
  28023. sqlite3_free(pNew);
  28024. sqlite3_free(pUnused);
  28025. return rc;
  28026. }
  28027. #ifdef SQLITE_TEST
  28028. /* simulate multiple hosts by creating unique hostid file paths */
  28029. SQLITE_API int sqlite3_hostid_num = 0;
  28030. #endif
  28031. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  28032. /* Not always defined in the headers as it ought to be */
  28033. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  28034. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  28035. ** bytes of writable memory.
  28036. */
  28037. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  28038. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  28039. memset(pHostID, 0, PROXY_HOSTIDLEN);
  28040. #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
  28041. && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
  28042. {
  28043. static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
  28044. if( gethostuuid(pHostID, &timeout) ){
  28045. int err = errno;
  28046. if( pError ){
  28047. *pError = err;
  28048. }
  28049. return SQLITE_IOERR;
  28050. }
  28051. }
  28052. #endif
  28053. #ifdef SQLITE_TEST
  28054. /* simulate multiple hosts by creating unique hostid file paths */
  28055. if( sqlite3_hostid_num != 0){
  28056. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  28057. }
  28058. #endif
  28059. return SQLITE_OK;
  28060. }
  28061. /* The conch file contains the header, host id and lock file path
  28062. */
  28063. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  28064. #define PROXY_HEADERLEN 1 /* conch file header length */
  28065. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  28066. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  28067. /*
  28068. ** Takes an open conch file, copies the contents to a new path and then moves
  28069. ** it back. The newly created file's file descriptor is assigned to the
  28070. ** conch file structure and finally the original conch file descriptor is
  28071. ** closed. Returns zero if successful.
  28072. */
  28073. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  28074. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28075. unixFile *conchFile = pCtx->conchFile;
  28076. char tPath[MAXPATHLEN];
  28077. char buf[PROXY_MAXCONCHLEN];
  28078. char *cPath = pCtx->conchFilePath;
  28079. size_t readLen = 0;
  28080. size_t pathLen = 0;
  28081. char errmsg[64] = "";
  28082. int fd = -1;
  28083. int rc = -1;
  28084. UNUSED_PARAMETER(myHostID);
  28085. /* create a new path by replace the trailing '-conch' with '-break' */
  28086. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  28087. if( pathLen>MAXPATHLEN || pathLen<6 ||
  28088. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  28089. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  28090. goto end_breaklock;
  28091. }
  28092. /* read the conch content */
  28093. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  28094. if( readLen<PROXY_PATHINDEX ){
  28095. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  28096. goto end_breaklock;
  28097. }
  28098. /* write it out to the temporary break file */
  28099. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
  28100. SQLITE_DEFAULT_FILE_PERMISSIONS);
  28101. if( fd<0 ){
  28102. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  28103. goto end_breaklock;
  28104. }
  28105. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  28106. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  28107. goto end_breaklock;
  28108. }
  28109. if( rename(tPath, cPath) ){
  28110. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  28111. goto end_breaklock;
  28112. }
  28113. rc = 0;
  28114. fprintf(stderr, "broke stale lock on %s\n", cPath);
  28115. robust_close(pFile, conchFile->h, __LINE__);
  28116. conchFile->h = fd;
  28117. conchFile->openFlags = O_RDWR | O_CREAT;
  28118. end_breaklock:
  28119. if( rc ){
  28120. if( fd>=0 ){
  28121. unlink(tPath);
  28122. robust_close(pFile, fd, __LINE__);
  28123. }
  28124. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  28125. }
  28126. return rc;
  28127. }
  28128. /* Take the requested lock on the conch file and break a stale lock if the
  28129. ** host id matches.
  28130. */
  28131. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  28132. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28133. unixFile *conchFile = pCtx->conchFile;
  28134. int rc = SQLITE_OK;
  28135. int nTries = 0;
  28136. struct timespec conchModTime;
  28137. do {
  28138. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28139. nTries ++;
  28140. if( rc==SQLITE_BUSY ){
  28141. /* If the lock failed (busy):
  28142. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  28143. * 2nd try: fail if the mod time changed or host id is different, wait
  28144. * 10 sec and try again
  28145. * 3rd try: break the lock unless the mod time has changed.
  28146. */
  28147. struct stat buf;
  28148. if( osFstat(conchFile->h, &buf) ){
  28149. pFile->lastErrno = errno;
  28150. return SQLITE_IOERR_LOCK;
  28151. }
  28152. if( nTries==1 ){
  28153. conchModTime = buf.st_mtimespec;
  28154. usleep(500000); /* wait 0.5 sec and try the lock again*/
  28155. continue;
  28156. }
  28157. assert( nTries>1 );
  28158. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  28159. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  28160. return SQLITE_BUSY;
  28161. }
  28162. if( nTries==2 ){
  28163. char tBuf[PROXY_MAXCONCHLEN];
  28164. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  28165. if( len<0 ){
  28166. pFile->lastErrno = errno;
  28167. return SQLITE_IOERR_LOCK;
  28168. }
  28169. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  28170. /* don't break the lock if the host id doesn't match */
  28171. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  28172. return SQLITE_BUSY;
  28173. }
  28174. }else{
  28175. /* don't break the lock on short read or a version mismatch */
  28176. return SQLITE_BUSY;
  28177. }
  28178. usleep(10000000); /* wait 10 sec and try the lock again */
  28179. continue;
  28180. }
  28181. assert( nTries==3 );
  28182. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  28183. rc = SQLITE_OK;
  28184. if( lockType==EXCLUSIVE_LOCK ){
  28185. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  28186. }
  28187. if( !rc ){
  28188. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28189. }
  28190. }
  28191. }
  28192. } while( rc==SQLITE_BUSY && nTries<3 );
  28193. return rc;
  28194. }
  28195. /* Takes the conch by taking a shared lock and read the contents conch, if
  28196. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  28197. ** lockPath means that the lockPath in the conch file will be used if the
  28198. ** host IDs match, or a new lock path will be generated automatically
  28199. ** and written to the conch file.
  28200. */
  28201. static int proxyTakeConch(unixFile *pFile){
  28202. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28203. if( pCtx->conchHeld!=0 ){
  28204. return SQLITE_OK;
  28205. }else{
  28206. unixFile *conchFile = pCtx->conchFile;
  28207. uuid_t myHostID;
  28208. int pError = 0;
  28209. char readBuf[PROXY_MAXCONCHLEN];
  28210. char lockPath[MAXPATHLEN];
  28211. char *tempLockPath = NULL;
  28212. int rc = SQLITE_OK;
  28213. int createConch = 0;
  28214. int hostIdMatch = 0;
  28215. int readLen = 0;
  28216. int tryOldLockPath = 0;
  28217. int forceNewLockPath = 0;
  28218. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  28219. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
  28220. rc = proxyGetHostID(myHostID, &pError);
  28221. if( (rc&0xff)==SQLITE_IOERR ){
  28222. pFile->lastErrno = pError;
  28223. goto end_takeconch;
  28224. }
  28225. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  28226. if( rc!=SQLITE_OK ){
  28227. goto end_takeconch;
  28228. }
  28229. /* read the existing conch file */
  28230. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  28231. if( readLen<0 ){
  28232. /* I/O error: lastErrno set by seekAndRead */
  28233. pFile->lastErrno = conchFile->lastErrno;
  28234. rc = SQLITE_IOERR_READ;
  28235. goto end_takeconch;
  28236. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  28237. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  28238. /* a short read or version format mismatch means we need to create a new
  28239. ** conch file.
  28240. */
  28241. createConch = 1;
  28242. }
  28243. /* if the host id matches and the lock path already exists in the conch
  28244. ** we'll try to use the path there, if we can't open that path, we'll
  28245. ** retry with a new auto-generated path
  28246. */
  28247. do { /* in case we need to try again for an :auto: named lock file */
  28248. if( !createConch && !forceNewLockPath ){
  28249. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  28250. PROXY_HOSTIDLEN);
  28251. /* if the conch has data compare the contents */
  28252. if( !pCtx->lockProxyPath ){
  28253. /* for auto-named local lock file, just check the host ID and we'll
  28254. ** use the local lock file path that's already in there
  28255. */
  28256. if( hostIdMatch ){
  28257. size_t pathLen = (readLen - PROXY_PATHINDEX);
  28258. if( pathLen>=MAXPATHLEN ){
  28259. pathLen=MAXPATHLEN-1;
  28260. }
  28261. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  28262. lockPath[pathLen] = 0;
  28263. tempLockPath = lockPath;
  28264. tryOldLockPath = 1;
  28265. /* create a copy of the lock path if the conch is taken */
  28266. goto end_takeconch;
  28267. }
  28268. }else if( hostIdMatch
  28269. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  28270. readLen-PROXY_PATHINDEX)
  28271. ){
  28272. /* conch host and lock path match */
  28273. goto end_takeconch;
  28274. }
  28275. }
  28276. /* if the conch isn't writable and doesn't match, we can't take it */
  28277. if( (conchFile->openFlags&O_RDWR) == 0 ){
  28278. rc = SQLITE_BUSY;
  28279. goto end_takeconch;
  28280. }
  28281. /* either the conch didn't match or we need to create a new one */
  28282. if( !pCtx->lockProxyPath ){
  28283. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  28284. tempLockPath = lockPath;
  28285. /* create a copy of the lock path _only_ if the conch is taken */
  28286. }
  28287. /* update conch with host and path (this will fail if other process
  28288. ** has a shared lock already), if the host id matches, use the big
  28289. ** stick.
  28290. */
  28291. futimes(conchFile->h, NULL);
  28292. if( hostIdMatch && !createConch ){
  28293. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  28294. /* We are trying for an exclusive lock but another thread in this
  28295. ** same process is still holding a shared lock. */
  28296. rc = SQLITE_BUSY;
  28297. } else {
  28298. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  28299. }
  28300. }else{
  28301. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  28302. }
  28303. if( rc==SQLITE_OK ){
  28304. char writeBuffer[PROXY_MAXCONCHLEN];
  28305. int writeSize = 0;
  28306. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  28307. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  28308. if( pCtx->lockProxyPath!=NULL ){
  28309. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
  28310. }else{
  28311. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  28312. }
  28313. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  28314. robust_ftruncate(conchFile->h, writeSize);
  28315. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  28316. fsync(conchFile->h);
  28317. /* If we created a new conch file (not just updated the contents of a
  28318. ** valid conch file), try to match the permissions of the database
  28319. */
  28320. if( rc==SQLITE_OK && createConch ){
  28321. struct stat buf;
  28322. int err = osFstat(pFile->h, &buf);
  28323. if( err==0 ){
  28324. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  28325. S_IROTH|S_IWOTH);
  28326. /* try to match the database file R/W permissions, ignore failure */
  28327. #ifndef SQLITE_PROXY_DEBUG
  28328. osFchmod(conchFile->h, cmode);
  28329. #else
  28330. do{
  28331. rc = osFchmod(conchFile->h, cmode);
  28332. }while( rc==(-1) && errno==EINTR );
  28333. if( rc!=0 ){
  28334. int code = errno;
  28335. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  28336. cmode, code, strerror(code));
  28337. } else {
  28338. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  28339. }
  28340. }else{
  28341. int code = errno;
  28342. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  28343. err, code, strerror(code));
  28344. #endif
  28345. }
  28346. }
  28347. }
  28348. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  28349. end_takeconch:
  28350. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  28351. if( rc==SQLITE_OK && pFile->openFlags ){
  28352. if( pFile->h>=0 ){
  28353. robust_close(pFile, pFile->h, __LINE__);
  28354. }
  28355. pFile->h = -1;
  28356. int fd = robust_open(pCtx->dbPath, pFile->openFlags,
  28357. SQLITE_DEFAULT_FILE_PERMISSIONS);
  28358. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  28359. if( fd>=0 ){
  28360. pFile->h = fd;
  28361. }else{
  28362. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  28363. during locking */
  28364. }
  28365. }
  28366. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  28367. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  28368. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  28369. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  28370. /* we couldn't create the proxy lock file with the old lock file path
  28371. ** so try again via auto-naming
  28372. */
  28373. forceNewLockPath = 1;
  28374. tryOldLockPath = 0;
  28375. continue; /* go back to the do {} while start point, try again */
  28376. }
  28377. }
  28378. if( rc==SQLITE_OK ){
  28379. /* Need to make a copy of path if we extracted the value
  28380. ** from the conch file or the path was allocated on the stack
  28381. */
  28382. if( tempLockPath ){
  28383. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  28384. if( !pCtx->lockProxyPath ){
  28385. rc = SQLITE_NOMEM;
  28386. }
  28387. }
  28388. }
  28389. if( rc==SQLITE_OK ){
  28390. pCtx->conchHeld = 1;
  28391. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  28392. afpLockingContext *afpCtx;
  28393. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  28394. afpCtx->dbPath = pCtx->lockProxyPath;
  28395. }
  28396. } else {
  28397. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28398. }
  28399. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  28400. rc==SQLITE_OK?"ok":"failed"));
  28401. return rc;
  28402. } while (1); /* in case we need to retry the :auto: lock file -
  28403. ** we should never get here except via the 'continue' call. */
  28404. }
  28405. }
  28406. /*
  28407. ** If pFile holds a lock on a conch file, then release that lock.
  28408. */
  28409. static int proxyReleaseConch(unixFile *pFile){
  28410. int rc = SQLITE_OK; /* Subroutine return code */
  28411. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  28412. unixFile *conchFile; /* Name of the conch file */
  28413. pCtx = (proxyLockingContext *)pFile->lockingContext;
  28414. conchFile = pCtx->conchFile;
  28415. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  28416. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  28417. getpid()));
  28418. if( pCtx->conchHeld>0 ){
  28419. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28420. }
  28421. pCtx->conchHeld = 0;
  28422. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  28423. (rc==SQLITE_OK ? "ok" : "failed")));
  28424. return rc;
  28425. }
  28426. /*
  28427. ** Given the name of a database file, compute the name of its conch file.
  28428. ** Store the conch filename in memory obtained from sqlite3_malloc().
  28429. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  28430. ** or SQLITE_NOMEM if unable to obtain memory.
  28431. **
  28432. ** The caller is responsible for ensuring that the allocated memory
  28433. ** space is eventually freed.
  28434. **
  28435. ** *pConchPath is set to NULL if a memory allocation error occurs.
  28436. */
  28437. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  28438. int i; /* Loop counter */
  28439. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  28440. char *conchPath; /* buffer in which to construct conch name */
  28441. /* Allocate space for the conch filename and initialize the name to
  28442. ** the name of the original database file. */
  28443. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  28444. if( conchPath==0 ){
  28445. return SQLITE_NOMEM;
  28446. }
  28447. memcpy(conchPath, dbPath, len+1);
  28448. /* now insert a "." before the last / character */
  28449. for( i=(len-1); i>=0; i-- ){
  28450. if( conchPath[i]=='/' ){
  28451. i++;
  28452. break;
  28453. }
  28454. }
  28455. conchPath[i]='.';
  28456. while ( i<len ){
  28457. conchPath[i+1]=dbPath[i];
  28458. i++;
  28459. }
  28460. /* append the "-conch" suffix to the file */
  28461. memcpy(&conchPath[i+1], "-conch", 7);
  28462. assert( (int)strlen(conchPath) == len+7 );
  28463. return SQLITE_OK;
  28464. }
  28465. /* Takes a fully configured proxy locking-style unix file and switches
  28466. ** the local lock file path
  28467. */
  28468. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  28469. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28470. char *oldPath = pCtx->lockProxyPath;
  28471. int rc = SQLITE_OK;
  28472. if( pFile->eFileLock!=NO_LOCK ){
  28473. return SQLITE_BUSY;
  28474. }
  28475. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  28476. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  28477. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  28478. return SQLITE_OK;
  28479. }else{
  28480. unixFile *lockProxy = pCtx->lockProxy;
  28481. pCtx->lockProxy=NULL;
  28482. pCtx->conchHeld = 0;
  28483. if( lockProxy!=NULL ){
  28484. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  28485. if( rc ) return rc;
  28486. sqlite3_free(lockProxy);
  28487. }
  28488. sqlite3_free(oldPath);
  28489. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  28490. }
  28491. return rc;
  28492. }
  28493. /*
  28494. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  28495. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  28496. **
  28497. ** This routine find the filename associated with pFile and writes it
  28498. ** int dbPath.
  28499. */
  28500. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  28501. #if defined(__APPLE__)
  28502. if( pFile->pMethod == &afpIoMethods ){
  28503. /* afp style keeps a reference to the db path in the filePath field
  28504. ** of the struct */
  28505. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28506. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
  28507. } else
  28508. #endif
  28509. if( pFile->pMethod == &dotlockIoMethods ){
  28510. /* dot lock style uses the locking context to store the dot lock
  28511. ** file path */
  28512. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  28513. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  28514. }else{
  28515. /* all other styles use the locking context to store the db file path */
  28516. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28517. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  28518. }
  28519. return SQLITE_OK;
  28520. }
  28521. /*
  28522. ** Takes an already filled in unix file and alters it so all file locking
  28523. ** will be performed on the local proxy lock file. The following fields
  28524. ** are preserved in the locking context so that they can be restored and
  28525. ** the unix structure properly cleaned up at close time:
  28526. ** ->lockingContext
  28527. ** ->pMethod
  28528. */
  28529. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  28530. proxyLockingContext *pCtx;
  28531. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  28532. char *lockPath=NULL;
  28533. int rc = SQLITE_OK;
  28534. if( pFile->eFileLock!=NO_LOCK ){
  28535. return SQLITE_BUSY;
  28536. }
  28537. proxyGetDbPathForUnixFile(pFile, dbPath);
  28538. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  28539. lockPath=NULL;
  28540. }else{
  28541. lockPath=(char *)path;
  28542. }
  28543. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  28544. (lockPath ? lockPath : ":auto:"), getpid()));
  28545. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  28546. if( pCtx==0 ){
  28547. return SQLITE_NOMEM;
  28548. }
  28549. memset(pCtx, 0, sizeof(*pCtx));
  28550. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  28551. if( rc==SQLITE_OK ){
  28552. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  28553. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  28554. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  28555. ** (c) the file system is read-only, then enable no-locking access.
  28556. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  28557. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  28558. */
  28559. struct statfs fsInfo;
  28560. struct stat conchInfo;
  28561. int goLockless = 0;
  28562. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  28563. int err = errno;
  28564. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  28565. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  28566. }
  28567. }
  28568. if( goLockless ){
  28569. pCtx->conchHeld = -1; /* read only FS/ lockless */
  28570. rc = SQLITE_OK;
  28571. }
  28572. }
  28573. }
  28574. if( rc==SQLITE_OK && lockPath ){
  28575. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  28576. }
  28577. if( rc==SQLITE_OK ){
  28578. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  28579. if( pCtx->dbPath==NULL ){
  28580. rc = SQLITE_NOMEM;
  28581. }
  28582. }
  28583. if( rc==SQLITE_OK ){
  28584. /* all memory is allocated, proxys are created and assigned,
  28585. ** switch the locking context and pMethod then return.
  28586. */
  28587. pCtx->oldLockingContext = pFile->lockingContext;
  28588. pFile->lockingContext = pCtx;
  28589. pCtx->pOldMethod = pFile->pMethod;
  28590. pFile->pMethod = &proxyIoMethods;
  28591. }else{
  28592. if( pCtx->conchFile ){
  28593. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  28594. sqlite3_free(pCtx->conchFile);
  28595. }
  28596. sqlite3DbFree(0, pCtx->lockProxyPath);
  28597. sqlite3_free(pCtx->conchFilePath);
  28598. sqlite3_free(pCtx);
  28599. }
  28600. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  28601. (rc==SQLITE_OK ? "ok" : "failed")));
  28602. return rc;
  28603. }
  28604. /*
  28605. ** This routine handles sqlite3_file_control() calls that are specific
  28606. ** to proxy locking.
  28607. */
  28608. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  28609. switch( op ){
  28610. case SQLITE_GET_LOCKPROXYFILE: {
  28611. unixFile *pFile = (unixFile*)id;
  28612. if( pFile->pMethod == &proxyIoMethods ){
  28613. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28614. proxyTakeConch(pFile);
  28615. if( pCtx->lockProxyPath ){
  28616. *(const char **)pArg = pCtx->lockProxyPath;
  28617. }else{
  28618. *(const char **)pArg = ":auto: (not held)";
  28619. }
  28620. } else {
  28621. *(const char **)pArg = NULL;
  28622. }
  28623. return SQLITE_OK;
  28624. }
  28625. case SQLITE_SET_LOCKPROXYFILE: {
  28626. unixFile *pFile = (unixFile*)id;
  28627. int rc = SQLITE_OK;
  28628. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  28629. if( pArg==NULL || (const char *)pArg==0 ){
  28630. if( isProxyStyle ){
  28631. /* turn off proxy locking - not supported */
  28632. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  28633. }else{
  28634. /* turn off proxy locking - already off - NOOP */
  28635. rc = SQLITE_OK;
  28636. }
  28637. }else{
  28638. const char *proxyPath = (const char *)pArg;
  28639. if( isProxyStyle ){
  28640. proxyLockingContext *pCtx =
  28641. (proxyLockingContext*)pFile->lockingContext;
  28642. if( !strcmp(pArg, ":auto:")
  28643. || (pCtx->lockProxyPath &&
  28644. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  28645. ){
  28646. rc = SQLITE_OK;
  28647. }else{
  28648. rc = switchLockProxyPath(pFile, proxyPath);
  28649. }
  28650. }else{
  28651. /* turn on proxy file locking */
  28652. rc = proxyTransformUnixFile(pFile, proxyPath);
  28653. }
  28654. }
  28655. return rc;
  28656. }
  28657. default: {
  28658. assert( 0 ); /* The call assures that only valid opcodes are sent */
  28659. }
  28660. }
  28661. /*NOTREACHED*/
  28662. return SQLITE_ERROR;
  28663. }
  28664. /*
  28665. ** Within this division (the proxying locking implementation) the procedures
  28666. ** above this point are all utilities. The lock-related methods of the
  28667. ** proxy-locking sqlite3_io_method object follow.
  28668. */
  28669. /*
  28670. ** This routine checks if there is a RESERVED lock held on the specified
  28671. ** file by this or any other process. If such a lock is held, set *pResOut
  28672. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28673. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28674. */
  28675. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  28676. unixFile *pFile = (unixFile*)id;
  28677. int rc = proxyTakeConch(pFile);
  28678. if( rc==SQLITE_OK ){
  28679. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28680. if( pCtx->conchHeld>0 ){
  28681. unixFile *proxy = pCtx->lockProxy;
  28682. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  28683. }else{ /* conchHeld < 0 is lockless */
  28684. pResOut=0;
  28685. }
  28686. }
  28687. return rc;
  28688. }
  28689. /*
  28690. ** Lock the file with the lock specified by parameter eFileLock - one
  28691. ** of the following:
  28692. **
  28693. ** (1) SHARED_LOCK
  28694. ** (2) RESERVED_LOCK
  28695. ** (3) PENDING_LOCK
  28696. ** (4) EXCLUSIVE_LOCK
  28697. **
  28698. ** Sometimes when requesting one lock state, additional lock states
  28699. ** are inserted in between. The locking might fail on one of the later
  28700. ** transitions leaving the lock state different from what it started but
  28701. ** still short of its goal. The following chart shows the allowed
  28702. ** transitions and the inserted intermediate states:
  28703. **
  28704. ** UNLOCKED -> SHARED
  28705. ** SHARED -> RESERVED
  28706. ** SHARED -> (PENDING) -> EXCLUSIVE
  28707. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28708. ** PENDING -> EXCLUSIVE
  28709. **
  28710. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28711. ** routine to lower a locking level.
  28712. */
  28713. static int proxyLock(sqlite3_file *id, int eFileLock) {
  28714. unixFile *pFile = (unixFile*)id;
  28715. int rc = proxyTakeConch(pFile);
  28716. if( rc==SQLITE_OK ){
  28717. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28718. if( pCtx->conchHeld>0 ){
  28719. unixFile *proxy = pCtx->lockProxy;
  28720. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  28721. pFile->eFileLock = proxy->eFileLock;
  28722. }else{
  28723. /* conchHeld < 0 is lockless */
  28724. }
  28725. }
  28726. return rc;
  28727. }
  28728. /*
  28729. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28730. ** must be either NO_LOCK or SHARED_LOCK.
  28731. **
  28732. ** If the locking level of the file descriptor is already at or below
  28733. ** the requested locking level, this routine is a no-op.
  28734. */
  28735. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  28736. unixFile *pFile = (unixFile*)id;
  28737. int rc = proxyTakeConch(pFile);
  28738. if( rc==SQLITE_OK ){
  28739. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28740. if( pCtx->conchHeld>0 ){
  28741. unixFile *proxy = pCtx->lockProxy;
  28742. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  28743. pFile->eFileLock = proxy->eFileLock;
  28744. }else{
  28745. /* conchHeld < 0 is lockless */
  28746. }
  28747. }
  28748. return rc;
  28749. }
  28750. /*
  28751. ** Close a file that uses proxy locks.
  28752. */
  28753. static int proxyClose(sqlite3_file *id) {
  28754. if( id ){
  28755. unixFile *pFile = (unixFile*)id;
  28756. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28757. unixFile *lockProxy = pCtx->lockProxy;
  28758. unixFile *conchFile = pCtx->conchFile;
  28759. int rc = SQLITE_OK;
  28760. if( lockProxy ){
  28761. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  28762. if( rc ) return rc;
  28763. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  28764. if( rc ) return rc;
  28765. sqlite3_free(lockProxy);
  28766. pCtx->lockProxy = 0;
  28767. }
  28768. if( conchFile ){
  28769. if( pCtx->conchHeld ){
  28770. rc = proxyReleaseConch(pFile);
  28771. if( rc ) return rc;
  28772. }
  28773. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  28774. if( rc ) return rc;
  28775. sqlite3_free(conchFile);
  28776. }
  28777. sqlite3DbFree(0, pCtx->lockProxyPath);
  28778. sqlite3_free(pCtx->conchFilePath);
  28779. sqlite3DbFree(0, pCtx->dbPath);
  28780. /* restore the original locking context and pMethod then close it */
  28781. pFile->lockingContext = pCtx->oldLockingContext;
  28782. pFile->pMethod = pCtx->pOldMethod;
  28783. sqlite3_free(pCtx);
  28784. return pFile->pMethod->xClose(id);
  28785. }
  28786. return SQLITE_OK;
  28787. }
  28788. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28789. /*
  28790. ** The proxy locking style is intended for use with AFP filesystems.
  28791. ** And since AFP is only supported on MacOSX, the proxy locking is also
  28792. ** restricted to MacOSX.
  28793. **
  28794. **
  28795. ******************* End of the proxy lock implementation **********************
  28796. ******************************************************************************/
  28797. /*
  28798. ** Initialize the operating system interface.
  28799. **
  28800. ** This routine registers all VFS implementations for unix-like operating
  28801. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  28802. ** should be the only routines in this file that are visible from other
  28803. ** files.
  28804. **
  28805. ** This routine is called once during SQLite initialization and by a
  28806. ** single thread. The memory allocation and mutex subsystems have not
  28807. ** necessarily been initialized when this routine is called, and so they
  28808. ** should not be used.
  28809. */
  28810. SQLITE_API int sqlite3_os_init(void){
  28811. /*
  28812. ** The following macro defines an initializer for an sqlite3_vfs object.
  28813. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  28814. ** to the "finder" function. (pAppData is a pointer to a pointer because
  28815. ** silly C90 rules prohibit a void* from being cast to a function pointer
  28816. ** and so we have to go through the intermediate pointer to avoid problems
  28817. ** when compiling with -pedantic-errors on GCC.)
  28818. **
  28819. ** The FINDER parameter to this macro is the name of the pointer to the
  28820. ** finder-function. The finder-function returns a pointer to the
  28821. ** sqlite_io_methods object that implements the desired locking
  28822. ** behaviors. See the division above that contains the IOMETHODS
  28823. ** macro for addition information on finder-functions.
  28824. **
  28825. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  28826. ** object. But the "autolockIoFinder" available on MacOSX does a little
  28827. ** more than that; it looks at the filesystem type that hosts the
  28828. ** database file and tries to choose an locking method appropriate for
  28829. ** that filesystem time.
  28830. */
  28831. #define UNIXVFS(VFSNAME, FINDER) { \
  28832. 3, /* iVersion */ \
  28833. sizeof(unixFile), /* szOsFile */ \
  28834. MAX_PATHNAME, /* mxPathname */ \
  28835. 0, /* pNext */ \
  28836. VFSNAME, /* zName */ \
  28837. (void*)&FINDER, /* pAppData */ \
  28838. unixOpen, /* xOpen */ \
  28839. unixDelete, /* xDelete */ \
  28840. unixAccess, /* xAccess */ \
  28841. unixFullPathname, /* xFullPathname */ \
  28842. unixDlOpen, /* xDlOpen */ \
  28843. unixDlError, /* xDlError */ \
  28844. unixDlSym, /* xDlSym */ \
  28845. unixDlClose, /* xDlClose */ \
  28846. unixRandomness, /* xRandomness */ \
  28847. unixSleep, /* xSleep */ \
  28848. unixCurrentTime, /* xCurrentTime */ \
  28849. unixGetLastError, /* xGetLastError */ \
  28850. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  28851. unixSetSystemCall, /* xSetSystemCall */ \
  28852. unixGetSystemCall, /* xGetSystemCall */ \
  28853. unixNextSystemCall, /* xNextSystemCall */ \
  28854. }
  28855. /*
  28856. ** All default VFSes for unix are contained in the following array.
  28857. **
  28858. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  28859. ** by the SQLite core when the VFS is registered. So the following
  28860. ** array cannot be const.
  28861. */
  28862. static sqlite3_vfs aVfs[] = {
  28863. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  28864. UNIXVFS("unix", autolockIoFinder ),
  28865. #else
  28866. UNIXVFS("unix", posixIoFinder ),
  28867. #endif
  28868. UNIXVFS("unix-none", nolockIoFinder ),
  28869. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  28870. UNIXVFS("unix-excl", posixIoFinder ),
  28871. #if OS_VXWORKS
  28872. UNIXVFS("unix-namedsem", semIoFinder ),
  28873. #endif
  28874. #if SQLITE_ENABLE_LOCKING_STYLE
  28875. UNIXVFS("unix-posix", posixIoFinder ),
  28876. #if !OS_VXWORKS
  28877. UNIXVFS("unix-flock", flockIoFinder ),
  28878. #endif
  28879. #endif
  28880. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28881. UNIXVFS("unix-afp", afpIoFinder ),
  28882. UNIXVFS("unix-nfs", nfsIoFinder ),
  28883. UNIXVFS("unix-proxy", proxyIoFinder ),
  28884. #endif
  28885. };
  28886. unsigned int i; /* Loop counter */
  28887. /* Double-check that the aSyscall[] array has been constructed
  28888. ** correctly. See ticket [bb3a86e890c8e96ab] */
  28889. assert( ArraySize(aSyscall)==16 );
  28890. /* Register all VFSes defined in the aVfs[] array */
  28891. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  28892. sqlite3_vfs_register(&aVfs[i], i==0);
  28893. }
  28894. return SQLITE_OK;
  28895. }
  28896. /*
  28897. ** Shutdown the operating system interface.
  28898. **
  28899. ** Some operating systems might need to do some cleanup in this routine,
  28900. ** to release dynamically allocated objects. But not on unix.
  28901. ** This routine is a no-op for unix.
  28902. */
  28903. SQLITE_API int sqlite3_os_end(void){
  28904. return SQLITE_OK;
  28905. }
  28906. #endif /* SQLITE_OS_UNIX */
  28907. /************** End of os_unix.c *********************************************/
  28908. /************** Begin file os_win.c ******************************************/
  28909. /*
  28910. ** 2004 May 22
  28911. **
  28912. ** The author disclaims copyright to this source code. In place of
  28913. ** a legal notice, here is a blessing:
  28914. **
  28915. ** May you do good and not evil.
  28916. ** May you find forgiveness for yourself and forgive others.
  28917. ** May you share freely, never taking more than you give.
  28918. **
  28919. ******************************************************************************
  28920. **
  28921. ** This file contains code that is specific to windows.
  28922. */
  28923. #if SQLITE_OS_WIN /* This file is used for windows only */
  28924. /*
  28925. ** A Note About Memory Allocation:
  28926. **
  28927. ** This driver uses malloc()/free() directly rather than going through
  28928. ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free(). Those wrappers
  28929. ** are designed for use on embedded systems where memory is scarce and
  28930. ** malloc failures happen frequently. Win32 does not typically run on
  28931. ** embedded systems, and when it does the developers normally have bigger
  28932. ** problems to worry about than running out of memory. So there is not
  28933. ** a compelling need to use the wrappers.
  28934. **
  28935. ** But there is a good reason to not use the wrappers. If we use the
  28936. ** wrappers then we will get simulated malloc() failures within this
  28937. ** driver. And that causes all kinds of problems for our tests. We
  28938. ** could enhance SQLite to deal with simulated malloc failures within
  28939. ** the OS driver, but the code to deal with those failure would not
  28940. ** be exercised on Linux (which does not need to malloc() in the driver)
  28941. ** and so we would have difficulty writing coverage tests for that
  28942. ** code. Better to leave the code out, we think.
  28943. **
  28944. ** The point of this discussion is as follows: When creating a new
  28945. ** OS layer for an embedded system, if you use this file as an example,
  28946. ** avoid the use of malloc()/free(). Those routines work ok on windows
  28947. ** desktops but not so well in embedded systems.
  28948. */
  28949. #include <winbase.h>
  28950. #ifdef __CYGWIN__
  28951. # include <sys/cygwin.h>
  28952. #endif
  28953. /*
  28954. ** Macros used to determine whether or not to use threads.
  28955. */
  28956. #if defined(THREADSAFE) && THREADSAFE
  28957. # define SQLITE_W32_THREADS 1
  28958. #endif
  28959. /*
  28960. ** Include code that is common to all os_*.c files
  28961. */
  28962. /************** Include os_common.h in the middle of os_win.c ****************/
  28963. /************** Begin file os_common.h ***************************************/
  28964. /*
  28965. ** 2004 May 22
  28966. **
  28967. ** The author disclaims copyright to this source code. In place of
  28968. ** a legal notice, here is a blessing:
  28969. **
  28970. ** May you do good and not evil.
  28971. ** May you find forgiveness for yourself and forgive others.
  28972. ** May you share freely, never taking more than you give.
  28973. **
  28974. ******************************************************************************
  28975. **
  28976. ** This file contains macros and a little bit of code that is common to
  28977. ** all of the platform-specific files (os_*.c) and is #included into those
  28978. ** files.
  28979. **
  28980. ** This file should be #included by the os_*.c files only. It is not a
  28981. ** general purpose header file.
  28982. */
  28983. #ifndef _OS_COMMON_H_
  28984. #define _OS_COMMON_H_
  28985. /*
  28986. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  28987. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  28988. ** switch. The following code should catch this problem at compile-time.
  28989. */
  28990. #ifdef MEMORY_DEBUG
  28991. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  28992. #endif
  28993. #ifdef SQLITE_DEBUG
  28994. SQLITE_PRIVATE int sqlite3OSTrace = 0;
  28995. #define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  28996. #else
  28997. #define OSTRACE(X)
  28998. #endif
  28999. /*
  29000. ** Macros for performance tracing. Normally turned off. Only works
  29001. ** on i486 hardware.
  29002. */
  29003. #ifdef SQLITE_PERFORMANCE_TRACE
  29004. /*
  29005. ** hwtime.h contains inline assembler code for implementing
  29006. ** high-performance timing routines.
  29007. */
  29008. /************** Include hwtime.h in the middle of os_common.h ****************/
  29009. /************** Begin file hwtime.h ******************************************/
  29010. /*
  29011. ** 2008 May 27
  29012. **
  29013. ** The author disclaims copyright to this source code. In place of
  29014. ** a legal notice, here is a blessing:
  29015. **
  29016. ** May you do good and not evil.
  29017. ** May you find forgiveness for yourself and forgive others.
  29018. ** May you share freely, never taking more than you give.
  29019. **
  29020. ******************************************************************************
  29021. **
  29022. ** This file contains inline asm code for retrieving "high-performance"
  29023. ** counters for x86 class CPUs.
  29024. */
  29025. #ifndef _HWTIME_H_
  29026. #define _HWTIME_H_
  29027. /*
  29028. ** The following routine only works on pentium-class (or newer) processors.
  29029. ** It uses the RDTSC opcode to read the cycle count value out of the
  29030. ** processor and returns that value. This can be used for high-res
  29031. ** profiling.
  29032. */
  29033. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  29034. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  29035. #if defined(__GNUC__)
  29036. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29037. unsigned int lo, hi;
  29038. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  29039. return (sqlite_uint64)hi << 32 | lo;
  29040. }
  29041. #elif defined(_MSC_VER)
  29042. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  29043. __asm {
  29044. rdtsc
  29045. ret ; return value at EDX:EAX
  29046. }
  29047. }
  29048. #endif
  29049. #elif (defined(__GNUC__) && defined(__x86_64__))
  29050. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29051. unsigned long val;
  29052. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  29053. return val;
  29054. }
  29055. #elif (defined(__GNUC__) && defined(__ppc__))
  29056. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29057. unsigned long long retval;
  29058. unsigned long junk;
  29059. __asm__ __volatile__ ("\n\
  29060. 1: mftbu %1\n\
  29061. mftb %L0\n\
  29062. mftbu %0\n\
  29063. cmpw %0,%1\n\
  29064. bne 1b"
  29065. : "=r" (retval), "=r" (junk));
  29066. return retval;
  29067. }
  29068. #else
  29069. #error Need implementation of sqlite3Hwtime() for your platform.
  29070. /*
  29071. ** To compile without implementing sqlite3Hwtime() for your platform,
  29072. ** you can remove the above #error and use the following
  29073. ** stub function. You will lose timing support for many
  29074. ** of the debugging and testing utilities, but it should at
  29075. ** least compile and run.
  29076. */
  29077. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  29078. #endif
  29079. #endif /* !defined(_HWTIME_H_) */
  29080. /************** End of hwtime.h **********************************************/
  29081. /************** Continuing where we left off in os_common.h ******************/
  29082. static sqlite_uint64 g_start;
  29083. static sqlite_uint64 g_elapsed;
  29084. #define TIMER_START g_start=sqlite3Hwtime()
  29085. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  29086. #define TIMER_ELAPSED g_elapsed
  29087. #else
  29088. #define TIMER_START
  29089. #define TIMER_END
  29090. #define TIMER_ELAPSED ((sqlite_uint64)0)
  29091. #endif
  29092. /*
  29093. ** If we compile with the SQLITE_TEST macro set, then the following block
  29094. ** of code will give us the ability to simulate a disk I/O error. This
  29095. ** is used for testing the I/O recovery logic.
  29096. */
  29097. #ifdef SQLITE_TEST
  29098. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  29099. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  29100. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  29101. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  29102. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  29103. SQLITE_API int sqlite3_diskfull_pending = 0;
  29104. SQLITE_API int sqlite3_diskfull = 0;
  29105. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  29106. #define SimulateIOError(CODE) \
  29107. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  29108. || sqlite3_io_error_pending-- == 1 ) \
  29109. { local_ioerr(); CODE; }
  29110. static void local_ioerr(){
  29111. IOTRACE(("IOERR\n"));
  29112. sqlite3_io_error_hit++;
  29113. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  29114. }
  29115. #define SimulateDiskfullError(CODE) \
  29116. if( sqlite3_diskfull_pending ){ \
  29117. if( sqlite3_diskfull_pending == 1 ){ \
  29118. local_ioerr(); \
  29119. sqlite3_diskfull = 1; \
  29120. sqlite3_io_error_hit = 1; \
  29121. CODE; \
  29122. }else{ \
  29123. sqlite3_diskfull_pending--; \
  29124. } \
  29125. }
  29126. #else
  29127. #define SimulateIOErrorBenign(X)
  29128. #define SimulateIOError(A)
  29129. #define SimulateDiskfullError(A)
  29130. #endif
  29131. /*
  29132. ** When testing, keep a count of the number of open files.
  29133. */
  29134. #ifdef SQLITE_TEST
  29135. SQLITE_API int sqlite3_open_file_count = 0;
  29136. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  29137. #else
  29138. #define OpenCounter(X)
  29139. #endif
  29140. #endif /* !defined(_OS_COMMON_H_) */
  29141. /************** End of os_common.h *******************************************/
  29142. /************** Continuing where we left off in os_win.c *********************/
  29143. /*
  29144. ** Some microsoft compilers lack this definition.
  29145. */
  29146. #ifndef INVALID_FILE_ATTRIBUTES
  29147. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  29148. #endif
  29149. /*
  29150. ** Determine if we are dealing with WindowsCE - which has a much
  29151. ** reduced API.
  29152. */
  29153. #if SQLITE_OS_WINCE
  29154. # define AreFileApisANSI() 1
  29155. # define FormatMessageW(a,b,c,d,e,f,g) 0
  29156. #endif
  29157. /* Forward references */
  29158. typedef struct winShm winShm; /* A connection to shared-memory */
  29159. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  29160. /*
  29161. ** WinCE lacks native support for file locking so we have to fake it
  29162. ** with some code of our own.
  29163. */
  29164. #if SQLITE_OS_WINCE
  29165. typedef struct winceLock {
  29166. int nReaders; /* Number of reader locks obtained */
  29167. BOOL bPending; /* Indicates a pending lock has been obtained */
  29168. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  29169. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  29170. } winceLock;
  29171. #endif
  29172. /*
  29173. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  29174. ** portability layer.
  29175. */
  29176. typedef struct winFile winFile;
  29177. struct winFile {
  29178. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  29179. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  29180. HANDLE h; /* Handle for accessing the file */
  29181. unsigned char locktype; /* Type of lock currently held on this file */
  29182. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  29183. DWORD lastErrno; /* The Windows errno from the last I/O error */
  29184. DWORD sectorSize; /* Sector size of the device file is on */
  29185. winShm *pShm; /* Instance of shared memory on this file */
  29186. const char *zPath; /* Full pathname of this file */
  29187. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  29188. #if SQLITE_OS_WINCE
  29189. WCHAR *zDeleteOnClose; /* Name of file to delete when closing */
  29190. HANDLE hMutex; /* Mutex used to control access to shared lock */
  29191. HANDLE hShared; /* Shared memory segment used for locking */
  29192. winceLock local; /* Locks obtained by this instance of winFile */
  29193. winceLock *shared; /* Global shared lock memory for the file */
  29194. #endif
  29195. };
  29196. /*
  29197. ** Forward prototypes.
  29198. */
  29199. static int getSectorSize(
  29200. sqlite3_vfs *pVfs,
  29201. const char *zRelative /* UTF-8 file name */
  29202. );
  29203. /*
  29204. ** The following variable is (normally) set once and never changes
  29205. ** thereafter. It records whether the operating system is Win95
  29206. ** or WinNT.
  29207. **
  29208. ** 0: Operating system unknown.
  29209. ** 1: Operating system is Win95.
  29210. ** 2: Operating system is WinNT.
  29211. **
  29212. ** In order to facilitate testing on a WinNT system, the test fixture
  29213. ** can manually set this value to 1 to emulate Win98 behavior.
  29214. */
  29215. #ifdef SQLITE_TEST
  29216. SQLITE_API int sqlite3_os_type = 0;
  29217. #else
  29218. static int sqlite3_os_type = 0;
  29219. #endif
  29220. /*
  29221. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  29222. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  29223. **
  29224. ** Here is an interesting observation: Win95, Win98, and WinME lack
  29225. ** the LockFileEx() API. But we can still statically link against that
  29226. ** API as long as we don't call it when running Win95/98/ME. A call to
  29227. ** this routine is used to determine if the host is Win95/98/ME or
  29228. ** WinNT/2K/XP so that we will know whether or not we can safely call
  29229. ** the LockFileEx() API.
  29230. */
  29231. #if SQLITE_OS_WINCE
  29232. # define isNT() (1)
  29233. #else
  29234. static int isNT(void){
  29235. if( sqlite3_os_type==0 ){
  29236. OSVERSIONINFO sInfo;
  29237. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  29238. GetVersionEx(&sInfo);
  29239. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  29240. }
  29241. return sqlite3_os_type==2;
  29242. }
  29243. #endif /* SQLITE_OS_WINCE */
  29244. /*
  29245. ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
  29246. **
  29247. ** Space to hold the returned string is obtained from malloc.
  29248. */
  29249. static WCHAR *utf8ToUnicode(const char *zFilename){
  29250. int nChar;
  29251. WCHAR *zWideFilename;
  29252. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  29253. zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
  29254. if( zWideFilename==0 ){
  29255. return 0;
  29256. }
  29257. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
  29258. if( nChar==0 ){
  29259. free(zWideFilename);
  29260. zWideFilename = 0;
  29261. }
  29262. return zWideFilename;
  29263. }
  29264. /*
  29265. ** Convert microsoft unicode to UTF-8. Space to hold the returned string is
  29266. ** obtained from malloc().
  29267. */
  29268. static char *unicodeToUtf8(const WCHAR *zWideFilename){
  29269. int nByte;
  29270. char *zFilename;
  29271. nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  29272. zFilename = malloc( nByte );
  29273. if( zFilename==0 ){
  29274. return 0;
  29275. }
  29276. nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  29277. 0, 0);
  29278. if( nByte == 0 ){
  29279. free(zFilename);
  29280. zFilename = 0;
  29281. }
  29282. return zFilename;
  29283. }
  29284. /*
  29285. ** Convert an ansi string to microsoft unicode, based on the
  29286. ** current codepage settings for file apis.
  29287. **
  29288. ** Space to hold the returned string is obtained
  29289. ** from malloc.
  29290. */
  29291. static WCHAR *mbcsToUnicode(const char *zFilename){
  29292. int nByte;
  29293. WCHAR *zMbcsFilename;
  29294. int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  29295. nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
  29296. zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
  29297. if( zMbcsFilename==0 ){
  29298. return 0;
  29299. }
  29300. nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
  29301. if( nByte==0 ){
  29302. free(zMbcsFilename);
  29303. zMbcsFilename = 0;
  29304. }
  29305. return zMbcsFilename;
  29306. }
  29307. /*
  29308. ** Convert microsoft unicode to multibyte character string, based on the
  29309. ** user's Ansi codepage.
  29310. **
  29311. ** Space to hold the returned string is obtained from
  29312. ** malloc().
  29313. */
  29314. static char *unicodeToMbcs(const WCHAR *zWideFilename){
  29315. int nByte;
  29316. char *zFilename;
  29317. int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
  29318. nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  29319. zFilename = malloc( nByte );
  29320. if( zFilename==0 ){
  29321. return 0;
  29322. }
  29323. nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
  29324. 0, 0);
  29325. if( nByte == 0 ){
  29326. free(zFilename);
  29327. zFilename = 0;
  29328. }
  29329. return zFilename;
  29330. }
  29331. /*
  29332. ** Convert multibyte character string to UTF-8. Space to hold the
  29333. ** returned string is obtained from malloc().
  29334. */
  29335. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  29336. char *zFilenameUtf8;
  29337. WCHAR *zTmpWide;
  29338. zTmpWide = mbcsToUnicode(zFilename);
  29339. if( zTmpWide==0 ){
  29340. return 0;
  29341. }
  29342. zFilenameUtf8 = unicodeToUtf8(zTmpWide);
  29343. free(zTmpWide);
  29344. return zFilenameUtf8;
  29345. }
  29346. /*
  29347. ** Convert UTF-8 to multibyte character string. Space to hold the
  29348. ** returned string is obtained from malloc().
  29349. */
  29350. static char *utf8ToMbcs(const char *zFilename){
  29351. char *zFilenameMbcs;
  29352. WCHAR *zTmpWide;
  29353. zTmpWide = utf8ToUnicode(zFilename);
  29354. if( zTmpWide==0 ){
  29355. return 0;
  29356. }
  29357. zFilenameMbcs = unicodeToMbcs(zTmpWide);
  29358. free(zTmpWide);
  29359. return zFilenameMbcs;
  29360. }
  29361. #if SQLITE_OS_WINCE
  29362. /*************************************************************************
  29363. ** This section contains code for WinCE only.
  29364. */
  29365. /*
  29366. ** WindowsCE does not have a localtime() function. So create a
  29367. ** substitute.
  29368. */
  29369. struct tm *__cdecl localtime(const time_t *t)
  29370. {
  29371. static struct tm y;
  29372. FILETIME uTm, lTm;
  29373. SYSTEMTIME pTm;
  29374. sqlite3_int64 t64;
  29375. t64 = *t;
  29376. t64 = (t64 + 11644473600)*10000000;
  29377. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  29378. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  29379. FileTimeToLocalFileTime(&uTm,&lTm);
  29380. FileTimeToSystemTime(&lTm,&pTm);
  29381. y.tm_year = pTm.wYear - 1900;
  29382. y.tm_mon = pTm.wMonth - 1;
  29383. y.tm_wday = pTm.wDayOfWeek;
  29384. y.tm_mday = pTm.wDay;
  29385. y.tm_hour = pTm.wHour;
  29386. y.tm_min = pTm.wMinute;
  29387. y.tm_sec = pTm.wSecond;
  29388. return &y;
  29389. }
  29390. /* This will never be called, but defined to make the code compile */
  29391. #define GetTempPathA(a,b)
  29392. #define LockFile(a,b,c,d,e) winceLockFile(&a, b, c, d, e)
  29393. #define UnlockFile(a,b,c,d,e) winceUnlockFile(&a, b, c, d, e)
  29394. #define LockFileEx(a,b,c,d,e,f) winceLockFileEx(&a, b, c, d, e, f)
  29395. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  29396. /*
  29397. ** Acquire a lock on the handle h
  29398. */
  29399. static void winceMutexAcquire(HANDLE h){
  29400. DWORD dwErr;
  29401. do {
  29402. dwErr = WaitForSingleObject(h, INFINITE);
  29403. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  29404. }
  29405. /*
  29406. ** Release a lock acquired by winceMutexAcquire()
  29407. */
  29408. #define winceMutexRelease(h) ReleaseMutex(h)
  29409. /*
  29410. ** Create the mutex and shared memory used for locking in the file
  29411. ** descriptor pFile
  29412. */
  29413. static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
  29414. WCHAR *zTok;
  29415. WCHAR *zName = utf8ToUnicode(zFilename);
  29416. BOOL bInit = TRUE;
  29417. /* Initialize the local lockdata */
  29418. ZeroMemory(&pFile->local, sizeof(pFile->local));
  29419. /* Replace the backslashes from the filename and lowercase it
  29420. ** to derive a mutex name. */
  29421. zTok = CharLowerW(zName);
  29422. for (;*zTok;zTok++){
  29423. if (*zTok == '\\') *zTok = '_';
  29424. }
  29425. /* Create/open the named mutex */
  29426. pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
  29427. if (!pFile->hMutex){
  29428. pFile->lastErrno = GetLastError();
  29429. free(zName);
  29430. return FALSE;
  29431. }
  29432. /* Acquire the mutex before continuing */
  29433. winceMutexAcquire(pFile->hMutex);
  29434. /* Since the names of named mutexes, semaphores, file mappings etc are
  29435. ** case-sensitive, take advantage of that by uppercasing the mutex name
  29436. ** and using that as the shared filemapping name.
  29437. */
  29438. CharUpperW(zName);
  29439. pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  29440. PAGE_READWRITE, 0, sizeof(winceLock),
  29441. zName);
  29442. /* Set a flag that indicates we're the first to create the memory so it
  29443. ** must be zero-initialized */
  29444. if (GetLastError() == ERROR_ALREADY_EXISTS){
  29445. bInit = FALSE;
  29446. }
  29447. free(zName);
  29448. /* If we succeeded in making the shared memory handle, map it. */
  29449. if (pFile->hShared){
  29450. pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
  29451. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  29452. /* If mapping failed, close the shared memory handle and erase it */
  29453. if (!pFile->shared){
  29454. pFile->lastErrno = GetLastError();
  29455. CloseHandle(pFile->hShared);
  29456. pFile->hShared = NULL;
  29457. }
  29458. }
  29459. /* If shared memory could not be created, then close the mutex and fail */
  29460. if (pFile->hShared == NULL){
  29461. winceMutexRelease(pFile->hMutex);
  29462. CloseHandle(pFile->hMutex);
  29463. pFile->hMutex = NULL;
  29464. return FALSE;
  29465. }
  29466. /* Initialize the shared memory if we're supposed to */
  29467. if (bInit) {
  29468. ZeroMemory(pFile->shared, sizeof(winceLock));
  29469. }
  29470. winceMutexRelease(pFile->hMutex);
  29471. return TRUE;
  29472. }
  29473. /*
  29474. ** Destroy the part of winFile that deals with wince locks
  29475. */
  29476. static void winceDestroyLock(winFile *pFile){
  29477. if (pFile->hMutex){
  29478. /* Acquire the mutex */
  29479. winceMutexAcquire(pFile->hMutex);
  29480. /* The following blocks should probably assert in debug mode, but they
  29481. are to cleanup in case any locks remained open */
  29482. if (pFile->local.nReaders){
  29483. pFile->shared->nReaders --;
  29484. }
  29485. if (pFile->local.bReserved){
  29486. pFile->shared->bReserved = FALSE;
  29487. }
  29488. if (pFile->local.bPending){
  29489. pFile->shared->bPending = FALSE;
  29490. }
  29491. if (pFile->local.bExclusive){
  29492. pFile->shared->bExclusive = FALSE;
  29493. }
  29494. /* De-reference and close our copy of the shared memory handle */
  29495. UnmapViewOfFile(pFile->shared);
  29496. CloseHandle(pFile->hShared);
  29497. /* Done with the mutex */
  29498. winceMutexRelease(pFile->hMutex);
  29499. CloseHandle(pFile->hMutex);
  29500. pFile->hMutex = NULL;
  29501. }
  29502. }
  29503. /*
  29504. ** An implementation of the LockFile() API of windows for wince
  29505. */
  29506. static BOOL winceLockFile(
  29507. HANDLE *phFile,
  29508. DWORD dwFileOffsetLow,
  29509. DWORD dwFileOffsetHigh,
  29510. DWORD nNumberOfBytesToLockLow,
  29511. DWORD nNumberOfBytesToLockHigh
  29512. ){
  29513. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  29514. BOOL bReturn = FALSE;
  29515. UNUSED_PARAMETER(dwFileOffsetHigh);
  29516. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  29517. if (!pFile->hMutex) return TRUE;
  29518. winceMutexAcquire(pFile->hMutex);
  29519. /* Wanting an exclusive lock? */
  29520. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  29521. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  29522. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  29523. pFile->shared->bExclusive = TRUE;
  29524. pFile->local.bExclusive = TRUE;
  29525. bReturn = TRUE;
  29526. }
  29527. }
  29528. /* Want a read-only lock? */
  29529. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  29530. nNumberOfBytesToLockLow == 1){
  29531. if (pFile->shared->bExclusive == 0){
  29532. pFile->local.nReaders ++;
  29533. if (pFile->local.nReaders == 1){
  29534. pFile->shared->nReaders ++;
  29535. }
  29536. bReturn = TRUE;
  29537. }
  29538. }
  29539. /* Want a pending lock? */
  29540. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
  29541. /* If no pending lock has been acquired, then acquire it */
  29542. if (pFile->shared->bPending == 0) {
  29543. pFile->shared->bPending = TRUE;
  29544. pFile->local.bPending = TRUE;
  29545. bReturn = TRUE;
  29546. }
  29547. }
  29548. /* Want a reserved lock? */
  29549. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
  29550. if (pFile->shared->bReserved == 0) {
  29551. pFile->shared->bReserved = TRUE;
  29552. pFile->local.bReserved = TRUE;
  29553. bReturn = TRUE;
  29554. }
  29555. }
  29556. winceMutexRelease(pFile->hMutex);
  29557. return bReturn;
  29558. }
  29559. /*
  29560. ** An implementation of the UnlockFile API of windows for wince
  29561. */
  29562. static BOOL winceUnlockFile(
  29563. HANDLE *phFile,
  29564. DWORD dwFileOffsetLow,
  29565. DWORD dwFileOffsetHigh,
  29566. DWORD nNumberOfBytesToUnlockLow,
  29567. DWORD nNumberOfBytesToUnlockHigh
  29568. ){
  29569. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  29570. BOOL bReturn = FALSE;
  29571. UNUSED_PARAMETER(dwFileOffsetHigh);
  29572. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  29573. if (!pFile->hMutex) return TRUE;
  29574. winceMutexAcquire(pFile->hMutex);
  29575. /* Releasing a reader lock or an exclusive lock */
  29576. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  29577. /* Did we have an exclusive lock? */
  29578. if (pFile->local.bExclusive){
  29579. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  29580. pFile->local.bExclusive = FALSE;
  29581. pFile->shared->bExclusive = FALSE;
  29582. bReturn = TRUE;
  29583. }
  29584. /* Did we just have a reader lock? */
  29585. else if (pFile->local.nReaders){
  29586. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
  29587. pFile->local.nReaders --;
  29588. if (pFile->local.nReaders == 0)
  29589. {
  29590. pFile->shared->nReaders --;
  29591. }
  29592. bReturn = TRUE;
  29593. }
  29594. }
  29595. /* Releasing a pending lock */
  29596. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
  29597. if (pFile->local.bPending){
  29598. pFile->local.bPending = FALSE;
  29599. pFile->shared->bPending = FALSE;
  29600. bReturn = TRUE;
  29601. }
  29602. }
  29603. /* Releasing a reserved lock */
  29604. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
  29605. if (pFile->local.bReserved) {
  29606. pFile->local.bReserved = FALSE;
  29607. pFile->shared->bReserved = FALSE;
  29608. bReturn = TRUE;
  29609. }
  29610. }
  29611. winceMutexRelease(pFile->hMutex);
  29612. return bReturn;
  29613. }
  29614. /*
  29615. ** An implementation of the LockFileEx() API of windows for wince
  29616. */
  29617. static BOOL winceLockFileEx(
  29618. HANDLE *phFile,
  29619. DWORD dwFlags,
  29620. DWORD dwReserved,
  29621. DWORD nNumberOfBytesToLockLow,
  29622. DWORD nNumberOfBytesToLockHigh,
  29623. LPOVERLAPPED lpOverlapped
  29624. ){
  29625. UNUSED_PARAMETER(dwReserved);
  29626. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  29627. /* If the caller wants a shared read lock, forward this call
  29628. ** to winceLockFile */
  29629. if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
  29630. dwFlags == 1 &&
  29631. nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  29632. return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
  29633. }
  29634. return FALSE;
  29635. }
  29636. /*
  29637. ** End of the special code for wince
  29638. *****************************************************************************/
  29639. #endif /* SQLITE_OS_WINCE */
  29640. /*****************************************************************************
  29641. ** The next group of routines implement the I/O methods specified
  29642. ** by the sqlite3_io_methods object.
  29643. ******************************************************************************/
  29644. /*
  29645. ** Some microsoft compilers lack this definition.
  29646. */
  29647. #ifndef INVALID_SET_FILE_POINTER
  29648. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  29649. #endif
  29650. /*
  29651. ** Move the current position of the file handle passed as the first
  29652. ** argument to offset iOffset within the file. If successful, return 0.
  29653. ** Otherwise, set pFile->lastErrno and return non-zero.
  29654. */
  29655. static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
  29656. LONG upperBits; /* Most sig. 32 bits of new offset */
  29657. LONG lowerBits; /* Least sig. 32 bits of new offset */
  29658. DWORD dwRet; /* Value returned by SetFilePointer() */
  29659. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  29660. lowerBits = (LONG)(iOffset & 0xffffffff);
  29661. /* API oddity: If successful, SetFilePointer() returns a dword
  29662. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  29663. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  29664. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  29665. ** whether an error has actually occured, it is also necessary to call
  29666. ** GetLastError().
  29667. */
  29668. dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  29669. if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
  29670. pFile->lastErrno = GetLastError();
  29671. return 1;
  29672. }
  29673. return 0;
  29674. }
  29675. /*
  29676. ** Close a file.
  29677. **
  29678. ** It is reported that an attempt to close a handle might sometimes
  29679. ** fail. This is a very unreasonable result, but windows is notorious
  29680. ** for being unreasonable so I do not doubt that it might happen. If
  29681. ** the close fails, we pause for 100 milliseconds and try again. As
  29682. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  29683. ** giving up and returning an error.
  29684. */
  29685. #define MX_CLOSE_ATTEMPT 3
  29686. static int winClose(sqlite3_file *id){
  29687. int rc, cnt = 0;
  29688. winFile *pFile = (winFile*)id;
  29689. assert( id!=0 );
  29690. assert( pFile->pShm==0 );
  29691. OSTRACE(("CLOSE %d\n", pFile->h));
  29692. do{
  29693. rc = CloseHandle(pFile->h);
  29694. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  29695. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
  29696. #if SQLITE_OS_WINCE
  29697. #define WINCE_DELETION_ATTEMPTS 3
  29698. winceDestroyLock(pFile);
  29699. if( pFile->zDeleteOnClose ){
  29700. int cnt = 0;
  29701. while(
  29702. DeleteFileW(pFile->zDeleteOnClose)==0
  29703. && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  29704. && cnt++ < WINCE_DELETION_ATTEMPTS
  29705. ){
  29706. Sleep(100); /* Wait a little before trying again */
  29707. }
  29708. free(pFile->zDeleteOnClose);
  29709. }
  29710. #endif
  29711. OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
  29712. OpenCounter(-1);
  29713. return rc ? SQLITE_OK : SQLITE_IOERR;
  29714. }
  29715. /*
  29716. ** Read data from a file into a buffer. Return SQLITE_OK if all
  29717. ** bytes were read successfully and SQLITE_IOERR if anything goes
  29718. ** wrong.
  29719. */
  29720. static int winRead(
  29721. sqlite3_file *id, /* File to read from */
  29722. void *pBuf, /* Write content into this buffer */
  29723. int amt, /* Number of bytes to read */
  29724. sqlite3_int64 offset /* Begin reading at this offset */
  29725. ){
  29726. winFile *pFile = (winFile*)id; /* file handle */
  29727. DWORD nRead; /* Number of bytes actually read from file */
  29728. assert( id!=0 );
  29729. SimulateIOError(return SQLITE_IOERR_READ);
  29730. OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
  29731. if( seekWinFile(pFile, offset) ){
  29732. return SQLITE_FULL;
  29733. }
  29734. if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  29735. pFile->lastErrno = GetLastError();
  29736. return SQLITE_IOERR_READ;
  29737. }
  29738. if( nRead<(DWORD)amt ){
  29739. /* Unread parts of the buffer must be zero-filled */
  29740. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  29741. return SQLITE_IOERR_SHORT_READ;
  29742. }
  29743. return SQLITE_OK;
  29744. }
  29745. /*
  29746. ** Write data from a buffer into a file. Return SQLITE_OK on success
  29747. ** or some other error code on failure.
  29748. */
  29749. static int winWrite(
  29750. sqlite3_file *id, /* File to write into */
  29751. const void *pBuf, /* The bytes to be written */
  29752. int amt, /* Number of bytes to write */
  29753. sqlite3_int64 offset /* Offset into the file to begin writing at */
  29754. ){
  29755. int rc; /* True if error has occured, else false */
  29756. winFile *pFile = (winFile*)id; /* File handle */
  29757. assert( amt>0 );
  29758. assert( pFile );
  29759. SimulateIOError(return SQLITE_IOERR_WRITE);
  29760. SimulateDiskfullError(return SQLITE_FULL);
  29761. OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
  29762. rc = seekWinFile(pFile, offset);
  29763. if( rc==0 ){
  29764. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  29765. int nRem = amt; /* Number of bytes yet to be written */
  29766. DWORD nWrite; /* Bytes written by each WriteFile() call */
  29767. while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
  29768. aRem += nWrite;
  29769. nRem -= nWrite;
  29770. }
  29771. if( nRem>0 ){
  29772. pFile->lastErrno = GetLastError();
  29773. rc = 1;
  29774. }
  29775. }
  29776. if( rc ){
  29777. if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
  29778. return SQLITE_FULL;
  29779. }
  29780. return SQLITE_IOERR_WRITE;
  29781. }
  29782. return SQLITE_OK;
  29783. }
  29784. /*
  29785. ** Truncate an open file to a specified size
  29786. */
  29787. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  29788. winFile *pFile = (winFile*)id; /* File handle object */
  29789. int rc = SQLITE_OK; /* Return code for this function */
  29790. assert( pFile );
  29791. OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
  29792. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  29793. /* If the user has configured a chunk-size for this file, truncate the
  29794. ** file so that it consists of an integer number of chunks (i.e. the
  29795. ** actual file size after the operation may be larger than the requested
  29796. ** size).
  29797. */
  29798. if( pFile->szChunk ){
  29799. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  29800. }
  29801. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  29802. if( seekWinFile(pFile, nByte) ){
  29803. rc = SQLITE_IOERR_TRUNCATE;
  29804. }else if( 0==SetEndOfFile(pFile->h) ){
  29805. pFile->lastErrno = GetLastError();
  29806. rc = SQLITE_IOERR_TRUNCATE;
  29807. }
  29808. OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
  29809. return rc;
  29810. }
  29811. #ifdef SQLITE_TEST
  29812. /*
  29813. ** Count the number of fullsyncs and normal syncs. This is used to test
  29814. ** that syncs and fullsyncs are occuring at the right times.
  29815. */
  29816. SQLITE_API int sqlite3_sync_count = 0;
  29817. SQLITE_API int sqlite3_fullsync_count = 0;
  29818. #endif
  29819. /*
  29820. ** Make sure all writes to a particular file are committed to disk.
  29821. */
  29822. static int winSync(sqlite3_file *id, int flags){
  29823. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
  29824. winFile *pFile = (winFile*)id;
  29825. #else
  29826. UNUSED_PARAMETER(id);
  29827. #endif
  29828. assert( pFile );
  29829. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  29830. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  29831. || (flags&0x0F)==SQLITE_SYNC_FULL
  29832. );
  29833. OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
  29834. #ifndef SQLITE_TEST
  29835. UNUSED_PARAMETER(flags);
  29836. #else
  29837. if( flags & SQLITE_SYNC_FULL ){
  29838. sqlite3_fullsync_count++;
  29839. }
  29840. sqlite3_sync_count++;
  29841. #endif
  29842. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  29843. ** line is to test that doing so does not cause any problems.
  29844. */
  29845. SimulateDiskfullError( return SQLITE_FULL );
  29846. SimulateIOError( return SQLITE_IOERR; );
  29847. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  29848. ** no-op
  29849. */
  29850. #ifdef SQLITE_NO_SYNC
  29851. return SQLITE_OK;
  29852. #else
  29853. if( FlushFileBuffers(pFile->h) ){
  29854. return SQLITE_OK;
  29855. }else{
  29856. pFile->lastErrno = GetLastError();
  29857. return SQLITE_IOERR;
  29858. }
  29859. #endif
  29860. }
  29861. /*
  29862. ** Determine the current size of a file in bytes
  29863. */
  29864. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  29865. DWORD upperBits;
  29866. DWORD lowerBits;
  29867. winFile *pFile = (winFile*)id;
  29868. DWORD error;
  29869. assert( id!=0 );
  29870. SimulateIOError(return SQLITE_IOERR_FSTAT);
  29871. lowerBits = GetFileSize(pFile->h, &upperBits);
  29872. if( (lowerBits == INVALID_FILE_SIZE)
  29873. && ((error = GetLastError()) != NO_ERROR) )
  29874. {
  29875. pFile->lastErrno = error;
  29876. return SQLITE_IOERR_FSTAT;
  29877. }
  29878. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  29879. return SQLITE_OK;
  29880. }
  29881. /*
  29882. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  29883. */
  29884. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  29885. # define LOCKFILE_FAIL_IMMEDIATELY 1
  29886. #endif
  29887. /*
  29888. ** Acquire a reader lock.
  29889. ** Different API routines are called depending on whether or not this
  29890. ** is Win95 or WinNT.
  29891. */
  29892. static int getReadLock(winFile *pFile){
  29893. int res;
  29894. if( isNT() ){
  29895. OVERLAPPED ovlp;
  29896. ovlp.Offset = SHARED_FIRST;
  29897. ovlp.OffsetHigh = 0;
  29898. ovlp.hEvent = 0;
  29899. res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
  29900. 0, SHARED_SIZE, 0, &ovlp);
  29901. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  29902. */
  29903. #if SQLITE_OS_WINCE==0
  29904. }else{
  29905. int lk;
  29906. sqlite3_randomness(sizeof(lk), &lk);
  29907. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  29908. res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  29909. #endif
  29910. }
  29911. if( res == 0 ){
  29912. pFile->lastErrno = GetLastError();
  29913. }
  29914. return res;
  29915. }
  29916. /*
  29917. ** Undo a readlock
  29918. */
  29919. static int unlockReadLock(winFile *pFile){
  29920. int res;
  29921. if( isNT() ){
  29922. res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  29923. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  29924. */
  29925. #if SQLITE_OS_WINCE==0
  29926. }else{
  29927. res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
  29928. #endif
  29929. }
  29930. if( res == 0 ){
  29931. pFile->lastErrno = GetLastError();
  29932. }
  29933. return res;
  29934. }
  29935. /*
  29936. ** Lock the file with the lock specified by parameter locktype - one
  29937. ** of the following:
  29938. **
  29939. ** (1) SHARED_LOCK
  29940. ** (2) RESERVED_LOCK
  29941. ** (3) PENDING_LOCK
  29942. ** (4) EXCLUSIVE_LOCK
  29943. **
  29944. ** Sometimes when requesting one lock state, additional lock states
  29945. ** are inserted in between. The locking might fail on one of the later
  29946. ** transitions leaving the lock state different from what it started but
  29947. ** still short of its goal. The following chart shows the allowed
  29948. ** transitions and the inserted intermediate states:
  29949. **
  29950. ** UNLOCKED -> SHARED
  29951. ** SHARED -> RESERVED
  29952. ** SHARED -> (PENDING) -> EXCLUSIVE
  29953. ** RESERVED -> (PENDING) -> EXCLUSIVE
  29954. ** PENDING -> EXCLUSIVE
  29955. **
  29956. ** This routine will only increase a lock. The winUnlock() routine
  29957. ** erases all locks at once and returns us immediately to locking level 0.
  29958. ** It is not possible to lower the locking level one step at a time. You
  29959. ** must go straight to locking level 0.
  29960. */
  29961. static int winLock(sqlite3_file *id, int locktype){
  29962. int rc = SQLITE_OK; /* Return code from subroutines */
  29963. int res = 1; /* Result of a windows lock call */
  29964. int newLocktype; /* Set pFile->locktype to this value before exiting */
  29965. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  29966. winFile *pFile = (winFile*)id;
  29967. DWORD error = NO_ERROR;
  29968. assert( id!=0 );
  29969. OSTRACE(("LOCK %d %d was %d(%d)\n",
  29970. pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
  29971. /* If there is already a lock of this type or more restrictive on the
  29972. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  29973. ** sqlite3OsEnterMutex() hasn't been called yet.
  29974. */
  29975. if( pFile->locktype>=locktype ){
  29976. return SQLITE_OK;
  29977. }
  29978. /* Make sure the locking sequence is correct
  29979. */
  29980. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  29981. assert( locktype!=PENDING_LOCK );
  29982. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  29983. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  29984. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  29985. ** the PENDING_LOCK byte is temporary.
  29986. */
  29987. newLocktype = pFile->locktype;
  29988. if( (pFile->locktype==NO_LOCK)
  29989. || ( (locktype==EXCLUSIVE_LOCK)
  29990. && (pFile->locktype==RESERVED_LOCK))
  29991. ){
  29992. int cnt = 3;
  29993. while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
  29994. /* Try 3 times to get the pending lock. The pending lock might be
  29995. ** held by another reader process who will release it momentarily.
  29996. */
  29997. OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
  29998. Sleep(1);
  29999. }
  30000. gotPendingLock = res;
  30001. if( !res ){
  30002. error = GetLastError();
  30003. }
  30004. }
  30005. /* Acquire a shared lock
  30006. */
  30007. if( locktype==SHARED_LOCK && res ){
  30008. assert( pFile->locktype==NO_LOCK );
  30009. res = getReadLock(pFile);
  30010. if( res ){
  30011. newLocktype = SHARED_LOCK;
  30012. }else{
  30013. error = GetLastError();
  30014. }
  30015. }
  30016. /* Acquire a RESERVED lock
  30017. */
  30018. if( locktype==RESERVED_LOCK && res ){
  30019. assert( pFile->locktype==SHARED_LOCK );
  30020. res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  30021. if( res ){
  30022. newLocktype = RESERVED_LOCK;
  30023. }else{
  30024. error = GetLastError();
  30025. }
  30026. }
  30027. /* Acquire a PENDING lock
  30028. */
  30029. if( locktype==EXCLUSIVE_LOCK && res ){
  30030. newLocktype = PENDING_LOCK;
  30031. gotPendingLock = 0;
  30032. }
  30033. /* Acquire an EXCLUSIVE lock
  30034. */
  30035. if( locktype==EXCLUSIVE_LOCK && res ){
  30036. assert( pFile->locktype>=SHARED_LOCK );
  30037. res = unlockReadLock(pFile);
  30038. OSTRACE(("unreadlock = %d\n", res));
  30039. res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  30040. if( res ){
  30041. newLocktype = EXCLUSIVE_LOCK;
  30042. }else{
  30043. error = GetLastError();
  30044. OSTRACE(("error-code = %d\n", error));
  30045. getReadLock(pFile);
  30046. }
  30047. }
  30048. /* If we are holding a PENDING lock that ought to be released, then
  30049. ** release it now.
  30050. */
  30051. if( gotPendingLock && locktype==SHARED_LOCK ){
  30052. UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  30053. }
  30054. /* Update the state of the lock has held in the file descriptor then
  30055. ** return the appropriate result code.
  30056. */
  30057. if( res ){
  30058. rc = SQLITE_OK;
  30059. }else{
  30060. OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  30061. locktype, newLocktype));
  30062. pFile->lastErrno = error;
  30063. rc = SQLITE_BUSY;
  30064. }
  30065. pFile->locktype = (u8)newLocktype;
  30066. return rc;
  30067. }
  30068. /*
  30069. ** This routine checks if there is a RESERVED lock held on the specified
  30070. ** file by this or any other process. If such a lock is held, return
  30071. ** non-zero, otherwise zero.
  30072. */
  30073. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  30074. int rc;
  30075. winFile *pFile = (winFile*)id;
  30076. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30077. assert( id!=0 );
  30078. if( pFile->locktype>=RESERVED_LOCK ){
  30079. rc = 1;
  30080. OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
  30081. }else{
  30082. rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  30083. if( rc ){
  30084. UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  30085. }
  30086. rc = !rc;
  30087. OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
  30088. }
  30089. *pResOut = rc;
  30090. return SQLITE_OK;
  30091. }
  30092. /*
  30093. ** Lower the locking level on file descriptor id to locktype. locktype
  30094. ** must be either NO_LOCK or SHARED_LOCK.
  30095. **
  30096. ** If the locking level of the file descriptor is already at or below
  30097. ** the requested locking level, this routine is a no-op.
  30098. **
  30099. ** It is not possible for this routine to fail if the second argument
  30100. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  30101. ** might return SQLITE_IOERR;
  30102. */
  30103. static int winUnlock(sqlite3_file *id, int locktype){
  30104. int type;
  30105. winFile *pFile = (winFile*)id;
  30106. int rc = SQLITE_OK;
  30107. assert( pFile!=0 );
  30108. assert( locktype<=SHARED_LOCK );
  30109. OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
  30110. pFile->locktype, pFile->sharedLockByte));
  30111. type = pFile->locktype;
  30112. if( type>=EXCLUSIVE_LOCK ){
  30113. UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  30114. if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
  30115. /* This should never happen. We should always be able to
  30116. ** reacquire the read lock */
  30117. rc = SQLITE_IOERR_UNLOCK;
  30118. }
  30119. }
  30120. if( type>=RESERVED_LOCK ){
  30121. UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  30122. }
  30123. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  30124. unlockReadLock(pFile);
  30125. }
  30126. if( type>=PENDING_LOCK ){
  30127. UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  30128. }
  30129. pFile->locktype = (u8)locktype;
  30130. return rc;
  30131. }
  30132. /*
  30133. ** Control and query of the open file handle.
  30134. */
  30135. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  30136. switch( op ){
  30137. case SQLITE_FCNTL_LOCKSTATE: {
  30138. *(int*)pArg = ((winFile*)id)->locktype;
  30139. return SQLITE_OK;
  30140. }
  30141. case SQLITE_LAST_ERRNO: {
  30142. *(int*)pArg = (int)((winFile*)id)->lastErrno;
  30143. return SQLITE_OK;
  30144. }
  30145. case SQLITE_FCNTL_CHUNK_SIZE: {
  30146. ((winFile*)id)->szChunk = *(int *)pArg;
  30147. return SQLITE_OK;
  30148. }
  30149. case SQLITE_FCNTL_SIZE_HINT: {
  30150. sqlite3_int64 sz = *(sqlite3_int64*)pArg;
  30151. SimulateIOErrorBenign(1);
  30152. winTruncate(id, sz);
  30153. SimulateIOErrorBenign(0);
  30154. return SQLITE_OK;
  30155. }
  30156. case SQLITE_FCNTL_SYNC_OMITTED: {
  30157. return SQLITE_OK;
  30158. }
  30159. }
  30160. return SQLITE_NOTFOUND;
  30161. }
  30162. /*
  30163. ** Return the sector size in bytes of the underlying block device for
  30164. ** the specified file. This is almost always 512 bytes, but may be
  30165. ** larger for some devices.
  30166. **
  30167. ** SQLite code assumes this function cannot fail. It also assumes that
  30168. ** if two files are created in the same file-system directory (i.e.
  30169. ** a database and its journal file) that the sector size will be the
  30170. ** same for both.
  30171. */
  30172. static int winSectorSize(sqlite3_file *id){
  30173. assert( id!=0 );
  30174. return (int)(((winFile*)id)->sectorSize);
  30175. }
  30176. /*
  30177. ** Return a vector of device characteristics.
  30178. */
  30179. static int winDeviceCharacteristics(sqlite3_file *id){
  30180. UNUSED_PARAMETER(id);
  30181. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
  30182. }
  30183. #ifndef SQLITE_OMIT_WAL
  30184. /*
  30185. ** Windows will only let you create file view mappings
  30186. ** on allocation size granularity boundaries.
  30187. ** During sqlite3_os_init() we do a GetSystemInfo()
  30188. ** to get the granularity size.
  30189. */
  30190. SYSTEM_INFO winSysInfo;
  30191. /*
  30192. ** Helper functions to obtain and relinquish the global mutex. The
  30193. ** global mutex is used to protect the winLockInfo objects used by
  30194. ** this file, all of which may be shared by multiple threads.
  30195. **
  30196. ** Function winShmMutexHeld() is used to assert() that the global mutex
  30197. ** is held when required. This function is only used as part of assert()
  30198. ** statements. e.g.
  30199. **
  30200. ** winShmEnterMutex()
  30201. ** assert( winShmMutexHeld() );
  30202. ** winShmLeaveMutex()
  30203. */
  30204. static void winShmEnterMutex(void){
  30205. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  30206. }
  30207. static void winShmLeaveMutex(void){
  30208. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  30209. }
  30210. #ifdef SQLITE_DEBUG
  30211. static int winShmMutexHeld(void) {
  30212. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  30213. }
  30214. #endif
  30215. /*
  30216. ** Object used to represent a single file opened and mmapped to provide
  30217. ** shared memory. When multiple threads all reference the same
  30218. ** log-summary, each thread has its own winFile object, but they all
  30219. ** point to a single instance of this object. In other words, each
  30220. ** log-summary is opened only once per process.
  30221. **
  30222. ** winShmMutexHeld() must be true when creating or destroying
  30223. ** this object or while reading or writing the following fields:
  30224. **
  30225. ** nRef
  30226. ** pNext
  30227. **
  30228. ** The following fields are read-only after the object is created:
  30229. **
  30230. ** fid
  30231. ** zFilename
  30232. **
  30233. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  30234. ** winShmMutexHeld() is true when reading or writing any other field
  30235. ** in this structure.
  30236. **
  30237. */
  30238. struct winShmNode {
  30239. sqlite3_mutex *mutex; /* Mutex to access this object */
  30240. char *zFilename; /* Name of the file */
  30241. winFile hFile; /* File handle from winOpen */
  30242. int szRegion; /* Size of shared-memory regions */
  30243. int nRegion; /* Size of array apRegion */
  30244. struct ShmRegion {
  30245. HANDLE hMap; /* File handle from CreateFileMapping */
  30246. void *pMap;
  30247. } *aRegion;
  30248. DWORD lastErrno; /* The Windows errno from the last I/O error */
  30249. int nRef; /* Number of winShm objects pointing to this */
  30250. winShm *pFirst; /* All winShm objects pointing to this */
  30251. winShmNode *pNext; /* Next in list of all winShmNode objects */
  30252. #ifdef SQLITE_DEBUG
  30253. u8 nextShmId; /* Next available winShm.id value */
  30254. #endif
  30255. };
  30256. /*
  30257. ** A global array of all winShmNode objects.
  30258. **
  30259. ** The winShmMutexHeld() must be true while reading or writing this list.
  30260. */
  30261. static winShmNode *winShmNodeList = 0;
  30262. /*
  30263. ** Structure used internally by this VFS to record the state of an
  30264. ** open shared memory connection.
  30265. **
  30266. ** The following fields are initialized when this object is created and
  30267. ** are read-only thereafter:
  30268. **
  30269. ** winShm.pShmNode
  30270. ** winShm.id
  30271. **
  30272. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  30273. ** while accessing any read/write fields.
  30274. */
  30275. struct winShm {
  30276. winShmNode *pShmNode; /* The underlying winShmNode object */
  30277. winShm *pNext; /* Next winShm with the same winShmNode */
  30278. u8 hasMutex; /* True if holding the winShmNode mutex */
  30279. u16 sharedMask; /* Mask of shared locks held */
  30280. u16 exclMask; /* Mask of exclusive locks held */
  30281. #ifdef SQLITE_DEBUG
  30282. u8 id; /* Id of this connection with its winShmNode */
  30283. #endif
  30284. };
  30285. /*
  30286. ** Constants used for locking
  30287. */
  30288. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  30289. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  30290. /*
  30291. ** Apply advisory locks for all n bytes beginning at ofst.
  30292. */
  30293. #define _SHM_UNLCK 1
  30294. #define _SHM_RDLCK 2
  30295. #define _SHM_WRLCK 3
  30296. static int winShmSystemLock(
  30297. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  30298. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  30299. int ofst, /* Offset to first byte to be locked/unlocked */
  30300. int nByte /* Number of bytes to lock or unlock */
  30301. ){
  30302. OVERLAPPED ovlp;
  30303. DWORD dwFlags;
  30304. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  30305. /* Access to the winShmNode object is serialized by the caller */
  30306. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  30307. /* Initialize the locking parameters */
  30308. dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  30309. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  30310. memset(&ovlp, 0, sizeof(OVERLAPPED));
  30311. ovlp.Offset = ofst;
  30312. /* Release/Acquire the system-level lock */
  30313. if( lockType==_SHM_UNLCK ){
  30314. rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
  30315. }else{
  30316. rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
  30317. }
  30318. if( rc!= 0 ){
  30319. rc = SQLITE_OK;
  30320. }else{
  30321. pFile->lastErrno = GetLastError();
  30322. rc = SQLITE_BUSY;
  30323. }
  30324. OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
  30325. pFile->hFile.h,
  30326. rc==SQLITE_OK ? "ok" : "failed",
  30327. lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
  30328. pFile->lastErrno));
  30329. return rc;
  30330. }
  30331. /* Forward references to VFS methods */
  30332. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  30333. static int winDelete(sqlite3_vfs *,const char*,int);
  30334. /*
  30335. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  30336. **
  30337. ** This is not a VFS shared-memory method; it is a utility function called
  30338. ** by VFS shared-memory methods.
  30339. */
  30340. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  30341. winShmNode **pp;
  30342. winShmNode *p;
  30343. BOOL bRc;
  30344. assert( winShmMutexHeld() );
  30345. pp = &winShmNodeList;
  30346. while( (p = *pp)!=0 ){
  30347. if( p->nRef==0 ){
  30348. int i;
  30349. if( p->mutex ) sqlite3_mutex_free(p->mutex);
  30350. for(i=0; i<p->nRegion; i++){
  30351. bRc = UnmapViewOfFile(p->aRegion[i].pMap);
  30352. OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
  30353. (int)GetCurrentProcessId(), i,
  30354. bRc ? "ok" : "failed"));
  30355. bRc = CloseHandle(p->aRegion[i].hMap);
  30356. OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
  30357. (int)GetCurrentProcessId(), i,
  30358. bRc ? "ok" : "failed"));
  30359. }
  30360. if( p->hFile.h != INVALID_HANDLE_VALUE ){
  30361. SimulateIOErrorBenign(1);
  30362. winClose((sqlite3_file *)&p->hFile);
  30363. SimulateIOErrorBenign(0);
  30364. }
  30365. if( deleteFlag ){
  30366. SimulateIOErrorBenign(1);
  30367. winDelete(pVfs, p->zFilename, 0);
  30368. SimulateIOErrorBenign(0);
  30369. }
  30370. *pp = p->pNext;
  30371. sqlite3_free(p->aRegion);
  30372. sqlite3_free(p);
  30373. }else{
  30374. pp = &p->pNext;
  30375. }
  30376. }
  30377. }
  30378. /*
  30379. ** Open the shared-memory area associated with database file pDbFd.
  30380. **
  30381. ** When opening a new shared-memory file, if no other instances of that
  30382. ** file are currently open, in this process or in other processes, then
  30383. ** the file must be truncated to zero length or have its header cleared.
  30384. */
  30385. static int winOpenSharedMemory(winFile *pDbFd){
  30386. struct winShm *p; /* The connection to be opened */
  30387. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  30388. int rc; /* Result code */
  30389. struct winShmNode *pNew; /* Newly allocated winShmNode */
  30390. int nName; /* Size of zName in bytes */
  30391. assert( pDbFd->pShm==0 ); /* Not previously opened */
  30392. /* Allocate space for the new sqlite3_shm object. Also speculatively
  30393. ** allocate space for a new winShmNode and filename.
  30394. */
  30395. p = sqlite3_malloc( sizeof(*p) );
  30396. if( p==0 ) return SQLITE_NOMEM;
  30397. memset(p, 0, sizeof(*p));
  30398. nName = sqlite3Strlen30(pDbFd->zPath);
  30399. pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
  30400. if( pNew==0 ){
  30401. sqlite3_free(p);
  30402. return SQLITE_NOMEM;
  30403. }
  30404. memset(pNew, 0, sizeof(*pNew));
  30405. pNew->zFilename = (char*)&pNew[1];
  30406. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  30407. /* Look to see if there is an existing winShmNode that can be used.
  30408. ** If no matching winShmNode currently exists, create a new one.
  30409. */
  30410. winShmEnterMutex();
  30411. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  30412. /* TBD need to come up with better match here. Perhaps
  30413. ** use FILE_ID_BOTH_DIR_INFO Structure.
  30414. */
  30415. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  30416. }
  30417. if( pShmNode ){
  30418. sqlite3_free(pNew);
  30419. }else{
  30420. pShmNode = pNew;
  30421. pNew = 0;
  30422. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  30423. pShmNode->pNext = winShmNodeList;
  30424. winShmNodeList = pShmNode;
  30425. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  30426. if( pShmNode->mutex==0 ){
  30427. rc = SQLITE_NOMEM;
  30428. goto shm_open_err;
  30429. }
  30430. rc = winOpen(pDbFd->pVfs,
  30431. pShmNode->zFilename, /* Name of the file (UTF-8) */
  30432. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  30433. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
  30434. 0);
  30435. if( SQLITE_OK!=rc ){
  30436. rc = SQLITE_CANTOPEN_BKPT;
  30437. goto shm_open_err;
  30438. }
  30439. /* Check to see if another process is holding the dead-man switch.
  30440. ** If not, truncate the file to zero length.
  30441. */
  30442. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  30443. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  30444. if( rc!=SQLITE_OK ){
  30445. rc = SQLITE_IOERR_SHMOPEN;
  30446. }
  30447. }
  30448. if( rc==SQLITE_OK ){
  30449. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  30450. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  30451. }
  30452. if( rc ) goto shm_open_err;
  30453. }
  30454. /* Make the new connection a child of the winShmNode */
  30455. p->pShmNode = pShmNode;
  30456. #ifdef SQLITE_DEBUG
  30457. p->id = pShmNode->nextShmId++;
  30458. #endif
  30459. pShmNode->nRef++;
  30460. pDbFd->pShm = p;
  30461. winShmLeaveMutex();
  30462. /* The reference count on pShmNode has already been incremented under
  30463. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  30464. ** new (struct winShm) object to the pShmNode has been set. All that is
  30465. ** left to do is to link the new object into the linked list starting
  30466. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  30467. ** mutex.
  30468. */
  30469. sqlite3_mutex_enter(pShmNode->mutex);
  30470. p->pNext = pShmNode->pFirst;
  30471. pShmNode->pFirst = p;
  30472. sqlite3_mutex_leave(pShmNode->mutex);
  30473. return SQLITE_OK;
  30474. /* Jump here on any error */
  30475. shm_open_err:
  30476. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  30477. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  30478. sqlite3_free(p);
  30479. sqlite3_free(pNew);
  30480. winShmLeaveMutex();
  30481. return rc;
  30482. }
  30483. /*
  30484. ** Close a connection to shared-memory. Delete the underlying
  30485. ** storage if deleteFlag is true.
  30486. */
  30487. static int winShmUnmap(
  30488. sqlite3_file *fd, /* Database holding shared memory */
  30489. int deleteFlag /* Delete after closing if true */
  30490. ){
  30491. winFile *pDbFd; /* Database holding shared-memory */
  30492. winShm *p; /* The connection to be closed */
  30493. winShmNode *pShmNode; /* The underlying shared-memory file */
  30494. winShm **pp; /* For looping over sibling connections */
  30495. pDbFd = (winFile*)fd;
  30496. p = pDbFd->pShm;
  30497. if( p==0 ) return SQLITE_OK;
  30498. pShmNode = p->pShmNode;
  30499. /* Remove connection p from the set of connections associated
  30500. ** with pShmNode */
  30501. sqlite3_mutex_enter(pShmNode->mutex);
  30502. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  30503. *pp = p->pNext;
  30504. /* Free the connection p */
  30505. sqlite3_free(p);
  30506. pDbFd->pShm = 0;
  30507. sqlite3_mutex_leave(pShmNode->mutex);
  30508. /* If pShmNode->nRef has reached 0, then close the underlying
  30509. ** shared-memory file, too */
  30510. winShmEnterMutex();
  30511. assert( pShmNode->nRef>0 );
  30512. pShmNode->nRef--;
  30513. if( pShmNode->nRef==0 ){
  30514. winShmPurge(pDbFd->pVfs, deleteFlag);
  30515. }
  30516. winShmLeaveMutex();
  30517. return SQLITE_OK;
  30518. }
  30519. /*
  30520. ** Change the lock state for a shared-memory segment.
  30521. */
  30522. static int winShmLock(
  30523. sqlite3_file *fd, /* Database file holding the shared memory */
  30524. int ofst, /* First lock to acquire or release */
  30525. int n, /* Number of locks to acquire or release */
  30526. int flags /* What to do with the lock */
  30527. ){
  30528. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  30529. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  30530. winShm *pX; /* For looping over all siblings */
  30531. winShmNode *pShmNode = p->pShmNode;
  30532. int rc = SQLITE_OK; /* Result code */
  30533. u16 mask; /* Mask of locks to take or release */
  30534. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  30535. assert( n>=1 );
  30536. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  30537. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  30538. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  30539. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  30540. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  30541. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  30542. assert( n>1 || mask==(1<<ofst) );
  30543. sqlite3_mutex_enter(pShmNode->mutex);
  30544. if( flags & SQLITE_SHM_UNLOCK ){
  30545. u16 allMask = 0; /* Mask of locks held by siblings */
  30546. /* See if any siblings hold this same lock */
  30547. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  30548. if( pX==p ) continue;
  30549. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  30550. allMask |= pX->sharedMask;
  30551. }
  30552. /* Unlock the system-level locks */
  30553. if( (mask & allMask)==0 ){
  30554. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  30555. }else{
  30556. rc = SQLITE_OK;
  30557. }
  30558. /* Undo the local locks */
  30559. if( rc==SQLITE_OK ){
  30560. p->exclMask &= ~mask;
  30561. p->sharedMask &= ~mask;
  30562. }
  30563. }else if( flags & SQLITE_SHM_SHARED ){
  30564. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  30565. /* Find out which shared locks are already held by sibling connections.
  30566. ** If any sibling already holds an exclusive lock, go ahead and return
  30567. ** SQLITE_BUSY.
  30568. */
  30569. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  30570. if( (pX->exclMask & mask)!=0 ){
  30571. rc = SQLITE_BUSY;
  30572. break;
  30573. }
  30574. allShared |= pX->sharedMask;
  30575. }
  30576. /* Get shared locks at the system level, if necessary */
  30577. if( rc==SQLITE_OK ){
  30578. if( (allShared & mask)==0 ){
  30579. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  30580. }else{
  30581. rc = SQLITE_OK;
  30582. }
  30583. }
  30584. /* Get the local shared locks */
  30585. if( rc==SQLITE_OK ){
  30586. p->sharedMask |= mask;
  30587. }
  30588. }else{
  30589. /* Make sure no sibling connections hold locks that will block this
  30590. ** lock. If any do, return SQLITE_BUSY right away.
  30591. */
  30592. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  30593. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  30594. rc = SQLITE_BUSY;
  30595. break;
  30596. }
  30597. }
  30598. /* Get the exclusive locks at the system level. Then if successful
  30599. ** also mark the local connection as being locked.
  30600. */
  30601. if( rc==SQLITE_OK ){
  30602. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  30603. if( rc==SQLITE_OK ){
  30604. assert( (p->sharedMask & mask)==0 );
  30605. p->exclMask |= mask;
  30606. }
  30607. }
  30608. }
  30609. sqlite3_mutex_leave(pShmNode->mutex);
  30610. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
  30611. p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
  30612. rc ? "failed" : "ok"));
  30613. return rc;
  30614. }
  30615. /*
  30616. ** Implement a memory barrier or memory fence on shared memory.
  30617. **
  30618. ** All loads and stores begun before the barrier must complete before
  30619. ** any load or store begun after the barrier.
  30620. */
  30621. static void winShmBarrier(
  30622. sqlite3_file *fd /* Database holding the shared memory */
  30623. ){
  30624. UNUSED_PARAMETER(fd);
  30625. /* MemoryBarrier(); // does not work -- do not know why not */
  30626. winShmEnterMutex();
  30627. winShmLeaveMutex();
  30628. }
  30629. /*
  30630. ** This function is called to obtain a pointer to region iRegion of the
  30631. ** shared-memory associated with the database file fd. Shared-memory regions
  30632. ** are numbered starting from zero. Each shared-memory region is szRegion
  30633. ** bytes in size.
  30634. **
  30635. ** If an error occurs, an error code is returned and *pp is set to NULL.
  30636. **
  30637. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  30638. ** region has not been allocated (by any client, including one running in a
  30639. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  30640. ** isWrite is non-zero and the requested shared-memory region has not yet
  30641. ** been allocated, it is allocated by this function.
  30642. **
  30643. ** If the shared-memory region has already been allocated or is allocated by
  30644. ** this call as described above, then it is mapped into this processes
  30645. ** address space (if it is not already), *pp is set to point to the mapped
  30646. ** memory and SQLITE_OK returned.
  30647. */
  30648. static int winShmMap(
  30649. sqlite3_file *fd, /* Handle open on database file */
  30650. int iRegion, /* Region to retrieve */
  30651. int szRegion, /* Size of regions */
  30652. int isWrite, /* True to extend file if necessary */
  30653. void volatile **pp /* OUT: Mapped memory */
  30654. ){
  30655. winFile *pDbFd = (winFile*)fd;
  30656. winShm *p = pDbFd->pShm;
  30657. winShmNode *pShmNode;
  30658. int rc = SQLITE_OK;
  30659. if( !p ){
  30660. rc = winOpenSharedMemory(pDbFd);
  30661. if( rc!=SQLITE_OK ) return rc;
  30662. p = pDbFd->pShm;
  30663. }
  30664. pShmNode = p->pShmNode;
  30665. sqlite3_mutex_enter(pShmNode->mutex);
  30666. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  30667. if( pShmNode->nRegion<=iRegion ){
  30668. struct ShmRegion *apNew; /* New aRegion[] array */
  30669. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  30670. sqlite3_int64 sz; /* Current size of wal-index file */
  30671. pShmNode->szRegion = szRegion;
  30672. /* The requested region is not mapped into this processes address space.
  30673. ** Check to see if it has been allocated (i.e. if the wal-index file is
  30674. ** large enough to contain the requested region).
  30675. */
  30676. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  30677. if( rc!=SQLITE_OK ){
  30678. rc = SQLITE_IOERR_SHMSIZE;
  30679. goto shmpage_out;
  30680. }
  30681. if( sz<nByte ){
  30682. /* The requested memory region does not exist. If isWrite is set to
  30683. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  30684. **
  30685. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  30686. ** the requested memory region.
  30687. */
  30688. if( !isWrite ) goto shmpage_out;
  30689. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  30690. if( rc!=SQLITE_OK ){
  30691. rc = SQLITE_IOERR_SHMSIZE;
  30692. goto shmpage_out;
  30693. }
  30694. }
  30695. /* Map the requested memory region into this processes address space. */
  30696. apNew = (struct ShmRegion *)sqlite3_realloc(
  30697. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  30698. );
  30699. if( !apNew ){
  30700. rc = SQLITE_IOERR_NOMEM;
  30701. goto shmpage_out;
  30702. }
  30703. pShmNode->aRegion = apNew;
  30704. while( pShmNode->nRegion<=iRegion ){
  30705. HANDLE hMap; /* file-mapping handle */
  30706. void *pMap = 0; /* Mapped memory region */
  30707. hMap = CreateFileMapping(pShmNode->hFile.h,
  30708. NULL, PAGE_READWRITE, 0, nByte, NULL
  30709. );
  30710. OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
  30711. (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
  30712. hMap ? "ok" : "failed"));
  30713. if( hMap ){
  30714. int iOffset = pShmNode->nRegion*szRegion;
  30715. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  30716. pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  30717. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  30718. );
  30719. OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
  30720. (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
  30721. pMap ? "ok" : "failed"));
  30722. }
  30723. if( !pMap ){
  30724. pShmNode->lastErrno = GetLastError();
  30725. rc = SQLITE_IOERR;
  30726. if( hMap ) CloseHandle(hMap);
  30727. goto shmpage_out;
  30728. }
  30729. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  30730. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  30731. pShmNode->nRegion++;
  30732. }
  30733. }
  30734. shmpage_out:
  30735. if( pShmNode->nRegion>iRegion ){
  30736. int iOffset = iRegion*szRegion;
  30737. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  30738. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  30739. *pp = (void *)&p[iOffsetShift];
  30740. }else{
  30741. *pp = 0;
  30742. }
  30743. sqlite3_mutex_leave(pShmNode->mutex);
  30744. return rc;
  30745. }
  30746. #else
  30747. # define winShmMap 0
  30748. # define winShmLock 0
  30749. # define winShmBarrier 0
  30750. # define winShmUnmap 0
  30751. #endif /* #ifndef SQLITE_OMIT_WAL */
  30752. /*
  30753. ** Here ends the implementation of all sqlite3_file methods.
  30754. **
  30755. ********************** End sqlite3_file Methods *******************************
  30756. ******************************************************************************/
  30757. /*
  30758. ** This vector defines all the methods that can operate on an
  30759. ** sqlite3_file for win32.
  30760. */
  30761. static const sqlite3_io_methods winIoMethod = {
  30762. 2, /* iVersion */
  30763. winClose, /* xClose */
  30764. winRead, /* xRead */
  30765. winWrite, /* xWrite */
  30766. winTruncate, /* xTruncate */
  30767. winSync, /* xSync */
  30768. winFileSize, /* xFileSize */
  30769. winLock, /* xLock */
  30770. winUnlock, /* xUnlock */
  30771. winCheckReservedLock, /* xCheckReservedLock */
  30772. winFileControl, /* xFileControl */
  30773. winSectorSize, /* xSectorSize */
  30774. winDeviceCharacteristics, /* xDeviceCharacteristics */
  30775. winShmMap, /* xShmMap */
  30776. winShmLock, /* xShmLock */
  30777. winShmBarrier, /* xShmBarrier */
  30778. winShmUnmap /* xShmUnmap */
  30779. };
  30780. /****************************************************************************
  30781. **************************** sqlite3_vfs methods ****************************
  30782. **
  30783. ** This division contains the implementation of methods on the
  30784. ** sqlite3_vfs object.
  30785. */
  30786. /*
  30787. ** Convert a UTF-8 filename into whatever form the underlying
  30788. ** operating system wants filenames in. Space to hold the result
  30789. ** is obtained from malloc and must be freed by the calling
  30790. ** function.
  30791. */
  30792. static void *convertUtf8Filename(const char *zFilename){
  30793. void *zConverted = 0;
  30794. if( isNT() ){
  30795. zConverted = utf8ToUnicode(zFilename);
  30796. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  30797. */
  30798. #if SQLITE_OS_WINCE==0
  30799. }else{
  30800. zConverted = utf8ToMbcs(zFilename);
  30801. #endif
  30802. }
  30803. /* caller will handle out of memory */
  30804. return zConverted;
  30805. }
  30806. /*
  30807. ** Create a temporary file name in zBuf. zBuf must be big enough to
  30808. ** hold at pVfs->mxPathname characters.
  30809. */
  30810. static int getTempname(int nBuf, char *zBuf){
  30811. static char zChars[] =
  30812. "abcdefghijklmnopqrstuvwxyz"
  30813. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  30814. "0123456789";
  30815. size_t i, j;
  30816. char zTempPath[MAX_PATH+1];
  30817. /* It's odd to simulate an io-error here, but really this is just
  30818. ** using the io-error infrastructure to test that SQLite handles this
  30819. ** function failing.
  30820. */
  30821. SimulateIOError( return SQLITE_IOERR );
  30822. if( sqlite3_temp_directory ){
  30823. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
  30824. }else if( isNT() ){
  30825. char *zMulti;
  30826. WCHAR zWidePath[MAX_PATH];
  30827. GetTempPathW(MAX_PATH-30, zWidePath);
  30828. zMulti = unicodeToUtf8(zWidePath);
  30829. if( zMulti ){
  30830. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
  30831. free(zMulti);
  30832. }else{
  30833. return SQLITE_NOMEM;
  30834. }
  30835. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  30836. ** Since the ASCII version of these Windows API do not exist for WINCE,
  30837. ** it's important to not reference them for WINCE builds.
  30838. */
  30839. #if SQLITE_OS_WINCE==0
  30840. }else{
  30841. char *zUtf8;
  30842. char zMbcsPath[MAX_PATH];
  30843. GetTempPathA(MAX_PATH-30, zMbcsPath);
  30844. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  30845. if( zUtf8 ){
  30846. sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
  30847. free(zUtf8);
  30848. }else{
  30849. return SQLITE_NOMEM;
  30850. }
  30851. #endif
  30852. }
  30853. /* Check that the output buffer is large enough for the temporary file
  30854. ** name. If it is not, return SQLITE_ERROR.
  30855. */
  30856. if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
  30857. return SQLITE_ERROR;
  30858. }
  30859. for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
  30860. zTempPath[i] = 0;
  30861. sqlite3_snprintf(nBuf-17, zBuf,
  30862. "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
  30863. j = sqlite3Strlen30(zBuf);
  30864. sqlite3_randomness(15, &zBuf[j]);
  30865. for(i=0; i<15; i++, j++){
  30866. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  30867. }
  30868. zBuf[j] = 0;
  30869. OSTRACE(("TEMP FILENAME: %s\n", zBuf));
  30870. return SQLITE_OK;
  30871. }
  30872. /*
  30873. ** The return value of getLastErrorMsg
  30874. ** is zero if the error message fits in the buffer, or non-zero
  30875. ** otherwise (if the message was truncated).
  30876. */
  30877. static int getLastErrorMsg(int nBuf, char *zBuf){
  30878. /* FormatMessage returns 0 on failure. Otherwise it
  30879. ** returns the number of TCHARs written to the output
  30880. ** buffer, excluding the terminating null char.
  30881. */
  30882. DWORD error = GetLastError();
  30883. DWORD dwLen = 0;
  30884. char *zOut = 0;
  30885. if( isNT() ){
  30886. WCHAR *zTempWide = NULL;
  30887. dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  30888. NULL,
  30889. error,
  30890. 0,
  30891. (LPWSTR) &zTempWide,
  30892. 0,
  30893. 0);
  30894. if( dwLen > 0 ){
  30895. /* allocate a buffer and convert to UTF8 */
  30896. zOut = unicodeToUtf8(zTempWide);
  30897. /* free the system buffer allocated by FormatMessage */
  30898. LocalFree(zTempWide);
  30899. }
  30900. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  30901. ** Since the ASCII version of these Windows API do not exist for WINCE,
  30902. ** it's important to not reference them for WINCE builds.
  30903. */
  30904. #if SQLITE_OS_WINCE==0
  30905. }else{
  30906. char *zTemp = NULL;
  30907. dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  30908. NULL,
  30909. error,
  30910. 0,
  30911. (LPSTR) &zTemp,
  30912. 0,
  30913. 0);
  30914. if( dwLen > 0 ){
  30915. /* allocate a buffer and convert to UTF8 */
  30916. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  30917. /* free the system buffer allocated by FormatMessage */
  30918. LocalFree(zTemp);
  30919. }
  30920. #endif
  30921. }
  30922. if( 0 == dwLen ){
  30923. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
  30924. }else{
  30925. /* copy a maximum of nBuf chars to output buffer */
  30926. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  30927. /* free the UTF8 buffer */
  30928. free(zOut);
  30929. }
  30930. return 0;
  30931. }
  30932. /*
  30933. ** Open a file.
  30934. */
  30935. static int winOpen(
  30936. sqlite3_vfs *pVfs, /* Not used */
  30937. const char *zName, /* Name of the file (UTF-8) */
  30938. sqlite3_file *id, /* Write the SQLite file handle here */
  30939. int flags, /* Open mode flags */
  30940. int *pOutFlags /* Status return flags */
  30941. ){
  30942. HANDLE h;
  30943. DWORD dwDesiredAccess;
  30944. DWORD dwShareMode;
  30945. DWORD dwCreationDisposition;
  30946. DWORD dwFlagsAndAttributes = 0;
  30947. #if SQLITE_OS_WINCE
  30948. int isTemp = 0;
  30949. #endif
  30950. winFile *pFile = (winFile*)id;
  30951. void *zConverted; /* Filename in OS encoding */
  30952. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  30953. /* If argument zPath is a NULL pointer, this function is required to open
  30954. ** a temporary file. Use this buffer to store the file name in.
  30955. */
  30956. char zTmpname[MAX_PATH+1]; /* Buffer used to create temp filename */
  30957. int rc = SQLITE_OK; /* Function Return Code */
  30958. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  30959. int eType = flags&0xFFFFFF00; /* Type of file to open */
  30960. #endif
  30961. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  30962. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  30963. int isCreate = (flags & SQLITE_OPEN_CREATE);
  30964. #ifndef NDEBUG
  30965. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  30966. #endif
  30967. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  30968. #ifndef NDEBUG
  30969. int isOpenJournal = (isCreate && (
  30970. eType==SQLITE_OPEN_MASTER_JOURNAL
  30971. || eType==SQLITE_OPEN_MAIN_JOURNAL
  30972. || eType==SQLITE_OPEN_WAL
  30973. ));
  30974. #endif
  30975. /* Check the following statements are true:
  30976. **
  30977. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  30978. ** (b) if CREATE is set, then READWRITE must also be set, and
  30979. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  30980. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  30981. */
  30982. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  30983. assert(isCreate==0 || isReadWrite);
  30984. assert(isExclusive==0 || isCreate);
  30985. assert(isDelete==0 || isCreate);
  30986. /* The main DB, main journal, WAL file and master journal are never
  30987. ** automatically deleted. Nor are they ever temporary files. */
  30988. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  30989. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  30990. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  30991. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  30992. /* Assert that the upper layer has set one of the "file-type" flags. */
  30993. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  30994. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  30995. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  30996. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  30997. );
  30998. assert( id!=0 );
  30999. UNUSED_PARAMETER(pVfs);
  31000. pFile->h = INVALID_HANDLE_VALUE;
  31001. /* If the second argument to this function is NULL, generate a
  31002. ** temporary file name to use
  31003. */
  31004. if( !zUtf8Name ){
  31005. assert(isDelete && !isOpenJournal);
  31006. rc = getTempname(MAX_PATH+1, zTmpname);
  31007. if( rc!=SQLITE_OK ){
  31008. return rc;
  31009. }
  31010. zUtf8Name = zTmpname;
  31011. }
  31012. /* Convert the filename to the system encoding. */
  31013. zConverted = convertUtf8Filename(zUtf8Name);
  31014. if( zConverted==0 ){
  31015. return SQLITE_NOMEM;
  31016. }
  31017. if( isReadWrite ){
  31018. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  31019. }else{
  31020. dwDesiredAccess = GENERIC_READ;
  31021. }
  31022. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  31023. ** created. SQLite doesn't use it to indicate "exclusive access"
  31024. ** as it is usually understood.
  31025. */
  31026. if( isExclusive ){
  31027. /* Creates a new file, only if it does not already exist. */
  31028. /* If the file exists, it fails. */
  31029. dwCreationDisposition = CREATE_NEW;
  31030. }else if( isCreate ){
  31031. /* Open existing file, or create if it doesn't exist */
  31032. dwCreationDisposition = OPEN_ALWAYS;
  31033. }else{
  31034. /* Opens a file, only if it exists. */
  31035. dwCreationDisposition = OPEN_EXISTING;
  31036. }
  31037. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  31038. if( isDelete ){
  31039. #if SQLITE_OS_WINCE
  31040. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  31041. isTemp = 1;
  31042. #else
  31043. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  31044. | FILE_ATTRIBUTE_HIDDEN
  31045. | FILE_FLAG_DELETE_ON_CLOSE;
  31046. #endif
  31047. }else{
  31048. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  31049. }
  31050. /* Reports from the internet are that performance is always
  31051. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  31052. #if SQLITE_OS_WINCE
  31053. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  31054. #endif
  31055. if( isNT() ){
  31056. h = CreateFileW((WCHAR*)zConverted,
  31057. dwDesiredAccess,
  31058. dwShareMode,
  31059. NULL,
  31060. dwCreationDisposition,
  31061. dwFlagsAndAttributes,
  31062. NULL
  31063. );
  31064. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  31065. ** Since the ASCII version of these Windows API do not exist for WINCE,
  31066. ** it's important to not reference them for WINCE builds.
  31067. */
  31068. #if SQLITE_OS_WINCE==0
  31069. }else{
  31070. h = CreateFileA((char*)zConverted,
  31071. dwDesiredAccess,
  31072. dwShareMode,
  31073. NULL,
  31074. dwCreationDisposition,
  31075. dwFlagsAndAttributes,
  31076. NULL
  31077. );
  31078. #endif
  31079. }
  31080. OSTRACE(("OPEN %d %s 0x%lx %s\n",
  31081. h, zName, dwDesiredAccess,
  31082. h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
  31083. if( h==INVALID_HANDLE_VALUE ){
  31084. pFile->lastErrno = GetLastError();
  31085. free(zConverted);
  31086. if( isReadWrite ){
  31087. return winOpen(pVfs, zName, id,
  31088. ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
  31089. }else{
  31090. return SQLITE_CANTOPEN_BKPT;
  31091. }
  31092. }
  31093. if( pOutFlags ){
  31094. if( isReadWrite ){
  31095. *pOutFlags = SQLITE_OPEN_READWRITE;
  31096. }else{
  31097. *pOutFlags = SQLITE_OPEN_READONLY;
  31098. }
  31099. }
  31100. memset(pFile, 0, sizeof(*pFile));
  31101. pFile->pMethod = &winIoMethod;
  31102. pFile->h = h;
  31103. pFile->lastErrno = NO_ERROR;
  31104. pFile->pVfs = pVfs;
  31105. pFile->pShm = 0;
  31106. pFile->zPath = zName;
  31107. pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
  31108. #if SQLITE_OS_WINCE
  31109. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  31110. && !winceCreateLock(zName, pFile)
  31111. ){
  31112. CloseHandle(h);
  31113. free(zConverted);
  31114. return SQLITE_CANTOPEN_BKPT;
  31115. }
  31116. if( isTemp ){
  31117. pFile->zDeleteOnClose = zConverted;
  31118. }else
  31119. #endif
  31120. {
  31121. free(zConverted);
  31122. }
  31123. OpenCounter(+1);
  31124. return rc;
  31125. }
  31126. /*
  31127. ** Delete the named file.
  31128. **
  31129. ** Note that windows does not allow a file to be deleted if some other
  31130. ** process has it open. Sometimes a virus scanner or indexing program
  31131. ** will open a journal file shortly after it is created in order to do
  31132. ** whatever it does. While this other process is holding the
  31133. ** file open, we will be unable to delete it. To work around this
  31134. ** problem, we delay 100 milliseconds and try to delete again. Up
  31135. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  31136. ** up and returning an error.
  31137. */
  31138. #define MX_DELETION_ATTEMPTS 5
  31139. static int winDelete(
  31140. sqlite3_vfs *pVfs, /* Not used on win32 */
  31141. const char *zFilename, /* Name of file to delete */
  31142. int syncDir /* Not used on win32 */
  31143. ){
  31144. int cnt = 0;
  31145. DWORD rc;
  31146. DWORD error = 0;
  31147. void *zConverted;
  31148. UNUSED_PARAMETER(pVfs);
  31149. UNUSED_PARAMETER(syncDir);
  31150. SimulateIOError(return SQLITE_IOERR_DELETE);
  31151. zConverted = convertUtf8Filename(zFilename);
  31152. if( zConverted==0 ){
  31153. return SQLITE_NOMEM;
  31154. }
  31155. if( isNT() ){
  31156. do{
  31157. DeleteFileW(zConverted);
  31158. }while( ( ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
  31159. || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
  31160. && (++cnt < MX_DELETION_ATTEMPTS)
  31161. && (Sleep(100), 1) );
  31162. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  31163. ** Since the ASCII version of these Windows API do not exist for WINCE,
  31164. ** it's important to not reference them for WINCE builds.
  31165. */
  31166. #if SQLITE_OS_WINCE==0
  31167. }else{
  31168. do{
  31169. DeleteFileA(zConverted);
  31170. }while( ( ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
  31171. || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
  31172. && (++cnt < MX_DELETION_ATTEMPTS)
  31173. && (Sleep(100), 1) );
  31174. #endif
  31175. }
  31176. free(zConverted);
  31177. OSTRACE(("DELETE \"%s\" %s\n", zFilename,
  31178. ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
  31179. "ok" : "failed" ));
  31180. return ( (rc == INVALID_FILE_ATTRIBUTES)
  31181. && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
  31182. }
  31183. /*
  31184. ** Check the existance and status of a file.
  31185. */
  31186. static int winAccess(
  31187. sqlite3_vfs *pVfs, /* Not used on win32 */
  31188. const char *zFilename, /* Name of file to check */
  31189. int flags, /* Type of test to make on this file */
  31190. int *pResOut /* OUT: Result */
  31191. ){
  31192. DWORD attr;
  31193. int rc = 0;
  31194. void *zConverted;
  31195. UNUSED_PARAMETER(pVfs);
  31196. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  31197. zConverted = convertUtf8Filename(zFilename);
  31198. if( zConverted==0 ){
  31199. return SQLITE_NOMEM;
  31200. }
  31201. if( isNT() ){
  31202. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  31203. memset(&sAttrData, 0, sizeof(sAttrData));
  31204. if( GetFileAttributesExW((WCHAR*)zConverted,
  31205. GetFileExInfoStandard,
  31206. &sAttrData) ){
  31207. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  31208. ** as if it does not exist.
  31209. */
  31210. if( flags==SQLITE_ACCESS_EXISTS
  31211. && sAttrData.nFileSizeHigh==0
  31212. && sAttrData.nFileSizeLow==0 ){
  31213. attr = INVALID_FILE_ATTRIBUTES;
  31214. }else{
  31215. attr = sAttrData.dwFileAttributes;
  31216. }
  31217. }else{
  31218. if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
  31219. free(zConverted);
  31220. return SQLITE_IOERR_ACCESS;
  31221. }else{
  31222. attr = INVALID_FILE_ATTRIBUTES;
  31223. }
  31224. }
  31225. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  31226. ** Since the ASCII version of these Windows API do not exist for WINCE,
  31227. ** it's important to not reference them for WINCE builds.
  31228. */
  31229. #if SQLITE_OS_WINCE==0
  31230. }else{
  31231. attr = GetFileAttributesA((char*)zConverted);
  31232. #endif
  31233. }
  31234. free(zConverted);
  31235. switch( flags ){
  31236. case SQLITE_ACCESS_READ:
  31237. case SQLITE_ACCESS_EXISTS:
  31238. rc = attr!=INVALID_FILE_ATTRIBUTES;
  31239. break;
  31240. case SQLITE_ACCESS_READWRITE:
  31241. rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
  31242. break;
  31243. default:
  31244. assert(!"Invalid flags argument");
  31245. }
  31246. *pResOut = rc;
  31247. return SQLITE_OK;
  31248. }
  31249. /*
  31250. ** Turn a relative pathname into a full pathname. Write the full
  31251. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  31252. ** bytes in size.
  31253. */
  31254. static int winFullPathname(
  31255. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  31256. const char *zRelative, /* Possibly relative input path */
  31257. int nFull, /* Size of output buffer in bytes */
  31258. char *zFull /* Output buffer */
  31259. ){
  31260. #if defined(__CYGWIN__)
  31261. SimulateIOError( return SQLITE_ERROR );
  31262. UNUSED_PARAMETER(nFull);
  31263. cygwin_conv_to_full_win32_path(zRelative, zFull);
  31264. return SQLITE_OK;
  31265. #endif
  31266. #if SQLITE_OS_WINCE
  31267. SimulateIOError( return SQLITE_ERROR );
  31268. UNUSED_PARAMETER(nFull);
  31269. /* WinCE has no concept of a relative pathname, or so I am told. */
  31270. sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
  31271. return SQLITE_OK;
  31272. #endif
  31273. #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
  31274. int nByte;
  31275. void *zConverted;
  31276. char *zOut;
  31277. /* It's odd to simulate an io-error here, but really this is just
  31278. ** using the io-error infrastructure to test that SQLite handles this
  31279. ** function failing. This function could fail if, for example, the
  31280. ** current working directory has been unlinked.
  31281. */
  31282. SimulateIOError( return SQLITE_ERROR );
  31283. UNUSED_PARAMETER(nFull);
  31284. zConverted = convertUtf8Filename(zRelative);
  31285. if( isNT() ){
  31286. WCHAR *zTemp;
  31287. nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
  31288. zTemp = malloc( nByte*sizeof(zTemp[0]) );
  31289. if( zTemp==0 ){
  31290. free(zConverted);
  31291. return SQLITE_NOMEM;
  31292. }
  31293. GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
  31294. free(zConverted);
  31295. zOut = unicodeToUtf8(zTemp);
  31296. free(zTemp);
  31297. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  31298. ** Since the ASCII version of these Windows API do not exist for WINCE,
  31299. ** it's important to not reference them for WINCE builds.
  31300. */
  31301. #if SQLITE_OS_WINCE==0
  31302. }else{
  31303. char *zTemp;
  31304. nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
  31305. zTemp = malloc( nByte*sizeof(zTemp[0]) );
  31306. if( zTemp==0 ){
  31307. free(zConverted);
  31308. return SQLITE_NOMEM;
  31309. }
  31310. GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  31311. free(zConverted);
  31312. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  31313. free(zTemp);
  31314. #endif
  31315. }
  31316. if( zOut ){
  31317. sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
  31318. free(zOut);
  31319. return SQLITE_OK;
  31320. }else{
  31321. return SQLITE_NOMEM;
  31322. }
  31323. #endif
  31324. }
  31325. /*
  31326. ** Get the sector size of the device used to store
  31327. ** file.
  31328. */
  31329. static int getSectorSize(
  31330. sqlite3_vfs *pVfs,
  31331. const char *zRelative /* UTF-8 file name */
  31332. ){
  31333. DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
  31334. /* GetDiskFreeSpace is not supported under WINCE */
  31335. #if SQLITE_OS_WINCE
  31336. UNUSED_PARAMETER(pVfs);
  31337. UNUSED_PARAMETER(zRelative);
  31338. #else
  31339. char zFullpath[MAX_PATH+1];
  31340. int rc;
  31341. DWORD dwRet = 0;
  31342. DWORD dwDummy;
  31343. /*
  31344. ** We need to get the full path name of the file
  31345. ** to get the drive letter to look up the sector
  31346. ** size.
  31347. */
  31348. SimulateIOErrorBenign(1);
  31349. rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
  31350. SimulateIOErrorBenign(0);
  31351. if( rc == SQLITE_OK )
  31352. {
  31353. void *zConverted = convertUtf8Filename(zFullpath);
  31354. if( zConverted ){
  31355. if( isNT() ){
  31356. /* trim path to just drive reference */
  31357. WCHAR *p = zConverted;
  31358. for(;*p;p++){
  31359. if( *p == '\\' ){
  31360. *p = '\0';
  31361. break;
  31362. }
  31363. }
  31364. dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
  31365. &dwDummy,
  31366. &bytesPerSector,
  31367. &dwDummy,
  31368. &dwDummy);
  31369. }else{
  31370. /* trim path to just drive reference */
  31371. char *p = (char *)zConverted;
  31372. for(;*p;p++){
  31373. if( *p == '\\' ){
  31374. *p = '\0';
  31375. break;
  31376. }
  31377. }
  31378. dwRet = GetDiskFreeSpaceA((char*)zConverted,
  31379. &dwDummy,
  31380. &bytesPerSector,
  31381. &dwDummy,
  31382. &dwDummy);
  31383. }
  31384. free(zConverted);
  31385. }
  31386. if( !dwRet ){
  31387. bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
  31388. }
  31389. }
  31390. #endif
  31391. return (int) bytesPerSector;
  31392. }
  31393. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  31394. /*
  31395. ** Interfaces for opening a shared library, finding entry points
  31396. ** within the shared library, and closing the shared library.
  31397. */
  31398. /*
  31399. ** Interfaces for opening a shared library, finding entry points
  31400. ** within the shared library, and closing the shared library.
  31401. */
  31402. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  31403. HANDLE h;
  31404. void *zConverted = convertUtf8Filename(zFilename);
  31405. UNUSED_PARAMETER(pVfs);
  31406. if( zConverted==0 ){
  31407. return 0;
  31408. }
  31409. if( isNT() ){
  31410. h = LoadLibraryW((WCHAR*)zConverted);
  31411. /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
  31412. ** Since the ASCII version of these Windows API do not exist for WINCE,
  31413. ** it's important to not reference them for WINCE builds.
  31414. */
  31415. #if SQLITE_OS_WINCE==0
  31416. }else{
  31417. h = LoadLibraryA((char*)zConverted);
  31418. #endif
  31419. }
  31420. free(zConverted);
  31421. return (void*)h;
  31422. }
  31423. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  31424. UNUSED_PARAMETER(pVfs);
  31425. getLastErrorMsg(nBuf, zBufOut);
  31426. }
  31427. void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
  31428. UNUSED_PARAMETER(pVfs);
  31429. #if SQLITE_OS_WINCE
  31430. /* The GetProcAddressA() routine is only available on wince. */
  31431. return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
  31432. #else
  31433. /* All other windows platforms expect GetProcAddress() to take
  31434. ** an Ansi string regardless of the _UNICODE setting */
  31435. return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
  31436. #endif
  31437. }
  31438. void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  31439. UNUSED_PARAMETER(pVfs);
  31440. FreeLibrary((HANDLE)pHandle);
  31441. }
  31442. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  31443. #define winDlOpen 0
  31444. #define winDlError 0
  31445. #define winDlSym 0
  31446. #define winDlClose 0
  31447. #endif
  31448. /*
  31449. ** Write up to nBuf bytes of randomness into zBuf.
  31450. */
  31451. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  31452. int n = 0;
  31453. UNUSED_PARAMETER(pVfs);
  31454. #if defined(SQLITE_TEST)
  31455. n = nBuf;
  31456. memset(zBuf, 0, nBuf);
  31457. #else
  31458. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  31459. SYSTEMTIME x;
  31460. GetSystemTime(&x);
  31461. memcpy(&zBuf[n], &x, sizeof(x));
  31462. n += sizeof(x);
  31463. }
  31464. if( sizeof(DWORD)<=nBuf-n ){
  31465. DWORD pid = GetCurrentProcessId();
  31466. memcpy(&zBuf[n], &pid, sizeof(pid));
  31467. n += sizeof(pid);
  31468. }
  31469. if( sizeof(DWORD)<=nBuf-n ){
  31470. DWORD cnt = GetTickCount();
  31471. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  31472. n += sizeof(cnt);
  31473. }
  31474. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  31475. LARGE_INTEGER i;
  31476. QueryPerformanceCounter(&i);
  31477. memcpy(&zBuf[n], &i, sizeof(i));
  31478. n += sizeof(i);
  31479. }
  31480. #endif
  31481. return n;
  31482. }
  31483. /*
  31484. ** Sleep for a little while. Return the amount of time slept.
  31485. */
  31486. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  31487. Sleep((microsec+999)/1000);
  31488. UNUSED_PARAMETER(pVfs);
  31489. return ((microsec+999)/1000)*1000;
  31490. }
  31491. /*
  31492. ** The following variable, if set to a non-zero value, is interpreted as
  31493. ** the number of seconds since 1970 and is used to set the result of
  31494. ** sqlite3OsCurrentTime() during testing.
  31495. */
  31496. #ifdef SQLITE_TEST
  31497. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  31498. #endif
  31499. /*
  31500. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  31501. ** the current time and date as a Julian Day number times 86_400_000. In
  31502. ** other words, write into *piNow the number of milliseconds since the Julian
  31503. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  31504. ** proleptic Gregorian calendar.
  31505. **
  31506. ** On success, return 0. Return 1 if the time and date cannot be found.
  31507. */
  31508. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  31509. /* FILETIME structure is a 64-bit value representing the number of
  31510. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  31511. */
  31512. FILETIME ft;
  31513. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  31514. #ifdef SQLITE_TEST
  31515. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  31516. #endif
  31517. /* 2^32 - to avoid use of LL and warnings in gcc */
  31518. static const sqlite3_int64 max32BitValue =
  31519. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
  31520. #if SQLITE_OS_WINCE
  31521. SYSTEMTIME time;
  31522. GetSystemTime(&time);
  31523. /* if SystemTimeToFileTime() fails, it returns zero. */
  31524. if (!SystemTimeToFileTime(&time,&ft)){
  31525. return 1;
  31526. }
  31527. #else
  31528. GetSystemTimeAsFileTime( &ft );
  31529. #endif
  31530. *piNow = winFiletimeEpoch +
  31531. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  31532. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  31533. #ifdef SQLITE_TEST
  31534. if( sqlite3_current_time ){
  31535. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  31536. }
  31537. #endif
  31538. UNUSED_PARAMETER(pVfs);
  31539. return 0;
  31540. }
  31541. /*
  31542. ** Find the current time (in Universal Coordinated Time). Write the
  31543. ** current time and date as a Julian Day number into *prNow and
  31544. ** return 0. Return 1 if the time and date cannot be found.
  31545. */
  31546. int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  31547. int rc;
  31548. sqlite3_int64 i;
  31549. rc = winCurrentTimeInt64(pVfs, &i);
  31550. if( !rc ){
  31551. *prNow = i/86400000.0;
  31552. }
  31553. return rc;
  31554. }
  31555. /*
  31556. ** The idea is that this function works like a combination of
  31557. ** GetLastError() and FormatMessage() on windows (or errno and
  31558. ** strerror_r() on unix). After an error is returned by an OS
  31559. ** function, SQLite calls this function with zBuf pointing to
  31560. ** a buffer of nBuf bytes. The OS layer should populate the
  31561. ** buffer with a nul-terminated UTF-8 encoded error message
  31562. ** describing the last IO error to have occurred within the calling
  31563. ** thread.
  31564. **
  31565. ** If the error message is too large for the supplied buffer,
  31566. ** it should be truncated. The return value of xGetLastError
  31567. ** is zero if the error message fits in the buffer, or non-zero
  31568. ** otherwise (if the message was truncated). If non-zero is returned,
  31569. ** then it is not necessary to include the nul-terminator character
  31570. ** in the output buffer.
  31571. **
  31572. ** Not supplying an error message will have no adverse effect
  31573. ** on SQLite. It is fine to have an implementation that never
  31574. ** returns an error message:
  31575. **
  31576. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  31577. ** assert(zBuf[0]=='\0');
  31578. ** return 0;
  31579. ** }
  31580. **
  31581. ** However if an error message is supplied, it will be incorporated
  31582. ** by sqlite into the error message available to the user using
  31583. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  31584. */
  31585. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  31586. UNUSED_PARAMETER(pVfs);
  31587. return getLastErrorMsg(nBuf, zBuf);
  31588. }
  31589. /*
  31590. ** Initialize and deinitialize the operating system interface.
  31591. */
  31592. SQLITE_API int sqlite3_os_init(void){
  31593. static sqlite3_vfs winVfs = {
  31594. 3, /* iVersion */
  31595. sizeof(winFile), /* szOsFile */
  31596. MAX_PATH, /* mxPathname */
  31597. 0, /* pNext */
  31598. "win32", /* zName */
  31599. 0, /* pAppData */
  31600. winOpen, /* xOpen */
  31601. winDelete, /* xDelete */
  31602. winAccess, /* xAccess */
  31603. winFullPathname, /* xFullPathname */
  31604. winDlOpen, /* xDlOpen */
  31605. winDlError, /* xDlError */
  31606. winDlSym, /* xDlSym */
  31607. winDlClose, /* xDlClose */
  31608. winRandomness, /* xRandomness */
  31609. winSleep, /* xSleep */
  31610. winCurrentTime, /* xCurrentTime */
  31611. winGetLastError, /* xGetLastError */
  31612. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  31613. 0, /* xSetSystemCall */
  31614. 0, /* xGetSystemCall */
  31615. 0, /* xNextSystemCall */
  31616. };
  31617. #ifndef SQLITE_OMIT_WAL
  31618. /* get memory map allocation granularity */
  31619. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  31620. GetSystemInfo(&winSysInfo);
  31621. assert(winSysInfo.dwAllocationGranularity > 0);
  31622. #endif
  31623. sqlite3_vfs_register(&winVfs, 1);
  31624. return SQLITE_OK;
  31625. }
  31626. SQLITE_API int sqlite3_os_end(void){
  31627. return SQLITE_OK;
  31628. }
  31629. #endif /* SQLITE_OS_WIN */
  31630. /************** End of os_win.c **********************************************/
  31631. /************** Begin file bitvec.c ******************************************/
  31632. /*
  31633. ** 2008 February 16
  31634. **
  31635. ** The author disclaims copyright to this source code. In place of
  31636. ** a legal notice, here is a blessing:
  31637. **
  31638. ** May you do good and not evil.
  31639. ** May you find forgiveness for yourself and forgive others.
  31640. ** May you share freely, never taking more than you give.
  31641. **
  31642. *************************************************************************
  31643. ** This file implements an object that represents a fixed-length
  31644. ** bitmap. Bits are numbered starting with 1.
  31645. **
  31646. ** A bitmap is used to record which pages of a database file have been
  31647. ** journalled during a transaction, or which pages have the "dont-write"
  31648. ** property. Usually only a few pages are meet either condition.
  31649. ** So the bitmap is usually sparse and has low cardinality.
  31650. ** But sometimes (for example when during a DROP of a large table) most
  31651. ** or all of the pages in a database can get journalled. In those cases,
  31652. ** the bitmap becomes dense with high cardinality. The algorithm needs
  31653. ** to handle both cases well.
  31654. **
  31655. ** The size of the bitmap is fixed when the object is created.
  31656. **
  31657. ** All bits are clear when the bitmap is created. Individual bits
  31658. ** may be set or cleared one at a time.
  31659. **
  31660. ** Test operations are about 100 times more common that set operations.
  31661. ** Clear operations are exceedingly rare. There are usually between
  31662. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  31663. ** sometimes grow into tens of thousands or larger. The size of the
  31664. ** Bitvec object is the number of pages in the database file at the
  31665. ** start of a transaction, and is thus usually less than a few thousand,
  31666. ** but can be as large as 2 billion for a really big database.
  31667. */
  31668. /* Size of the Bitvec structure in bytes. */
  31669. #define BITVEC_SZ 512
  31670. /* Round the union size down to the nearest pointer boundary, since that's how
  31671. ** it will be aligned within the Bitvec struct. */
  31672. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  31673. /* Type of the array "element" for the bitmap representation.
  31674. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  31675. ** Setting this to the "natural word" size of your CPU may improve
  31676. ** performance. */
  31677. #define BITVEC_TELEM u8
  31678. /* Size, in bits, of the bitmap element. */
  31679. #define BITVEC_SZELEM 8
  31680. /* Number of elements in a bitmap array. */
  31681. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  31682. /* Number of bits in the bitmap array. */
  31683. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  31684. /* Number of u32 values in hash table. */
  31685. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  31686. /* Maximum number of entries in hash table before
  31687. ** sub-dividing and re-hashing. */
  31688. #define BITVEC_MXHASH (BITVEC_NINT/2)
  31689. /* Hashing function for the aHash representation.
  31690. ** Empirical testing showed that the *37 multiplier
  31691. ** (an arbitrary prime)in the hash function provided
  31692. ** no fewer collisions than the no-op *1. */
  31693. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  31694. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  31695. /*
  31696. ** A bitmap is an instance of the following structure.
  31697. **
  31698. ** This bitmap records the existance of zero or more bits
  31699. ** with values between 1 and iSize, inclusive.
  31700. **
  31701. ** There are three possible representations of the bitmap.
  31702. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  31703. ** bitmap. The least significant bit is bit 1.
  31704. **
  31705. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  31706. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  31707. **
  31708. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  31709. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  31710. ** handles up to iDivisor separate values of i. apSub[0] holds
  31711. ** values between 1 and iDivisor. apSub[1] holds values between
  31712. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  31713. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  31714. ** to hold deal with values between 1 and iDivisor.
  31715. */
  31716. struct Bitvec {
  31717. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  31718. u32 nSet; /* Number of bits that are set - only valid for aHash
  31719. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  31720. ** this would be 125. */
  31721. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  31722. /* Should >=0 for apSub element. */
  31723. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  31724. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  31725. union {
  31726. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  31727. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  31728. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  31729. } u;
  31730. };
  31731. /*
  31732. ** Create a new bitmap object able to handle bits between 0 and iSize,
  31733. ** inclusive. Return a pointer to the new object. Return NULL if
  31734. ** malloc fails.
  31735. */
  31736. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  31737. Bitvec *p;
  31738. assert( sizeof(*p)==BITVEC_SZ );
  31739. p = sqlite3MallocZero( sizeof(*p) );
  31740. if( p ){
  31741. p->iSize = iSize;
  31742. }
  31743. return p;
  31744. }
  31745. /*
  31746. ** Check to see if the i-th bit is set. Return true or false.
  31747. ** If p is NULL (if the bitmap has not been created) or if
  31748. ** i is out of range, then return false.
  31749. */
  31750. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  31751. if( p==0 ) return 0;
  31752. if( i>p->iSize || i==0 ) return 0;
  31753. i--;
  31754. while( p->iDivisor ){
  31755. u32 bin = i/p->iDivisor;
  31756. i = i%p->iDivisor;
  31757. p = p->u.apSub[bin];
  31758. if (!p) {
  31759. return 0;
  31760. }
  31761. }
  31762. if( p->iSize<=BITVEC_NBIT ){
  31763. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  31764. } else{
  31765. u32 h = BITVEC_HASH(i++);
  31766. while( p->u.aHash[h] ){
  31767. if( p->u.aHash[h]==i ) return 1;
  31768. h = (h+1) % BITVEC_NINT;
  31769. }
  31770. return 0;
  31771. }
  31772. }
  31773. /*
  31774. ** Set the i-th bit. Return 0 on success and an error code if
  31775. ** anything goes wrong.
  31776. **
  31777. ** This routine might cause sub-bitmaps to be allocated. Failing
  31778. ** to get the memory needed to hold the sub-bitmap is the only
  31779. ** that can go wrong with an insert, assuming p and i are valid.
  31780. **
  31781. ** The calling function must ensure that p is a valid Bitvec object
  31782. ** and that the value for "i" is within range of the Bitvec object.
  31783. ** Otherwise the behavior is undefined.
  31784. */
  31785. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  31786. u32 h;
  31787. if( p==0 ) return SQLITE_OK;
  31788. assert( i>0 );
  31789. assert( i<=p->iSize );
  31790. i--;
  31791. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  31792. u32 bin = i/p->iDivisor;
  31793. i = i%p->iDivisor;
  31794. if( p->u.apSub[bin]==0 ){
  31795. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  31796. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  31797. }
  31798. p = p->u.apSub[bin];
  31799. }
  31800. if( p->iSize<=BITVEC_NBIT ){
  31801. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  31802. return SQLITE_OK;
  31803. }
  31804. h = BITVEC_HASH(i++);
  31805. /* if there wasn't a hash collision, and this doesn't */
  31806. /* completely fill the hash, then just add it without */
  31807. /* worring about sub-dividing and re-hashing. */
  31808. if( !p->u.aHash[h] ){
  31809. if (p->nSet<(BITVEC_NINT-1)) {
  31810. goto bitvec_set_end;
  31811. } else {
  31812. goto bitvec_set_rehash;
  31813. }
  31814. }
  31815. /* there was a collision, check to see if it's already */
  31816. /* in hash, if not, try to find a spot for it */
  31817. do {
  31818. if( p->u.aHash[h]==i ) return SQLITE_OK;
  31819. h++;
  31820. if( h>=BITVEC_NINT ) h = 0;
  31821. } while( p->u.aHash[h] );
  31822. /* we didn't find it in the hash. h points to the first */
  31823. /* available free spot. check to see if this is going to */
  31824. /* make our hash too "full". */
  31825. bitvec_set_rehash:
  31826. if( p->nSet>=BITVEC_MXHASH ){
  31827. unsigned int j;
  31828. int rc;
  31829. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  31830. if( aiValues==0 ){
  31831. return SQLITE_NOMEM;
  31832. }else{
  31833. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  31834. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  31835. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  31836. rc = sqlite3BitvecSet(p, i);
  31837. for(j=0; j<BITVEC_NINT; j++){
  31838. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  31839. }
  31840. sqlite3StackFree(0, aiValues);
  31841. return rc;
  31842. }
  31843. }
  31844. bitvec_set_end:
  31845. p->nSet++;
  31846. p->u.aHash[h] = i;
  31847. return SQLITE_OK;
  31848. }
  31849. /*
  31850. ** Clear the i-th bit.
  31851. **
  31852. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  31853. ** that BitvecClear can use to rebuilt its hash table.
  31854. */
  31855. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  31856. if( p==0 ) return;
  31857. assert( i>0 );
  31858. i--;
  31859. while( p->iDivisor ){
  31860. u32 bin = i/p->iDivisor;
  31861. i = i%p->iDivisor;
  31862. p = p->u.apSub[bin];
  31863. if (!p) {
  31864. return;
  31865. }
  31866. }
  31867. if( p->iSize<=BITVEC_NBIT ){
  31868. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  31869. }else{
  31870. unsigned int j;
  31871. u32 *aiValues = pBuf;
  31872. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  31873. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  31874. p->nSet = 0;
  31875. for(j=0; j<BITVEC_NINT; j++){
  31876. if( aiValues[j] && aiValues[j]!=(i+1) ){
  31877. u32 h = BITVEC_HASH(aiValues[j]-1);
  31878. p->nSet++;
  31879. while( p->u.aHash[h] ){
  31880. h++;
  31881. if( h>=BITVEC_NINT ) h = 0;
  31882. }
  31883. p->u.aHash[h] = aiValues[j];
  31884. }
  31885. }
  31886. }
  31887. }
  31888. /*
  31889. ** Destroy a bitmap object. Reclaim all memory used.
  31890. */
  31891. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  31892. if( p==0 ) return;
  31893. if( p->iDivisor ){
  31894. unsigned int i;
  31895. for(i=0; i<BITVEC_NPTR; i++){
  31896. sqlite3BitvecDestroy(p->u.apSub[i]);
  31897. }
  31898. }
  31899. sqlite3_free(p);
  31900. }
  31901. /*
  31902. ** Return the value of the iSize parameter specified when Bitvec *p
  31903. ** was created.
  31904. */
  31905. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  31906. return p->iSize;
  31907. }
  31908. #ifndef SQLITE_OMIT_BUILTIN_TEST
  31909. /*
  31910. ** Let V[] be an array of unsigned characters sufficient to hold
  31911. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  31912. ** Then the following macros can be used to set, clear, or test
  31913. ** individual bits within V.
  31914. */
  31915. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  31916. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  31917. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  31918. /*
  31919. ** This routine runs an extensive test of the Bitvec code.
  31920. **
  31921. ** The input is an array of integers that acts as a program
  31922. ** to test the Bitvec. The integers are opcodes followed
  31923. ** by 0, 1, or 3 operands, depending on the opcode. Another
  31924. ** opcode follows immediately after the last operand.
  31925. **
  31926. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  31927. ** "halt" opcode and causes the test to end.
  31928. **
  31929. ** 0 Halt and return the number of errors
  31930. ** 1 N S X Set N bits beginning with S and incrementing by X
  31931. ** 2 N S X Clear N bits beginning with S and incrementing by X
  31932. ** 3 N Set N randomly chosen bits
  31933. ** 4 N Clear N randomly chosen bits
  31934. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  31935. **
  31936. ** The opcodes 1 through 4 perform set and clear operations are performed
  31937. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  31938. ** Opcode 5 works on the linear array only, not on the Bitvec.
  31939. ** Opcode 5 is used to deliberately induce a fault in order to
  31940. ** confirm that error detection works.
  31941. **
  31942. ** At the conclusion of the test the linear array is compared
  31943. ** against the Bitvec object. If there are any differences,
  31944. ** an error is returned. If they are the same, zero is returned.
  31945. **
  31946. ** If a memory allocation error occurs, return -1.
  31947. */
  31948. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  31949. Bitvec *pBitvec = 0;
  31950. unsigned char *pV = 0;
  31951. int rc = -1;
  31952. int i, nx, pc, op;
  31953. void *pTmpSpace;
  31954. /* Allocate the Bitvec to be tested and a linear array of
  31955. ** bits to act as the reference */
  31956. pBitvec = sqlite3BitvecCreate( sz );
  31957. pV = sqlite3_malloc( (sz+7)/8 + 1 );
  31958. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  31959. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  31960. memset(pV, 0, (sz+7)/8 + 1);
  31961. /* NULL pBitvec tests */
  31962. sqlite3BitvecSet(0, 1);
  31963. sqlite3BitvecClear(0, 1, pTmpSpace);
  31964. /* Run the program */
  31965. pc = 0;
  31966. while( (op = aOp[pc])!=0 ){
  31967. switch( op ){
  31968. case 1:
  31969. case 2:
  31970. case 5: {
  31971. nx = 4;
  31972. i = aOp[pc+2] - 1;
  31973. aOp[pc+2] += aOp[pc+3];
  31974. break;
  31975. }
  31976. case 3:
  31977. case 4:
  31978. default: {
  31979. nx = 2;
  31980. sqlite3_randomness(sizeof(i), &i);
  31981. break;
  31982. }
  31983. }
  31984. if( (--aOp[pc+1]) > 0 ) nx = 0;
  31985. pc += nx;
  31986. i = (i & 0x7fffffff)%sz;
  31987. if( (op & 1)!=0 ){
  31988. SETBIT(pV, (i+1));
  31989. if( op!=5 ){
  31990. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  31991. }
  31992. }else{
  31993. CLEARBIT(pV, (i+1));
  31994. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  31995. }
  31996. }
  31997. /* Test to make sure the linear array exactly matches the
  31998. ** Bitvec object. Start with the assumption that they do
  31999. ** match (rc==0). Change rc to non-zero if a discrepancy
  32000. ** is found.
  32001. */
  32002. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  32003. + sqlite3BitvecTest(pBitvec, 0)
  32004. + (sqlite3BitvecSize(pBitvec) - sz);
  32005. for(i=1; i<=sz; i++){
  32006. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  32007. rc = i;
  32008. break;
  32009. }
  32010. }
  32011. /* Free allocated structure */
  32012. bitvec_end:
  32013. sqlite3_free(pTmpSpace);
  32014. sqlite3_free(pV);
  32015. sqlite3BitvecDestroy(pBitvec);
  32016. return rc;
  32017. }
  32018. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  32019. /************** End of bitvec.c **********************************************/
  32020. /************** Begin file pcache.c ******************************************/
  32021. /*
  32022. ** 2008 August 05
  32023. **
  32024. ** The author disclaims copyright to this source code. In place of
  32025. ** a legal notice, here is a blessing:
  32026. **
  32027. ** May you do good and not evil.
  32028. ** May you find forgiveness for yourself and forgive others.
  32029. ** May you share freely, never taking more than you give.
  32030. **
  32031. *************************************************************************
  32032. ** This file implements that page cache.
  32033. */
  32034. /*
  32035. ** A complete page cache is an instance of this structure.
  32036. */
  32037. struct PCache {
  32038. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  32039. PgHdr *pSynced; /* Last synced page in dirty page list */
  32040. int nRef; /* Number of referenced pages */
  32041. int nMax; /* Configured cache size */
  32042. int szPage; /* Size of every page in this cache */
  32043. int szExtra; /* Size of extra space for each page */
  32044. int bPurgeable; /* True if pages are on backing store */
  32045. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  32046. void *pStress; /* Argument to xStress */
  32047. sqlite3_pcache *pCache; /* Pluggable cache module */
  32048. PgHdr *pPage1; /* Reference to page 1 */
  32049. };
  32050. /*
  32051. ** Some of the assert() macros in this code are too expensive to run
  32052. ** even during normal debugging. Use them only rarely on long-running
  32053. ** tests. Enable the expensive asserts using the
  32054. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  32055. */
  32056. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  32057. # define expensive_assert(X) assert(X)
  32058. #else
  32059. # define expensive_assert(X)
  32060. #endif
  32061. /********************************** Linked List Management ********************/
  32062. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  32063. /*
  32064. ** Check that the pCache->pSynced variable is set correctly. If it
  32065. ** is not, either fail an assert or return zero. Otherwise, return
  32066. ** non-zero. This is only used in debugging builds, as follows:
  32067. **
  32068. ** expensive_assert( pcacheCheckSynced(pCache) );
  32069. */
  32070. static int pcacheCheckSynced(PCache *pCache){
  32071. PgHdr *p;
  32072. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  32073. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  32074. }
  32075. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  32076. }
  32077. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  32078. /*
  32079. ** Remove page pPage from the list of dirty pages.
  32080. */
  32081. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  32082. PCache *p = pPage->pCache;
  32083. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  32084. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  32085. /* Update the PCache1.pSynced variable if necessary. */
  32086. if( p->pSynced==pPage ){
  32087. PgHdr *pSynced = pPage->pDirtyPrev;
  32088. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  32089. pSynced = pSynced->pDirtyPrev;
  32090. }
  32091. p->pSynced = pSynced;
  32092. }
  32093. if( pPage->pDirtyNext ){
  32094. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  32095. }else{
  32096. assert( pPage==p->pDirtyTail );
  32097. p->pDirtyTail = pPage->pDirtyPrev;
  32098. }
  32099. if( pPage->pDirtyPrev ){
  32100. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  32101. }else{
  32102. assert( pPage==p->pDirty );
  32103. p->pDirty = pPage->pDirtyNext;
  32104. }
  32105. pPage->pDirtyNext = 0;
  32106. pPage->pDirtyPrev = 0;
  32107. expensive_assert( pcacheCheckSynced(p) );
  32108. }
  32109. /*
  32110. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  32111. ** pPage).
  32112. */
  32113. static void pcacheAddToDirtyList(PgHdr *pPage){
  32114. PCache *p = pPage->pCache;
  32115. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  32116. pPage->pDirtyNext = p->pDirty;
  32117. if( pPage->pDirtyNext ){
  32118. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  32119. pPage->pDirtyNext->pDirtyPrev = pPage;
  32120. }
  32121. p->pDirty = pPage;
  32122. if( !p->pDirtyTail ){
  32123. p->pDirtyTail = pPage;
  32124. }
  32125. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  32126. p->pSynced = pPage;
  32127. }
  32128. expensive_assert( pcacheCheckSynced(p) );
  32129. }
  32130. /*
  32131. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  32132. ** being used for an in-memory database, this function is a no-op.
  32133. */
  32134. static void pcacheUnpin(PgHdr *p){
  32135. PCache *pCache = p->pCache;
  32136. if( pCache->bPurgeable ){
  32137. if( p->pgno==1 ){
  32138. pCache->pPage1 = 0;
  32139. }
  32140. sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
  32141. }
  32142. }
  32143. /*************************************************** General Interfaces ******
  32144. **
  32145. ** Initialize and shutdown the page cache subsystem. Neither of these
  32146. ** functions are threadsafe.
  32147. */
  32148. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  32149. if( sqlite3GlobalConfig.pcache.xInit==0 ){
  32150. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  32151. ** built-in default page cache is used instead of the application defined
  32152. ** page cache. */
  32153. sqlite3PCacheSetDefault();
  32154. }
  32155. return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
  32156. }
  32157. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  32158. if( sqlite3GlobalConfig.pcache.xShutdown ){
  32159. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  32160. sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
  32161. }
  32162. }
  32163. /*
  32164. ** Return the size in bytes of a PCache object.
  32165. */
  32166. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  32167. /*
  32168. ** Create a new PCache object. Storage space to hold the object
  32169. ** has already been allocated and is passed in as the p pointer.
  32170. ** The caller discovers how much space needs to be allocated by
  32171. ** calling sqlite3PcacheSize().
  32172. */
  32173. SQLITE_PRIVATE void sqlite3PcacheOpen(
  32174. int szPage, /* Size of every page */
  32175. int szExtra, /* Extra space associated with each page */
  32176. int bPurgeable, /* True if pages are on backing store */
  32177. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  32178. void *pStress, /* Argument to xStress */
  32179. PCache *p /* Preallocated space for the PCache */
  32180. ){
  32181. memset(p, 0, sizeof(PCache));
  32182. p->szPage = szPage;
  32183. p->szExtra = szExtra;
  32184. p->bPurgeable = bPurgeable;
  32185. p->xStress = xStress;
  32186. p->pStress = pStress;
  32187. p->nMax = 100;
  32188. }
  32189. /*
  32190. ** Change the page size for PCache object. The caller must ensure that there
  32191. ** are no outstanding page references when this function is called.
  32192. */
  32193. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  32194. assert( pCache->nRef==0 && pCache->pDirty==0 );
  32195. if( pCache->pCache ){
  32196. sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  32197. pCache->pCache = 0;
  32198. pCache->pPage1 = 0;
  32199. }
  32200. pCache->szPage = szPage;
  32201. }
  32202. /*
  32203. ** Try to obtain a page from the cache.
  32204. */
  32205. SQLITE_PRIVATE int sqlite3PcacheFetch(
  32206. PCache *pCache, /* Obtain the page from this cache */
  32207. Pgno pgno, /* Page number to obtain */
  32208. int createFlag, /* If true, create page if it does not exist already */
  32209. PgHdr **ppPage /* Write the page here */
  32210. ){
  32211. PgHdr *pPage = 0;
  32212. int eCreate;
  32213. assert( pCache!=0 );
  32214. assert( createFlag==1 || createFlag==0 );
  32215. assert( pgno>0 );
  32216. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  32217. ** allocate it now.
  32218. */
  32219. if( !pCache->pCache && createFlag ){
  32220. sqlite3_pcache *p;
  32221. int nByte;
  32222. nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
  32223. p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
  32224. if( !p ){
  32225. return SQLITE_NOMEM;
  32226. }
  32227. sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
  32228. pCache->pCache = p;
  32229. }
  32230. eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  32231. if( pCache->pCache ){
  32232. pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
  32233. }
  32234. if( !pPage && eCreate==1 ){
  32235. PgHdr *pPg;
  32236. /* Find a dirty page to write-out and recycle. First try to find a
  32237. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  32238. ** cleared), but if that is not possible settle for any other
  32239. ** unreferenced dirty page.
  32240. */
  32241. expensive_assert( pcacheCheckSynced(pCache) );
  32242. for(pPg=pCache->pSynced;
  32243. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  32244. pPg=pPg->pDirtyPrev
  32245. );
  32246. pCache->pSynced = pPg;
  32247. if( !pPg ){
  32248. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  32249. }
  32250. if( pPg ){
  32251. int rc;
  32252. rc = pCache->xStress(pCache->pStress, pPg);
  32253. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  32254. return rc;
  32255. }
  32256. }
  32257. pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
  32258. }
  32259. if( pPage ){
  32260. if( !pPage->pData ){
  32261. memset(pPage, 0, sizeof(PgHdr));
  32262. pPage->pData = (void *)&pPage[1];
  32263. pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
  32264. memset(pPage->pExtra, 0, pCache->szExtra);
  32265. pPage->pCache = pCache;
  32266. pPage->pgno = pgno;
  32267. }
  32268. assert( pPage->pCache==pCache );
  32269. assert( pPage->pgno==pgno );
  32270. assert( pPage->pData==(void *)&pPage[1] );
  32271. assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
  32272. if( 0==pPage->nRef ){
  32273. pCache->nRef++;
  32274. }
  32275. pPage->nRef++;
  32276. if( pgno==1 ){
  32277. pCache->pPage1 = pPage;
  32278. }
  32279. }
  32280. *ppPage = pPage;
  32281. return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  32282. }
  32283. /*
  32284. ** Decrement the reference count on a page. If the page is clean and the
  32285. ** reference count drops to 0, then it is made elible for recycling.
  32286. */
  32287. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  32288. assert( p->nRef>0 );
  32289. p->nRef--;
  32290. if( p->nRef==0 ){
  32291. PCache *pCache = p->pCache;
  32292. pCache->nRef--;
  32293. if( (p->flags&PGHDR_DIRTY)==0 ){
  32294. pcacheUnpin(p);
  32295. }else{
  32296. /* Move the page to the head of the dirty list. */
  32297. pcacheRemoveFromDirtyList(p);
  32298. pcacheAddToDirtyList(p);
  32299. }
  32300. }
  32301. }
  32302. /*
  32303. ** Increase the reference count of a supplied page by 1.
  32304. */
  32305. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  32306. assert(p->nRef>0);
  32307. p->nRef++;
  32308. }
  32309. /*
  32310. ** Drop a page from the cache. There must be exactly one reference to the
  32311. ** page. This function deletes that reference, so after it returns the
  32312. ** page pointed to by p is invalid.
  32313. */
  32314. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  32315. PCache *pCache;
  32316. assert( p->nRef==1 );
  32317. if( p->flags&PGHDR_DIRTY ){
  32318. pcacheRemoveFromDirtyList(p);
  32319. }
  32320. pCache = p->pCache;
  32321. pCache->nRef--;
  32322. if( p->pgno==1 ){
  32323. pCache->pPage1 = 0;
  32324. }
  32325. sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
  32326. }
  32327. /*
  32328. ** Make sure the page is marked as dirty. If it isn't dirty already,
  32329. ** make it so.
  32330. */
  32331. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  32332. p->flags &= ~PGHDR_DONT_WRITE;
  32333. assert( p->nRef>0 );
  32334. if( 0==(p->flags & PGHDR_DIRTY) ){
  32335. p->flags |= PGHDR_DIRTY;
  32336. pcacheAddToDirtyList( p);
  32337. }
  32338. }
  32339. /*
  32340. ** Make sure the page is marked as clean. If it isn't clean already,
  32341. ** make it so.
  32342. */
  32343. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  32344. if( (p->flags & PGHDR_DIRTY) ){
  32345. pcacheRemoveFromDirtyList(p);
  32346. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  32347. if( p->nRef==0 ){
  32348. pcacheUnpin(p);
  32349. }
  32350. }
  32351. }
  32352. /*
  32353. ** Make every page in the cache clean.
  32354. */
  32355. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  32356. PgHdr *p;
  32357. while( (p = pCache->pDirty)!=0 ){
  32358. sqlite3PcacheMakeClean(p);
  32359. }
  32360. }
  32361. /*
  32362. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  32363. */
  32364. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  32365. PgHdr *p;
  32366. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  32367. p->flags &= ~PGHDR_NEED_SYNC;
  32368. }
  32369. pCache->pSynced = pCache->pDirtyTail;
  32370. }
  32371. /*
  32372. ** Change the page number of page p to newPgno.
  32373. */
  32374. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  32375. PCache *pCache = p->pCache;
  32376. assert( p->nRef>0 );
  32377. assert( newPgno>0 );
  32378. sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
  32379. p->pgno = newPgno;
  32380. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  32381. pcacheRemoveFromDirtyList(p);
  32382. pcacheAddToDirtyList(p);
  32383. }
  32384. }
  32385. /*
  32386. ** Drop every cache entry whose page number is greater than "pgno". The
  32387. ** caller must ensure that there are no outstanding references to any pages
  32388. ** other than page 1 with a page number greater than pgno.
  32389. **
  32390. ** If there is a reference to page 1 and the pgno parameter passed to this
  32391. ** function is 0, then the data area associated with page 1 is zeroed, but
  32392. ** the page object is not dropped.
  32393. */
  32394. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  32395. if( pCache->pCache ){
  32396. PgHdr *p;
  32397. PgHdr *pNext;
  32398. for(p=pCache->pDirty; p; p=pNext){
  32399. pNext = p->pDirtyNext;
  32400. /* This routine never gets call with a positive pgno except right
  32401. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  32402. ** it must be that pgno==0.
  32403. */
  32404. assert( p->pgno>0 );
  32405. if( ALWAYS(p->pgno>pgno) ){
  32406. assert( p->flags&PGHDR_DIRTY );
  32407. sqlite3PcacheMakeClean(p);
  32408. }
  32409. }
  32410. if( pgno==0 && pCache->pPage1 ){
  32411. memset(pCache->pPage1->pData, 0, pCache->szPage);
  32412. pgno = 1;
  32413. }
  32414. sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
  32415. }
  32416. }
  32417. /*
  32418. ** Close a cache.
  32419. */
  32420. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  32421. if( pCache->pCache ){
  32422. sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  32423. }
  32424. }
  32425. /*
  32426. ** Discard the contents of the cache.
  32427. */
  32428. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  32429. sqlite3PcacheTruncate(pCache, 0);
  32430. }
  32431. /*
  32432. ** Merge two lists of pages connected by pDirty and in pgno order.
  32433. ** Do not both fixing the pDirtyPrev pointers.
  32434. */
  32435. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  32436. PgHdr result, *pTail;
  32437. pTail = &result;
  32438. while( pA && pB ){
  32439. if( pA->pgno<pB->pgno ){
  32440. pTail->pDirty = pA;
  32441. pTail = pA;
  32442. pA = pA->pDirty;
  32443. }else{
  32444. pTail->pDirty = pB;
  32445. pTail = pB;
  32446. pB = pB->pDirty;
  32447. }
  32448. }
  32449. if( pA ){
  32450. pTail->pDirty = pA;
  32451. }else if( pB ){
  32452. pTail->pDirty = pB;
  32453. }else{
  32454. pTail->pDirty = 0;
  32455. }
  32456. return result.pDirty;
  32457. }
  32458. /*
  32459. ** Sort the list of pages in accending order by pgno. Pages are
  32460. ** connected by pDirty pointers. The pDirtyPrev pointers are
  32461. ** corrupted by this sort.
  32462. **
  32463. ** Since there cannot be more than 2^31 distinct pages in a database,
  32464. ** there cannot be more than 31 buckets required by the merge sorter.
  32465. ** One extra bucket is added to catch overflow in case something
  32466. ** ever changes to make the previous sentence incorrect.
  32467. */
  32468. #define N_SORT_BUCKET 32
  32469. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  32470. PgHdr *a[N_SORT_BUCKET], *p;
  32471. int i;
  32472. memset(a, 0, sizeof(a));
  32473. while( pIn ){
  32474. p = pIn;
  32475. pIn = p->pDirty;
  32476. p->pDirty = 0;
  32477. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  32478. if( a[i]==0 ){
  32479. a[i] = p;
  32480. break;
  32481. }else{
  32482. p = pcacheMergeDirtyList(a[i], p);
  32483. a[i] = 0;
  32484. }
  32485. }
  32486. if( NEVER(i==N_SORT_BUCKET-1) ){
  32487. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  32488. ** the input list. But that is impossible.
  32489. */
  32490. a[i] = pcacheMergeDirtyList(a[i], p);
  32491. }
  32492. }
  32493. p = a[0];
  32494. for(i=1; i<N_SORT_BUCKET; i++){
  32495. p = pcacheMergeDirtyList(p, a[i]);
  32496. }
  32497. return p;
  32498. }
  32499. /*
  32500. ** Return a list of all dirty pages in the cache, sorted by page number.
  32501. */
  32502. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  32503. PgHdr *p;
  32504. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  32505. p->pDirty = p->pDirtyNext;
  32506. }
  32507. return pcacheSortDirtyList(pCache->pDirty);
  32508. }
  32509. /*
  32510. ** Return the total number of referenced pages held by the cache.
  32511. */
  32512. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  32513. return pCache->nRef;
  32514. }
  32515. /*
  32516. ** Return the number of references to the page supplied as an argument.
  32517. */
  32518. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  32519. return p->nRef;
  32520. }
  32521. /*
  32522. ** Return the total number of pages in the cache.
  32523. */
  32524. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  32525. int nPage = 0;
  32526. if( pCache->pCache ){
  32527. nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
  32528. }
  32529. return nPage;
  32530. }
  32531. #ifdef SQLITE_TEST
  32532. /*
  32533. ** Get the suggested cache-size value.
  32534. */
  32535. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  32536. return pCache->nMax;
  32537. }
  32538. #endif
  32539. /*
  32540. ** Set the suggested cache-size value.
  32541. */
  32542. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  32543. pCache->nMax = mxPage;
  32544. if( pCache->pCache ){
  32545. sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
  32546. }
  32547. }
  32548. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  32549. /*
  32550. ** For all dirty pages currently in the cache, invoke the specified
  32551. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  32552. ** defined.
  32553. */
  32554. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  32555. PgHdr *pDirty;
  32556. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  32557. xIter(pDirty);
  32558. }
  32559. }
  32560. #endif
  32561. /************** End of pcache.c **********************************************/
  32562. /************** Begin file pcache1.c *****************************************/
  32563. /*
  32564. ** 2008 November 05
  32565. **
  32566. ** The author disclaims copyright to this source code. In place of
  32567. ** a legal notice, here is a blessing:
  32568. **
  32569. ** May you do good and not evil.
  32570. ** May you find forgiveness for yourself and forgive others.
  32571. ** May you share freely, never taking more than you give.
  32572. **
  32573. *************************************************************************
  32574. **
  32575. ** This file implements the default page cache implementation (the
  32576. ** sqlite3_pcache interface). It also contains part of the implementation
  32577. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  32578. ** If the default page cache implementation is overriden, then neither of
  32579. ** these two features are available.
  32580. */
  32581. typedef struct PCache1 PCache1;
  32582. typedef struct PgHdr1 PgHdr1;
  32583. typedef struct PgFreeslot PgFreeslot;
  32584. typedef struct PGroup PGroup;
  32585. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  32586. ** of one or more PCaches that are able to recycle each others unpinned
  32587. ** pages when they are under memory pressure. A PGroup is an instance of
  32588. ** the following object.
  32589. **
  32590. ** This page cache implementation works in one of two modes:
  32591. **
  32592. ** (1) Every PCache is the sole member of its own PGroup. There is
  32593. ** one PGroup per PCache.
  32594. **
  32595. ** (2) There is a single global PGroup that all PCaches are a member
  32596. ** of.
  32597. **
  32598. ** Mode 1 uses more memory (since PCache instances are not able to rob
  32599. ** unused pages from other PCaches) but it also operates without a mutex,
  32600. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  32601. ** threadsafe, but is able recycle pages more efficient.
  32602. **
  32603. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  32604. ** PGroup which is the pcache1.grp global variable and its mutex is
  32605. ** SQLITE_MUTEX_STATIC_LRU.
  32606. */
  32607. struct PGroup {
  32608. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  32609. int nMaxPage; /* Sum of nMax for purgeable caches */
  32610. int nMinPage; /* Sum of nMin for purgeable caches */
  32611. int mxPinned; /* nMaxpage + 10 - nMinPage */
  32612. int nCurrentPage; /* Number of purgeable pages allocated */
  32613. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  32614. };
  32615. /* Each page cache is an instance of the following object. Every
  32616. ** open database file (including each in-memory database and each
  32617. ** temporary or transient database) has a single page cache which
  32618. ** is an instance of this object.
  32619. **
  32620. ** Pointers to structures of this type are cast and returned as
  32621. ** opaque sqlite3_pcache* handles.
  32622. */
  32623. struct PCache1 {
  32624. /* Cache configuration parameters. Page size (szPage) and the purgeable
  32625. ** flag (bPurgeable) are set when the cache is created. nMax may be
  32626. ** modified at any time by a call to the pcache1CacheSize() method.
  32627. ** The PGroup mutex must be held when accessing nMax.
  32628. */
  32629. PGroup *pGroup; /* PGroup this cache belongs to */
  32630. int szPage; /* Size of allocated pages in bytes */
  32631. int bPurgeable; /* True if cache is purgeable */
  32632. unsigned int nMin; /* Minimum number of pages reserved */
  32633. unsigned int nMax; /* Configured "cache_size" value */
  32634. unsigned int n90pct; /* nMax*9/10 */
  32635. /* Hash table of all pages. The following variables may only be accessed
  32636. ** when the accessor is holding the PGroup mutex.
  32637. */
  32638. unsigned int nRecyclable; /* Number of pages in the LRU list */
  32639. unsigned int nPage; /* Total number of pages in apHash */
  32640. unsigned int nHash; /* Number of slots in apHash[] */
  32641. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  32642. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  32643. };
  32644. /*
  32645. ** Each cache entry is represented by an instance of the following
  32646. ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
  32647. ** directly before this structure in memory (see the PGHDR1_TO_PAGE()
  32648. ** macro below).
  32649. */
  32650. struct PgHdr1 {
  32651. unsigned int iKey; /* Key value (page number) */
  32652. PgHdr1 *pNext; /* Next in hash table chain */
  32653. PCache1 *pCache; /* Cache that currently owns this page */
  32654. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  32655. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  32656. };
  32657. /*
  32658. ** Free slots in the allocator used to divide up the buffer provided using
  32659. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  32660. */
  32661. struct PgFreeslot {
  32662. PgFreeslot *pNext; /* Next free slot */
  32663. };
  32664. /*
  32665. ** Global data used by this cache.
  32666. */
  32667. static SQLITE_WSD struct PCacheGlobal {
  32668. PGroup grp; /* The global PGroup for mode (2) */
  32669. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  32670. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  32671. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  32672. ** The nFreeSlot and pFree values do require mutex protection.
  32673. */
  32674. int isInit; /* True if initialized */
  32675. int szSlot; /* Size of each free slot */
  32676. int nSlot; /* The number of pcache slots */
  32677. int nReserve; /* Try to keep nFreeSlot above this */
  32678. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  32679. /* Above requires no mutex. Use mutex below for variable that follow. */
  32680. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  32681. int nFreeSlot; /* Number of unused pcache slots */
  32682. PgFreeslot *pFree; /* Free page blocks */
  32683. /* The following value requires a mutex to change. We skip the mutex on
  32684. ** reading because (1) most platforms read a 32-bit integer atomically and
  32685. ** (2) even if an incorrect value is read, no great harm is done since this
  32686. ** is really just an optimization. */
  32687. int bUnderPressure; /* True if low on PAGECACHE memory */
  32688. } pcache1_g;
  32689. /*
  32690. ** All code in this file should access the global structure above via the
  32691. ** alias "pcache1". This ensures that the WSD emulation is used when
  32692. ** compiling for systems that do not support real WSD.
  32693. */
  32694. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  32695. /*
  32696. ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
  32697. ** bytes of data are located directly before it in memory (i.e. the total
  32698. ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
  32699. ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
  32700. ** an argument and returns a pointer to the associated block of szPage
  32701. ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
  32702. ** a pointer to a block of szPage bytes of data and the return value is
  32703. ** a pointer to the associated PgHdr1 structure.
  32704. **
  32705. ** assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
  32706. */
  32707. #define PGHDR1_TO_PAGE(p) (void*)(((char*)p) - p->pCache->szPage)
  32708. #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
  32709. /*
  32710. ** Macros to enter and leave the PCache LRU mutex.
  32711. */
  32712. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  32713. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  32714. /******************************************************************************/
  32715. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  32716. /*
  32717. ** This function is called during initialization if a static buffer is
  32718. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  32719. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  32720. ** enough to contain 'n' buffers of 'sz' bytes each.
  32721. **
  32722. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  32723. ** to be serialized already. There is no need for further mutexing.
  32724. */
  32725. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  32726. if( pcache1.isInit ){
  32727. PgFreeslot *p;
  32728. sz = ROUNDDOWN8(sz);
  32729. pcache1.szSlot = sz;
  32730. pcache1.nSlot = pcache1.nFreeSlot = n;
  32731. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  32732. pcache1.pStart = pBuf;
  32733. pcache1.pFree = 0;
  32734. pcache1.bUnderPressure = 0;
  32735. while( n-- ){
  32736. p = (PgFreeslot*)pBuf;
  32737. p->pNext = pcache1.pFree;
  32738. pcache1.pFree = p;
  32739. pBuf = (void*)&((char*)pBuf)[sz];
  32740. }
  32741. pcache1.pEnd = pBuf;
  32742. }
  32743. }
  32744. /*
  32745. ** Malloc function used within this file to allocate space from the buffer
  32746. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  32747. ** such buffer exists or there is no space left in it, this function falls
  32748. ** back to sqlite3Malloc().
  32749. **
  32750. ** Multiple threads can run this routine at the same time. Global variables
  32751. ** in pcache1 need to be protected via mutex.
  32752. */
  32753. static void *pcache1Alloc(int nByte){
  32754. void *p = 0;
  32755. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  32756. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  32757. if( nByte<=pcache1.szSlot ){
  32758. sqlite3_mutex_enter(pcache1.mutex);
  32759. p = (PgHdr1 *)pcache1.pFree;
  32760. if( p ){
  32761. pcache1.pFree = pcache1.pFree->pNext;
  32762. pcache1.nFreeSlot--;
  32763. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  32764. assert( pcache1.nFreeSlot>=0 );
  32765. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  32766. }
  32767. sqlite3_mutex_leave(pcache1.mutex);
  32768. }
  32769. if( p==0 ){
  32770. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  32771. ** it from sqlite3Malloc instead.
  32772. */
  32773. p = sqlite3Malloc(nByte);
  32774. if( p ){
  32775. int sz = sqlite3MallocSize(p);
  32776. sqlite3_mutex_enter(pcache1.mutex);
  32777. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  32778. sqlite3_mutex_leave(pcache1.mutex);
  32779. }
  32780. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  32781. }
  32782. return p;
  32783. }
  32784. /*
  32785. ** Free an allocated buffer obtained from pcache1Alloc().
  32786. */
  32787. static void pcache1Free(void *p){
  32788. if( p==0 ) return;
  32789. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  32790. PgFreeslot *pSlot;
  32791. sqlite3_mutex_enter(pcache1.mutex);
  32792. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  32793. pSlot = (PgFreeslot*)p;
  32794. pSlot->pNext = pcache1.pFree;
  32795. pcache1.pFree = pSlot;
  32796. pcache1.nFreeSlot++;
  32797. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  32798. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  32799. sqlite3_mutex_leave(pcache1.mutex);
  32800. }else{
  32801. int iSize;
  32802. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  32803. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  32804. iSize = sqlite3MallocSize(p);
  32805. sqlite3_mutex_enter(pcache1.mutex);
  32806. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
  32807. sqlite3_mutex_leave(pcache1.mutex);
  32808. sqlite3_free(p);
  32809. }
  32810. }
  32811. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  32812. /*
  32813. ** Return the size of a pcache allocation
  32814. */
  32815. static int pcache1MemSize(void *p){
  32816. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  32817. return pcache1.szSlot;
  32818. }else{
  32819. int iSize;
  32820. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  32821. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  32822. iSize = sqlite3MallocSize(p);
  32823. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  32824. return iSize;
  32825. }
  32826. }
  32827. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  32828. /*
  32829. ** Allocate a new page object initially associated with cache pCache.
  32830. */
  32831. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  32832. int nByte = sizeof(PgHdr1) + pCache->szPage;
  32833. void *pPg = pcache1Alloc(nByte);
  32834. PgHdr1 *p;
  32835. if( pPg ){
  32836. p = PAGE_TO_PGHDR1(pCache, pPg);
  32837. if( pCache->bPurgeable ){
  32838. pCache->pGroup->nCurrentPage++;
  32839. }
  32840. }else{
  32841. p = 0;
  32842. }
  32843. return p;
  32844. }
  32845. /*
  32846. ** Free a page object allocated by pcache1AllocPage().
  32847. **
  32848. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  32849. ** that the current implementation happens to never call this routine
  32850. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  32851. */
  32852. static void pcache1FreePage(PgHdr1 *p){
  32853. if( ALWAYS(p) ){
  32854. PCache1 *pCache = p->pCache;
  32855. if( pCache->bPurgeable ){
  32856. pCache->pGroup->nCurrentPage--;
  32857. }
  32858. pcache1Free(PGHDR1_TO_PAGE(p));
  32859. }
  32860. }
  32861. /*
  32862. ** Malloc function used by SQLite to obtain space from the buffer configured
  32863. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  32864. ** exists, this function falls back to sqlite3Malloc().
  32865. */
  32866. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  32867. return pcache1Alloc(sz);
  32868. }
  32869. /*
  32870. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  32871. */
  32872. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  32873. pcache1Free(p);
  32874. }
  32875. /*
  32876. ** Return true if it desirable to avoid allocating a new page cache
  32877. ** entry.
  32878. **
  32879. ** If memory was allocated specifically to the page cache using
  32880. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  32881. ** it is desirable to avoid allocating a new page cache entry because
  32882. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  32883. ** for all page cache needs and we should not need to spill the
  32884. ** allocation onto the heap.
  32885. **
  32886. ** Or, the heap is used for all page cache memory put the heap is
  32887. ** under memory pressure, then again it is desirable to avoid
  32888. ** allocating a new page cache entry in order to avoid stressing
  32889. ** the heap even further.
  32890. */
  32891. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  32892. if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
  32893. return pcache1.bUnderPressure;
  32894. }else{
  32895. return sqlite3HeapNearlyFull();
  32896. }
  32897. }
  32898. /******************************************************************************/
  32899. /******** General Implementation Functions ************************************/
  32900. /*
  32901. ** This function is used to resize the hash table used by the cache passed
  32902. ** as the first argument.
  32903. **
  32904. ** The PCache mutex must be held when this function is called.
  32905. */
  32906. static int pcache1ResizeHash(PCache1 *p){
  32907. PgHdr1 **apNew;
  32908. unsigned int nNew;
  32909. unsigned int i;
  32910. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  32911. nNew = p->nHash*2;
  32912. if( nNew<256 ){
  32913. nNew = 256;
  32914. }
  32915. pcache1LeaveMutex(p->pGroup);
  32916. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  32917. apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
  32918. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  32919. pcache1EnterMutex(p->pGroup);
  32920. if( apNew ){
  32921. memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
  32922. for(i=0; i<p->nHash; i++){
  32923. PgHdr1 *pPage;
  32924. PgHdr1 *pNext = p->apHash[i];
  32925. while( (pPage = pNext)!=0 ){
  32926. unsigned int h = pPage->iKey % nNew;
  32927. pNext = pPage->pNext;
  32928. pPage->pNext = apNew[h];
  32929. apNew[h] = pPage;
  32930. }
  32931. }
  32932. sqlite3_free(p->apHash);
  32933. p->apHash = apNew;
  32934. p->nHash = nNew;
  32935. }
  32936. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  32937. }
  32938. /*
  32939. ** This function is used internally to remove the page pPage from the
  32940. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  32941. ** LRU list, then this function is a no-op.
  32942. **
  32943. ** The PGroup mutex must be held when this function is called.
  32944. **
  32945. ** If pPage is NULL then this routine is a no-op.
  32946. */
  32947. static void pcache1PinPage(PgHdr1 *pPage){
  32948. PCache1 *pCache;
  32949. PGroup *pGroup;
  32950. if( pPage==0 ) return;
  32951. pCache = pPage->pCache;
  32952. pGroup = pCache->pGroup;
  32953. assert( sqlite3_mutex_held(pGroup->mutex) );
  32954. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  32955. if( pPage->pLruPrev ){
  32956. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  32957. }
  32958. if( pPage->pLruNext ){
  32959. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  32960. }
  32961. if( pGroup->pLruHead==pPage ){
  32962. pGroup->pLruHead = pPage->pLruNext;
  32963. }
  32964. if( pGroup->pLruTail==pPage ){
  32965. pGroup->pLruTail = pPage->pLruPrev;
  32966. }
  32967. pPage->pLruNext = 0;
  32968. pPage->pLruPrev = 0;
  32969. pPage->pCache->nRecyclable--;
  32970. }
  32971. }
  32972. /*
  32973. ** Remove the page supplied as an argument from the hash table
  32974. ** (PCache1.apHash structure) that it is currently stored in.
  32975. **
  32976. ** The PGroup mutex must be held when this function is called.
  32977. */
  32978. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  32979. unsigned int h;
  32980. PCache1 *pCache = pPage->pCache;
  32981. PgHdr1 **pp;
  32982. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  32983. h = pPage->iKey % pCache->nHash;
  32984. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  32985. *pp = (*pp)->pNext;
  32986. pCache->nPage--;
  32987. }
  32988. /*
  32989. ** If there are currently more than nMaxPage pages allocated, try
  32990. ** to recycle pages to reduce the number allocated to nMaxPage.
  32991. */
  32992. static void pcache1EnforceMaxPage(PGroup *pGroup){
  32993. assert( sqlite3_mutex_held(pGroup->mutex) );
  32994. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  32995. PgHdr1 *p = pGroup->pLruTail;
  32996. assert( p->pCache->pGroup==pGroup );
  32997. pcache1PinPage(p);
  32998. pcache1RemoveFromHash(p);
  32999. pcache1FreePage(p);
  33000. }
  33001. }
  33002. /*
  33003. ** Discard all pages from cache pCache with a page number (key value)
  33004. ** greater than or equal to iLimit. Any pinned pages that meet this
  33005. ** criteria are unpinned before they are discarded.
  33006. **
  33007. ** The PCache mutex must be held when this function is called.
  33008. */
  33009. static void pcache1TruncateUnsafe(
  33010. PCache1 *pCache, /* The cache to truncate */
  33011. unsigned int iLimit /* Drop pages with this pgno or larger */
  33012. ){
  33013. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  33014. unsigned int h;
  33015. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  33016. for(h=0; h<pCache->nHash; h++){
  33017. PgHdr1 **pp = &pCache->apHash[h];
  33018. PgHdr1 *pPage;
  33019. while( (pPage = *pp)!=0 ){
  33020. if( pPage->iKey>=iLimit ){
  33021. pCache->nPage--;
  33022. *pp = pPage->pNext;
  33023. pcache1PinPage(pPage);
  33024. pcache1FreePage(pPage);
  33025. }else{
  33026. pp = &pPage->pNext;
  33027. TESTONLY( nPage++; )
  33028. }
  33029. }
  33030. }
  33031. assert( pCache->nPage==nPage );
  33032. }
  33033. /******************************************************************************/
  33034. /******** sqlite3_pcache Methods **********************************************/
  33035. /*
  33036. ** Implementation of the sqlite3_pcache.xInit method.
  33037. */
  33038. static int pcache1Init(void *NotUsed){
  33039. UNUSED_PARAMETER(NotUsed);
  33040. assert( pcache1.isInit==0 );
  33041. memset(&pcache1, 0, sizeof(pcache1));
  33042. if( sqlite3GlobalConfig.bCoreMutex ){
  33043. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  33044. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  33045. }
  33046. pcache1.grp.mxPinned = 10;
  33047. pcache1.isInit = 1;
  33048. return SQLITE_OK;
  33049. }
  33050. /*
  33051. ** Implementation of the sqlite3_pcache.xShutdown method.
  33052. ** Note that the static mutex allocated in xInit does
  33053. ** not need to be freed.
  33054. */
  33055. static void pcache1Shutdown(void *NotUsed){
  33056. UNUSED_PARAMETER(NotUsed);
  33057. assert( pcache1.isInit!=0 );
  33058. memset(&pcache1, 0, sizeof(pcache1));
  33059. }
  33060. /*
  33061. ** Implementation of the sqlite3_pcache.xCreate method.
  33062. **
  33063. ** Allocate a new cache.
  33064. */
  33065. static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
  33066. PCache1 *pCache; /* The newly created page cache */
  33067. PGroup *pGroup; /* The group the new page cache will belong to */
  33068. int sz; /* Bytes of memory required to allocate the new cache */
  33069. /*
  33070. ** The seperateCache variable is true if each PCache has its own private
  33071. ** PGroup. In other words, separateCache is true for mode (1) where no
  33072. ** mutexing is required.
  33073. **
  33074. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  33075. **
  33076. ** * Always use a unified cache in single-threaded applications
  33077. **
  33078. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  33079. ** use separate caches (mode-1)
  33080. */
  33081. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  33082. const int separateCache = 0;
  33083. #else
  33084. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  33085. #endif
  33086. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  33087. pCache = (PCache1 *)sqlite3_malloc(sz);
  33088. if( pCache ){
  33089. memset(pCache, 0, sz);
  33090. if( separateCache ){
  33091. pGroup = (PGroup*)&pCache[1];
  33092. pGroup->mxPinned = 10;
  33093. }else{
  33094. pGroup = &pcache1_g.grp;
  33095. }
  33096. pCache->pGroup = pGroup;
  33097. pCache->szPage = szPage;
  33098. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  33099. if( bPurgeable ){
  33100. pCache->nMin = 10;
  33101. pcache1EnterMutex(pGroup);
  33102. pGroup->nMinPage += pCache->nMin;
  33103. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  33104. pcache1LeaveMutex(pGroup);
  33105. }
  33106. }
  33107. return (sqlite3_pcache *)pCache;
  33108. }
  33109. /*
  33110. ** Implementation of the sqlite3_pcache.xCachesize method.
  33111. **
  33112. ** Configure the cache_size limit for a cache.
  33113. */
  33114. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  33115. PCache1 *pCache = (PCache1 *)p;
  33116. if( pCache->bPurgeable ){
  33117. PGroup *pGroup = pCache->pGroup;
  33118. pcache1EnterMutex(pGroup);
  33119. pGroup->nMaxPage += (nMax - pCache->nMax);
  33120. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  33121. pCache->nMax = nMax;
  33122. pCache->n90pct = pCache->nMax*9/10;
  33123. pcache1EnforceMaxPage(pGroup);
  33124. pcache1LeaveMutex(pGroup);
  33125. }
  33126. }
  33127. /*
  33128. ** Implementation of the sqlite3_pcache.xPagecount method.
  33129. */
  33130. static int pcache1Pagecount(sqlite3_pcache *p){
  33131. int n;
  33132. PCache1 *pCache = (PCache1*)p;
  33133. pcache1EnterMutex(pCache->pGroup);
  33134. n = pCache->nPage;
  33135. pcache1LeaveMutex(pCache->pGroup);
  33136. return n;
  33137. }
  33138. /*
  33139. ** Implementation of the sqlite3_pcache.xFetch method.
  33140. **
  33141. ** Fetch a page by key value.
  33142. **
  33143. ** Whether or not a new page may be allocated by this function depends on
  33144. ** the value of the createFlag argument. 0 means do not allocate a new
  33145. ** page. 1 means allocate a new page if space is easily available. 2
  33146. ** means to try really hard to allocate a new page.
  33147. **
  33148. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  33149. ** database) there is really no difference between createFlag 1 and 2. So
  33150. ** the calling function (pcache.c) will never have a createFlag of 1 on
  33151. ** a non-purgable cache.
  33152. **
  33153. ** There are three different approaches to obtaining space for a page,
  33154. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  33155. **
  33156. ** 1. Regardless of the value of createFlag, the cache is searched for a
  33157. ** copy of the requested page. If one is found, it is returned.
  33158. **
  33159. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  33160. ** returned.
  33161. **
  33162. ** 3. If createFlag is 1, and the page is not already in the cache, then
  33163. ** return NULL (do not allocate a new page) if any of the following
  33164. ** conditions are true:
  33165. **
  33166. ** (a) the number of pages pinned by the cache is greater than
  33167. ** PCache1.nMax, or
  33168. **
  33169. ** (b) the number of pages pinned by the cache is greater than
  33170. ** the sum of nMax for all purgeable caches, less the sum of
  33171. ** nMin for all other purgeable caches, or
  33172. **
  33173. ** 4. If none of the first three conditions apply and the cache is marked
  33174. ** as purgeable, and if one of the following is true:
  33175. **
  33176. ** (a) The number of pages allocated for the cache is already
  33177. ** PCache1.nMax, or
  33178. **
  33179. ** (b) The number of pages allocated for all purgeable caches is
  33180. ** already equal to or greater than the sum of nMax for all
  33181. ** purgeable caches,
  33182. **
  33183. ** (c) The system is under memory pressure and wants to avoid
  33184. ** unnecessary pages cache entry allocations
  33185. **
  33186. ** then attempt to recycle a page from the LRU list. If it is the right
  33187. ** size, return the recycled buffer. Otherwise, free the buffer and
  33188. ** proceed to step 5.
  33189. **
  33190. ** 5. Otherwise, allocate and return a new page buffer.
  33191. */
  33192. static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
  33193. int nPinned;
  33194. PCache1 *pCache = (PCache1 *)p;
  33195. PGroup *pGroup;
  33196. PgHdr1 *pPage = 0;
  33197. assert( pCache->bPurgeable || createFlag!=1 );
  33198. assert( pCache->bPurgeable || pCache->nMin==0 );
  33199. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  33200. assert( pCache->nMin==0 || pCache->bPurgeable );
  33201. pcache1EnterMutex(pGroup = pCache->pGroup);
  33202. /* Step 1: Search the hash table for an existing entry. */
  33203. if( pCache->nHash>0 ){
  33204. unsigned int h = iKey % pCache->nHash;
  33205. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  33206. }
  33207. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  33208. if( pPage || createFlag==0 ){
  33209. pcache1PinPage(pPage);
  33210. goto fetch_out;
  33211. }
  33212. /* The pGroup local variable will normally be initialized by the
  33213. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  33214. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  33215. ** local variable here. Delaying the initialization of pGroup is an
  33216. ** optimization: The common case is to exit the module before reaching
  33217. ** this point.
  33218. */
  33219. #ifdef SQLITE_MUTEX_OMIT
  33220. pGroup = pCache->pGroup;
  33221. #endif
  33222. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  33223. nPinned = pCache->nPage - pCache->nRecyclable;
  33224. assert( nPinned>=0 );
  33225. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  33226. assert( pCache->n90pct == pCache->nMax*9/10 );
  33227. if( createFlag==1 && (
  33228. nPinned>=pGroup->mxPinned
  33229. || nPinned>=(int)pCache->n90pct
  33230. || pcache1UnderMemoryPressure(pCache)
  33231. )){
  33232. goto fetch_out;
  33233. }
  33234. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  33235. goto fetch_out;
  33236. }
  33237. /* Step 4. Try to recycle a page. */
  33238. if( pCache->bPurgeable && pGroup->pLruTail && (
  33239. (pCache->nPage+1>=pCache->nMax)
  33240. || pGroup->nCurrentPage>=pGroup->nMaxPage
  33241. || pcache1UnderMemoryPressure(pCache)
  33242. )){
  33243. PCache1 *pOtherCache;
  33244. pPage = pGroup->pLruTail;
  33245. pcache1RemoveFromHash(pPage);
  33246. pcache1PinPage(pPage);
  33247. if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
  33248. pcache1FreePage(pPage);
  33249. pPage = 0;
  33250. }else{
  33251. pGroup->nCurrentPage -=
  33252. (pOtherCache->bPurgeable - pCache->bPurgeable);
  33253. }
  33254. }
  33255. /* Step 5. If a usable page buffer has still not been found,
  33256. ** attempt to allocate a new one.
  33257. */
  33258. if( !pPage ){
  33259. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  33260. pcache1LeaveMutex(pGroup);
  33261. pPage = pcache1AllocPage(pCache);
  33262. pcache1EnterMutex(pGroup);
  33263. if( createFlag==1 ) sqlite3EndBenignMalloc();
  33264. }
  33265. if( pPage ){
  33266. unsigned int h = iKey % pCache->nHash;
  33267. pCache->nPage++;
  33268. pPage->iKey = iKey;
  33269. pPage->pNext = pCache->apHash[h];
  33270. pPage->pCache = pCache;
  33271. pPage->pLruPrev = 0;
  33272. pPage->pLruNext = 0;
  33273. *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
  33274. pCache->apHash[h] = pPage;
  33275. }
  33276. fetch_out:
  33277. if( pPage && iKey>pCache->iMaxKey ){
  33278. pCache->iMaxKey = iKey;
  33279. }
  33280. pcache1LeaveMutex(pGroup);
  33281. return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
  33282. }
  33283. /*
  33284. ** Implementation of the sqlite3_pcache.xUnpin method.
  33285. **
  33286. ** Mark a page as unpinned (eligible for asynchronous recycling).
  33287. */
  33288. static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
  33289. PCache1 *pCache = (PCache1 *)p;
  33290. PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
  33291. PGroup *pGroup = pCache->pGroup;
  33292. assert( pPage->pCache==pCache );
  33293. pcache1EnterMutex(pGroup);
  33294. /* It is an error to call this function if the page is already
  33295. ** part of the PGroup LRU list.
  33296. */
  33297. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  33298. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  33299. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  33300. pcache1RemoveFromHash(pPage);
  33301. pcache1FreePage(pPage);
  33302. }else{
  33303. /* Add the page to the PGroup LRU list. */
  33304. if( pGroup->pLruHead ){
  33305. pGroup->pLruHead->pLruPrev = pPage;
  33306. pPage->pLruNext = pGroup->pLruHead;
  33307. pGroup->pLruHead = pPage;
  33308. }else{
  33309. pGroup->pLruTail = pPage;
  33310. pGroup->pLruHead = pPage;
  33311. }
  33312. pCache->nRecyclable++;
  33313. }
  33314. pcache1LeaveMutex(pCache->pGroup);
  33315. }
  33316. /*
  33317. ** Implementation of the sqlite3_pcache.xRekey method.
  33318. */
  33319. static void pcache1Rekey(
  33320. sqlite3_pcache *p,
  33321. void *pPg,
  33322. unsigned int iOld,
  33323. unsigned int iNew
  33324. ){
  33325. PCache1 *pCache = (PCache1 *)p;
  33326. PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
  33327. PgHdr1 **pp;
  33328. unsigned int h;
  33329. assert( pPage->iKey==iOld );
  33330. assert( pPage->pCache==pCache );
  33331. pcache1EnterMutex(pCache->pGroup);
  33332. h = iOld%pCache->nHash;
  33333. pp = &pCache->apHash[h];
  33334. while( (*pp)!=pPage ){
  33335. pp = &(*pp)->pNext;
  33336. }
  33337. *pp = pPage->pNext;
  33338. h = iNew%pCache->nHash;
  33339. pPage->iKey = iNew;
  33340. pPage->pNext = pCache->apHash[h];
  33341. pCache->apHash[h] = pPage;
  33342. if( iNew>pCache->iMaxKey ){
  33343. pCache->iMaxKey = iNew;
  33344. }
  33345. pcache1LeaveMutex(pCache->pGroup);
  33346. }
  33347. /*
  33348. ** Implementation of the sqlite3_pcache.xTruncate method.
  33349. **
  33350. ** Discard all unpinned pages in the cache with a page number equal to
  33351. ** or greater than parameter iLimit. Any pinned pages with a page number
  33352. ** equal to or greater than iLimit are implicitly unpinned.
  33353. */
  33354. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  33355. PCache1 *pCache = (PCache1 *)p;
  33356. pcache1EnterMutex(pCache->pGroup);
  33357. if( iLimit<=pCache->iMaxKey ){
  33358. pcache1TruncateUnsafe(pCache, iLimit);
  33359. pCache->iMaxKey = iLimit-1;
  33360. }
  33361. pcache1LeaveMutex(pCache->pGroup);
  33362. }
  33363. /*
  33364. ** Implementation of the sqlite3_pcache.xDestroy method.
  33365. **
  33366. ** Destroy a cache allocated using pcache1Create().
  33367. */
  33368. static void pcache1Destroy(sqlite3_pcache *p){
  33369. PCache1 *pCache = (PCache1 *)p;
  33370. PGroup *pGroup = pCache->pGroup;
  33371. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  33372. pcache1EnterMutex(pGroup);
  33373. pcache1TruncateUnsafe(pCache, 0);
  33374. pGroup->nMaxPage -= pCache->nMax;
  33375. pGroup->nMinPage -= pCache->nMin;
  33376. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  33377. pcache1EnforceMaxPage(pGroup);
  33378. pcache1LeaveMutex(pGroup);
  33379. sqlite3_free(pCache->apHash);
  33380. sqlite3_free(pCache);
  33381. }
  33382. /*
  33383. ** This function is called during initialization (sqlite3_initialize()) to
  33384. ** install the default pluggable cache module, assuming the user has not
  33385. ** already provided an alternative.
  33386. */
  33387. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  33388. static const sqlite3_pcache_methods defaultMethods = {
  33389. 0, /* pArg */
  33390. pcache1Init, /* xInit */
  33391. pcache1Shutdown, /* xShutdown */
  33392. pcache1Create, /* xCreate */
  33393. pcache1Cachesize, /* xCachesize */
  33394. pcache1Pagecount, /* xPagecount */
  33395. pcache1Fetch, /* xFetch */
  33396. pcache1Unpin, /* xUnpin */
  33397. pcache1Rekey, /* xRekey */
  33398. pcache1Truncate, /* xTruncate */
  33399. pcache1Destroy /* xDestroy */
  33400. };
  33401. sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
  33402. }
  33403. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  33404. /*
  33405. ** This function is called to free superfluous dynamically allocated memory
  33406. ** held by the pager system. Memory in use by any SQLite pager allocated
  33407. ** by the current thread may be sqlite3_free()ed.
  33408. **
  33409. ** nReq is the number of bytes of memory required. Once this much has
  33410. ** been released, the function returns. The return value is the total number
  33411. ** of bytes of memory released.
  33412. */
  33413. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  33414. int nFree = 0;
  33415. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  33416. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  33417. if( pcache1.pStart==0 ){
  33418. PgHdr1 *p;
  33419. pcache1EnterMutex(&pcache1.grp);
  33420. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  33421. nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
  33422. pcache1PinPage(p);
  33423. pcache1RemoveFromHash(p);
  33424. pcache1FreePage(p);
  33425. }
  33426. pcache1LeaveMutex(&pcache1.grp);
  33427. }
  33428. return nFree;
  33429. }
  33430. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  33431. #ifdef SQLITE_TEST
  33432. /*
  33433. ** This function is used by test procedures to inspect the internal state
  33434. ** of the global cache.
  33435. */
  33436. SQLITE_PRIVATE void sqlite3PcacheStats(
  33437. int *pnCurrent, /* OUT: Total number of pages cached */
  33438. int *pnMax, /* OUT: Global maximum cache size */
  33439. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  33440. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  33441. ){
  33442. PgHdr1 *p;
  33443. int nRecyclable = 0;
  33444. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  33445. nRecyclable++;
  33446. }
  33447. *pnCurrent = pcache1.grp.nCurrentPage;
  33448. *pnMax = pcache1.grp.nMaxPage;
  33449. *pnMin = pcache1.grp.nMinPage;
  33450. *pnRecyclable = nRecyclable;
  33451. }
  33452. #endif
  33453. /************** End of pcache1.c *********************************************/
  33454. /************** Begin file rowset.c ******************************************/
  33455. /*
  33456. ** 2008 December 3
  33457. **
  33458. ** The author disclaims copyright to this source code. In place of
  33459. ** a legal notice, here is a blessing:
  33460. **
  33461. ** May you do good and not evil.
  33462. ** May you find forgiveness for yourself and forgive others.
  33463. ** May you share freely, never taking more than you give.
  33464. **
  33465. *************************************************************************
  33466. **
  33467. ** This module implements an object we call a "RowSet".
  33468. **
  33469. ** The RowSet object is a collection of rowids. Rowids
  33470. ** are inserted into the RowSet in an arbitrary order. Inserts
  33471. ** can be intermixed with tests to see if a given rowid has been
  33472. ** previously inserted into the RowSet.
  33473. **
  33474. ** After all inserts are finished, it is possible to extract the
  33475. ** elements of the RowSet in sorted order. Once this extraction
  33476. ** process has started, no new elements may be inserted.
  33477. **
  33478. ** Hence, the primitive operations for a RowSet are:
  33479. **
  33480. ** CREATE
  33481. ** INSERT
  33482. ** TEST
  33483. ** SMALLEST
  33484. ** DESTROY
  33485. **
  33486. ** The CREATE and DESTROY primitives are the constructor and destructor,
  33487. ** obviously. The INSERT primitive adds a new element to the RowSet.
  33488. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  33489. ** extracts the least value from the RowSet.
  33490. **
  33491. ** The INSERT primitive might allocate additional memory. Memory is
  33492. ** allocated in chunks so most INSERTs do no allocation. There is an
  33493. ** upper bound on the size of allocated memory. No memory is freed
  33494. ** until DESTROY.
  33495. **
  33496. ** The TEST primitive includes a "batch" number. The TEST primitive
  33497. ** will only see elements that were inserted before the last change
  33498. ** in the batch number. In other words, if an INSERT occurs between
  33499. ** two TESTs where the TESTs have the same batch nubmer, then the
  33500. ** value added by the INSERT will not be visible to the second TEST.
  33501. ** The initial batch number is zero, so if the very first TEST contains
  33502. ** a non-zero batch number, it will see all prior INSERTs.
  33503. **
  33504. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  33505. ** that is attempted.
  33506. **
  33507. ** The cost of an INSERT is roughly constant. (Sometime new memory
  33508. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  33509. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  33510. ** The cost of a TEST using the same batch number is O(logN). The cost
  33511. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  33512. ** primitives are constant time. The cost of DESTROY is O(N).
  33513. **
  33514. ** There is an added cost of O(N) when switching between TEST and
  33515. ** SMALLEST primitives.
  33516. */
  33517. /*
  33518. ** Target size for allocation chunks.
  33519. */
  33520. #define ROWSET_ALLOCATION_SIZE 1024
  33521. /*
  33522. ** The number of rowset entries per allocation chunk.
  33523. */
  33524. #define ROWSET_ENTRY_PER_CHUNK \
  33525. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  33526. /*
  33527. ** Each entry in a RowSet is an instance of the following object.
  33528. */
  33529. struct RowSetEntry {
  33530. i64 v; /* ROWID value for this entry */
  33531. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  33532. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  33533. };
  33534. /*
  33535. ** RowSetEntry objects are allocated in large chunks (instances of the
  33536. ** following structure) to reduce memory allocation overhead. The
  33537. ** chunks are kept on a linked list so that they can be deallocated
  33538. ** when the RowSet is destroyed.
  33539. */
  33540. struct RowSetChunk {
  33541. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  33542. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  33543. };
  33544. /*
  33545. ** A RowSet in an instance of the following structure.
  33546. **
  33547. ** A typedef of this structure if found in sqliteInt.h.
  33548. */
  33549. struct RowSet {
  33550. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  33551. sqlite3 *db; /* The database connection */
  33552. struct RowSetEntry *pEntry; /* List of entries using pRight */
  33553. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  33554. struct RowSetEntry *pFresh; /* Source of new entry objects */
  33555. struct RowSetEntry *pTree; /* Binary tree of entries */
  33556. u16 nFresh; /* Number of objects on pFresh */
  33557. u8 isSorted; /* True if pEntry is sorted */
  33558. u8 iBatch; /* Current insert batch */
  33559. };
  33560. /*
  33561. ** Turn bulk memory into a RowSet object. N bytes of memory
  33562. ** are available at pSpace. The db pointer is used as a memory context
  33563. ** for any subsequent allocations that need to occur.
  33564. ** Return a pointer to the new RowSet object.
  33565. **
  33566. ** It must be the case that N is sufficient to make a Rowset. If not
  33567. ** an assertion fault occurs.
  33568. **
  33569. ** If N is larger than the minimum, use the surplus as an initial
  33570. ** allocation of entries available to be filled.
  33571. */
  33572. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  33573. RowSet *p;
  33574. assert( N >= ROUND8(sizeof(*p)) );
  33575. p = pSpace;
  33576. p->pChunk = 0;
  33577. p->db = db;
  33578. p->pEntry = 0;
  33579. p->pLast = 0;
  33580. p->pTree = 0;
  33581. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  33582. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  33583. p->isSorted = 1;
  33584. p->iBatch = 0;
  33585. return p;
  33586. }
  33587. /*
  33588. ** Deallocate all chunks from a RowSet. This frees all memory that
  33589. ** the RowSet has allocated over its lifetime. This routine is
  33590. ** the destructor for the RowSet.
  33591. */
  33592. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  33593. struct RowSetChunk *pChunk, *pNextChunk;
  33594. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  33595. pNextChunk = pChunk->pNextChunk;
  33596. sqlite3DbFree(p->db, pChunk);
  33597. }
  33598. p->pChunk = 0;
  33599. p->nFresh = 0;
  33600. p->pEntry = 0;
  33601. p->pLast = 0;
  33602. p->pTree = 0;
  33603. p->isSorted = 1;
  33604. }
  33605. /*
  33606. ** Insert a new value into a RowSet.
  33607. **
  33608. ** The mallocFailed flag of the database connection is set if a
  33609. ** memory allocation fails.
  33610. */
  33611. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  33612. struct RowSetEntry *pEntry; /* The new entry */
  33613. struct RowSetEntry *pLast; /* The last prior entry */
  33614. assert( p!=0 );
  33615. if( p->nFresh==0 ){
  33616. struct RowSetChunk *pNew;
  33617. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  33618. if( pNew==0 ){
  33619. return;
  33620. }
  33621. pNew->pNextChunk = p->pChunk;
  33622. p->pChunk = pNew;
  33623. p->pFresh = pNew->aEntry;
  33624. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  33625. }
  33626. pEntry = p->pFresh++;
  33627. p->nFresh--;
  33628. pEntry->v = rowid;
  33629. pEntry->pRight = 0;
  33630. pLast = p->pLast;
  33631. if( pLast ){
  33632. if( p->isSorted && rowid<=pLast->v ){
  33633. p->isSorted = 0;
  33634. }
  33635. pLast->pRight = pEntry;
  33636. }else{
  33637. assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
  33638. p->pEntry = pEntry;
  33639. }
  33640. p->pLast = pEntry;
  33641. }
  33642. /*
  33643. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  33644. **
  33645. ** The input lists are connected via pRight pointers and are
  33646. ** assumed to each already be in sorted order.
  33647. */
  33648. static struct RowSetEntry *rowSetMerge(
  33649. struct RowSetEntry *pA, /* First sorted list to be merged */
  33650. struct RowSetEntry *pB /* Second sorted list to be merged */
  33651. ){
  33652. struct RowSetEntry head;
  33653. struct RowSetEntry *pTail;
  33654. pTail = &head;
  33655. while( pA && pB ){
  33656. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  33657. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  33658. if( pA->v<pB->v ){
  33659. pTail->pRight = pA;
  33660. pA = pA->pRight;
  33661. pTail = pTail->pRight;
  33662. }else if( pB->v<pA->v ){
  33663. pTail->pRight = pB;
  33664. pB = pB->pRight;
  33665. pTail = pTail->pRight;
  33666. }else{
  33667. pA = pA->pRight;
  33668. }
  33669. }
  33670. if( pA ){
  33671. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  33672. pTail->pRight = pA;
  33673. }else{
  33674. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  33675. pTail->pRight = pB;
  33676. }
  33677. return head.pRight;
  33678. }
  33679. /*
  33680. ** Sort all elements on the pEntry list of the RowSet into ascending order.
  33681. */
  33682. static void rowSetSort(RowSet *p){
  33683. unsigned int i;
  33684. struct RowSetEntry *pEntry;
  33685. struct RowSetEntry *aBucket[40];
  33686. assert( p->isSorted==0 );
  33687. memset(aBucket, 0, sizeof(aBucket));
  33688. while( p->pEntry ){
  33689. pEntry = p->pEntry;
  33690. p->pEntry = pEntry->pRight;
  33691. pEntry->pRight = 0;
  33692. for(i=0; aBucket[i]; i++){
  33693. pEntry = rowSetMerge(aBucket[i], pEntry);
  33694. aBucket[i] = 0;
  33695. }
  33696. aBucket[i] = pEntry;
  33697. }
  33698. pEntry = 0;
  33699. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  33700. pEntry = rowSetMerge(pEntry, aBucket[i]);
  33701. }
  33702. p->pEntry = pEntry;
  33703. p->pLast = 0;
  33704. p->isSorted = 1;
  33705. }
  33706. /*
  33707. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  33708. ** Convert this tree into a linked list connected by the pRight pointers
  33709. ** and return pointers to the first and last elements of the new list.
  33710. */
  33711. static void rowSetTreeToList(
  33712. struct RowSetEntry *pIn, /* Root of the input tree */
  33713. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  33714. struct RowSetEntry **ppLast /* Write tail of the output list here */
  33715. ){
  33716. assert( pIn!=0 );
  33717. if( pIn->pLeft ){
  33718. struct RowSetEntry *p;
  33719. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  33720. p->pRight = pIn;
  33721. }else{
  33722. *ppFirst = pIn;
  33723. }
  33724. if( pIn->pRight ){
  33725. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  33726. }else{
  33727. *ppLast = pIn;
  33728. }
  33729. assert( (*ppLast)->pRight==0 );
  33730. }
  33731. /*
  33732. ** Convert a sorted list of elements (connected by pRight) into a binary
  33733. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  33734. ** node taken from the head of *ppList. A depth of 2 means a tree with
  33735. ** three nodes. And so forth.
  33736. **
  33737. ** Use as many entries from the input list as required and update the
  33738. ** *ppList to point to the unused elements of the list. If the input
  33739. ** list contains too few elements, then construct an incomplete tree
  33740. ** and leave *ppList set to NULL.
  33741. **
  33742. ** Return a pointer to the root of the constructed binary tree.
  33743. */
  33744. static struct RowSetEntry *rowSetNDeepTree(
  33745. struct RowSetEntry **ppList,
  33746. int iDepth
  33747. ){
  33748. struct RowSetEntry *p; /* Root of the new tree */
  33749. struct RowSetEntry *pLeft; /* Left subtree */
  33750. if( *ppList==0 ){
  33751. return 0;
  33752. }
  33753. if( iDepth==1 ){
  33754. p = *ppList;
  33755. *ppList = p->pRight;
  33756. p->pLeft = p->pRight = 0;
  33757. return p;
  33758. }
  33759. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  33760. p = *ppList;
  33761. if( p==0 ){
  33762. return pLeft;
  33763. }
  33764. p->pLeft = pLeft;
  33765. *ppList = p->pRight;
  33766. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  33767. return p;
  33768. }
  33769. /*
  33770. ** Convert a sorted list of elements into a binary tree. Make the tree
  33771. ** as deep as it needs to be in order to contain the entire list.
  33772. */
  33773. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  33774. int iDepth; /* Depth of the tree so far */
  33775. struct RowSetEntry *p; /* Current tree root */
  33776. struct RowSetEntry *pLeft; /* Left subtree */
  33777. assert( pList!=0 );
  33778. p = pList;
  33779. pList = p->pRight;
  33780. p->pLeft = p->pRight = 0;
  33781. for(iDepth=1; pList; iDepth++){
  33782. pLeft = p;
  33783. p = pList;
  33784. pList = p->pRight;
  33785. p->pLeft = pLeft;
  33786. p->pRight = rowSetNDeepTree(&pList, iDepth);
  33787. }
  33788. return p;
  33789. }
  33790. /*
  33791. ** Convert the list in p->pEntry into a sorted list if it is not
  33792. ** sorted already. If there is a binary tree on p->pTree, then
  33793. ** convert it into a list too and merge it into the p->pEntry list.
  33794. */
  33795. static void rowSetToList(RowSet *p){
  33796. if( !p->isSorted ){
  33797. rowSetSort(p);
  33798. }
  33799. if( p->pTree ){
  33800. struct RowSetEntry *pHead, *pTail;
  33801. rowSetTreeToList(p->pTree, &pHead, &pTail);
  33802. p->pTree = 0;
  33803. p->pEntry = rowSetMerge(p->pEntry, pHead);
  33804. }
  33805. }
  33806. /*
  33807. ** Extract the smallest element from the RowSet.
  33808. ** Write the element into *pRowid. Return 1 on success. Return
  33809. ** 0 if the RowSet is already empty.
  33810. **
  33811. ** After this routine has been called, the sqlite3RowSetInsert()
  33812. ** routine may not be called again.
  33813. */
  33814. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  33815. rowSetToList(p);
  33816. if( p->pEntry ){
  33817. *pRowid = p->pEntry->v;
  33818. p->pEntry = p->pEntry->pRight;
  33819. if( p->pEntry==0 ){
  33820. sqlite3RowSetClear(p);
  33821. }
  33822. return 1;
  33823. }else{
  33824. return 0;
  33825. }
  33826. }
  33827. /*
  33828. ** Check to see if element iRowid was inserted into the the rowset as
  33829. ** part of any insert batch prior to iBatch. Return 1 or 0.
  33830. */
  33831. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  33832. struct RowSetEntry *p;
  33833. if( iBatch!=pRowSet->iBatch ){
  33834. if( pRowSet->pEntry ){
  33835. rowSetToList(pRowSet);
  33836. pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
  33837. pRowSet->pEntry = 0;
  33838. pRowSet->pLast = 0;
  33839. }
  33840. pRowSet->iBatch = iBatch;
  33841. }
  33842. p = pRowSet->pTree;
  33843. while( p ){
  33844. if( p->v<iRowid ){
  33845. p = p->pRight;
  33846. }else if( p->v>iRowid ){
  33847. p = p->pLeft;
  33848. }else{
  33849. return 1;
  33850. }
  33851. }
  33852. return 0;
  33853. }
  33854. /************** End of rowset.c **********************************************/
  33855. /************** Begin file pager.c *******************************************/
  33856. /*
  33857. ** 2001 September 15
  33858. **
  33859. ** The author disclaims copyright to this source code. In place of
  33860. ** a legal notice, here is a blessing:
  33861. **
  33862. ** May you do good and not evil.
  33863. ** May you find forgiveness for yourself and forgive others.
  33864. ** May you share freely, never taking more than you give.
  33865. **
  33866. *************************************************************************
  33867. ** This is the implementation of the page cache subsystem or "pager".
  33868. **
  33869. ** The pager is used to access a database disk file. It implements
  33870. ** atomic commit and rollback through the use of a journal file that
  33871. ** is separate from the database file. The pager also implements file
  33872. ** locking to prevent two processes from writing the same database
  33873. ** file simultaneously, or one process from reading the database while
  33874. ** another is writing.
  33875. */
  33876. #ifndef SQLITE_OMIT_DISKIO
  33877. /************** Include wal.h in the middle of pager.c ***********************/
  33878. /************** Begin file wal.h *********************************************/
  33879. /*
  33880. ** 2010 February 1
  33881. **
  33882. ** The author disclaims copyright to this source code. In place of
  33883. ** a legal notice, here is a blessing:
  33884. **
  33885. ** May you do good and not evil.
  33886. ** May you find forgiveness for yourself and forgive others.
  33887. ** May you share freely, never taking more than you give.
  33888. **
  33889. *************************************************************************
  33890. ** This header file defines the interface to the write-ahead logging
  33891. ** system. Refer to the comments below and the header comment attached to
  33892. ** the implementation of each function in log.c for further details.
  33893. */
  33894. #ifndef _WAL_H_
  33895. #define _WAL_H_
  33896. #ifdef SQLITE_OMIT_WAL
  33897. # define sqlite3WalOpen(x,y,z) 0
  33898. # define sqlite3WalClose(w,x,y,z) 0
  33899. # define sqlite3WalBeginReadTransaction(y,z) 0
  33900. # define sqlite3WalEndReadTransaction(z)
  33901. # define sqlite3WalRead(v,w,x,y,z) 0
  33902. # define sqlite3WalDbsize(y) 0
  33903. # define sqlite3WalBeginWriteTransaction(y) 0
  33904. # define sqlite3WalEndWriteTransaction(x) 0
  33905. # define sqlite3WalUndo(x,y,z) 0
  33906. # define sqlite3WalSavepoint(y,z)
  33907. # define sqlite3WalSavepointUndo(y,z) 0
  33908. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  33909. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  33910. # define sqlite3WalCallback(z) 0
  33911. # define sqlite3WalExclusiveMode(y,z) 0
  33912. # define sqlite3WalHeapMemory(z) 0
  33913. #else
  33914. #define WAL_SAVEPOINT_NDATA 4
  33915. /* Connection to a write-ahead log (WAL) file.
  33916. ** There is one object of this type for each pager.
  33917. */
  33918. typedef struct Wal Wal;
  33919. /* Open and close a connection to a write-ahead log. */
  33920. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
  33921. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  33922. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  33923. ** snapshot is like a read-transaction. It is the state of the database
  33924. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  33925. ** preserves the current state even if the other threads or processes
  33926. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  33927. ** transaction and releases the lock.
  33928. */
  33929. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  33930. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  33931. /* Read a page from the write-ahead log, if it is present. */
  33932. SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
  33933. /* If the WAL is not empty, return the size of the database. */
  33934. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  33935. /* Obtain or release the WRITER lock. */
  33936. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  33937. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  33938. /* Undo any frames written (but not committed) to the log */
  33939. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  33940. /* Return an integer that records the current (uncommitted) write
  33941. ** position in the WAL */
  33942. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  33943. /* Move the write position of the WAL back to iFrame. Called in
  33944. ** response to a ROLLBACK TO command. */
  33945. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  33946. /* Write a frame or frames to the log. */
  33947. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  33948. /* Copy pages from the log to the database file */
  33949. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  33950. Wal *pWal, /* Write-ahead log connection */
  33951. int eMode, /* One of PASSIVE, FULL and RESTART */
  33952. int (*xBusy)(void*), /* Function to call when busy */
  33953. void *pBusyArg, /* Context argument for xBusyHandler */
  33954. int sync_flags, /* Flags to sync db file with (or 0) */
  33955. int nBuf, /* Size of buffer nBuf */
  33956. u8 *zBuf, /* Temporary buffer to use */
  33957. int *pnLog, /* OUT: Number of frames in WAL */
  33958. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  33959. );
  33960. /* Return the value to pass to a sqlite3_wal_hook callback, the
  33961. ** number of frames in the WAL at the point of the last commit since
  33962. ** sqlite3WalCallback() was called. If no commits have occurred since
  33963. ** the last call, then return 0.
  33964. */
  33965. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  33966. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  33967. ** by the pager layer on the database file.
  33968. */
  33969. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  33970. /* Return true if the argument is non-NULL and the WAL module is using
  33971. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  33972. ** WAL module is using shared-memory, return false.
  33973. */
  33974. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  33975. #endif /* ifndef SQLITE_OMIT_WAL */
  33976. #endif /* _WAL_H_ */
  33977. /************** End of wal.h *************************************************/
  33978. /************** Continuing where we left off in pager.c **********************/
  33979. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  33980. **
  33981. ** This comment block describes invariants that hold when using a rollback
  33982. ** journal. These invariants do not apply for journal_mode=WAL,
  33983. ** journal_mode=MEMORY, or journal_mode=OFF.
  33984. **
  33985. ** Within this comment block, a page is deemed to have been synced
  33986. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  33987. ** Otherwise, the page is not synced until the xSync method of the VFS
  33988. ** is called successfully on the file containing the page.
  33989. **
  33990. ** Definition: A page of the database file is said to be "overwriteable" if
  33991. ** one or more of the following are true about the page:
  33992. **
  33993. ** (a) The original content of the page as it was at the beginning of
  33994. ** the transaction has been written into the rollback journal and
  33995. ** synced.
  33996. **
  33997. ** (b) The page was a freelist leaf page at the start of the transaction.
  33998. **
  33999. ** (c) The page number is greater than the largest page that existed in
  34000. ** the database file at the start of the transaction.
  34001. **
  34002. ** (1) A page of the database file is never overwritten unless one of the
  34003. ** following are true:
  34004. **
  34005. ** (a) The page and all other pages on the same sector are overwriteable.
  34006. **
  34007. ** (b) The atomic page write optimization is enabled, and the entire
  34008. ** transaction other than the update of the transaction sequence
  34009. ** number consists of a single page change.
  34010. **
  34011. ** (2) The content of a page written into the rollback journal exactly matches
  34012. ** both the content in the database when the rollback journal was written
  34013. ** and the content in the database at the beginning of the current
  34014. ** transaction.
  34015. **
  34016. ** (3) Writes to the database file are an integer multiple of the page size
  34017. ** in length and are aligned on a page boundary.
  34018. **
  34019. ** (4) Reads from the database file are either aligned on a page boundary and
  34020. ** an integer multiple of the page size in length or are taken from the
  34021. ** first 100 bytes of the database file.
  34022. **
  34023. ** (5) All writes to the database file are synced prior to the rollback journal
  34024. ** being deleted, truncated, or zeroed.
  34025. **
  34026. ** (6) If a master journal file is used, then all writes to the database file
  34027. ** are synced prior to the master journal being deleted.
  34028. **
  34029. ** Definition: Two databases (or the same database at two points it time)
  34030. ** are said to be "logically equivalent" if they give the same answer to
  34031. ** all queries. Note in particular the the content of freelist leaf
  34032. ** pages can be changed arbitarily without effecting the logical equivalence
  34033. ** of the database.
  34034. **
  34035. ** (7) At any time, if any subset, including the empty set and the total set,
  34036. ** of the unsynced changes to a rollback journal are removed and the
  34037. ** journal is rolled back, the resulting database file will be logical
  34038. ** equivalent to the database file at the beginning of the transaction.
  34039. **
  34040. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  34041. ** is called to restore the database file to the same size it was at
  34042. ** the beginning of the transaction. (In some VFSes, the xTruncate
  34043. ** method is a no-op, but that does not change the fact the SQLite will
  34044. ** invoke it.)
  34045. **
  34046. ** (9) Whenever the database file is modified, at least one bit in the range
  34047. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  34048. ** the EXCLUSIVE lock, thus signaling other connections on the same
  34049. ** database to flush their caches.
  34050. **
  34051. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  34052. ** than one billion transactions.
  34053. **
  34054. ** (11) A database file is well-formed at the beginning and at the conclusion
  34055. ** of every transaction.
  34056. **
  34057. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  34058. ** the database file.
  34059. **
  34060. ** (13) A SHARED lock is held on the database file while reading any
  34061. ** content out of the database file.
  34062. **
  34063. ******************************************************************************/
  34064. /*
  34065. ** Macros for troubleshooting. Normally turned off
  34066. */
  34067. #if 0
  34068. int sqlite3PagerTrace=1; /* True to enable tracing */
  34069. #define sqlite3DebugPrintf printf
  34070. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  34071. #else
  34072. #define PAGERTRACE(X)
  34073. #endif
  34074. /*
  34075. ** The following two macros are used within the PAGERTRACE() macros above
  34076. ** to print out file-descriptors.
  34077. **
  34078. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  34079. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  34080. ** struct as its argument.
  34081. */
  34082. #define PAGERID(p) ((int)(p->fd))
  34083. #define FILEHANDLEID(fd) ((int)fd)
  34084. /*
  34085. ** The Pager.eState variable stores the current 'state' of a pager. A
  34086. ** pager may be in any one of the seven states shown in the following
  34087. ** state diagram.
  34088. **
  34089. ** OPEN <------+------+
  34090. ** | | |
  34091. ** V | |
  34092. ** +---------> READER-------+ |
  34093. ** | | |
  34094. ** | V |
  34095. ** |<-------WRITER_LOCKED------> ERROR
  34096. ** | | ^
  34097. ** | V |
  34098. ** |<------WRITER_CACHEMOD-------->|
  34099. ** | | |
  34100. ** | V |
  34101. ** |<-------WRITER_DBMOD---------->|
  34102. ** | | |
  34103. ** | V |
  34104. ** +<------WRITER_FINISHED-------->+
  34105. **
  34106. **
  34107. ** List of state transitions and the C [function] that performs each:
  34108. **
  34109. ** OPEN -> READER [sqlite3PagerSharedLock]
  34110. ** READER -> OPEN [pager_unlock]
  34111. **
  34112. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  34113. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  34114. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  34115. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  34116. ** WRITER_*** -> READER [pager_end_transaction]
  34117. **
  34118. ** WRITER_*** -> ERROR [pager_error]
  34119. ** ERROR -> OPEN [pager_unlock]
  34120. **
  34121. **
  34122. ** OPEN:
  34123. **
  34124. ** The pager starts up in this state. Nothing is guaranteed in this
  34125. ** state - the file may or may not be locked and the database size is
  34126. ** unknown. The database may not be read or written.
  34127. **
  34128. ** * No read or write transaction is active.
  34129. ** * Any lock, or no lock at all, may be held on the database file.
  34130. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  34131. **
  34132. ** READER:
  34133. **
  34134. ** In this state all the requirements for reading the database in
  34135. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  34136. ** was) in exclusive-locking mode, a user-level read transaction is
  34137. ** open. The database size is known in this state.
  34138. **
  34139. ** A connection running with locking_mode=normal enters this state when
  34140. ** it opens a read-transaction on the database and returns to state
  34141. ** OPEN after the read-transaction is completed. However a connection
  34142. ** running in locking_mode=exclusive (including temp databases) remains in
  34143. ** this state even after the read-transaction is closed. The only way
  34144. ** a locking_mode=exclusive connection can transition from READER to OPEN
  34145. ** is via the ERROR state (see below).
  34146. **
  34147. ** * A read transaction may be active (but a write-transaction cannot).
  34148. ** * A SHARED or greater lock is held on the database file.
  34149. ** * The dbSize variable may be trusted (even if a user-level read
  34150. ** transaction is not active). The dbOrigSize and dbFileSize variables
  34151. ** may not be trusted at this point.
  34152. ** * If the database is a WAL database, then the WAL connection is open.
  34153. ** * Even if a read-transaction is not open, it is guaranteed that
  34154. ** there is no hot-journal in the file-system.
  34155. **
  34156. ** WRITER_LOCKED:
  34157. **
  34158. ** The pager moves to this state from READER when a write-transaction
  34159. ** is first opened on the database. In WRITER_LOCKED state, all locks
  34160. ** required to start a write-transaction are held, but no actual
  34161. ** modifications to the cache or database have taken place.
  34162. **
  34163. ** In rollback mode, a RESERVED or (if the transaction was opened with
  34164. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  34165. ** moving to this state, but the journal file is not written to or opened
  34166. ** to in this state. If the transaction is committed or rolled back while
  34167. ** in WRITER_LOCKED state, all that is required is to unlock the database
  34168. ** file.
  34169. **
  34170. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  34171. ** If the connection is running with locking_mode=exclusive, an attempt
  34172. ** is made to obtain an EXCLUSIVE lock on the database file.
  34173. **
  34174. ** * A write transaction is active.
  34175. ** * If the connection is open in rollback-mode, a RESERVED or greater
  34176. ** lock is held on the database file.
  34177. ** * If the connection is open in WAL-mode, a WAL write transaction
  34178. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  34179. ** called).
  34180. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  34181. ** * The contents of the pager cache have not been modified.
  34182. ** * The journal file may or may not be open.
  34183. ** * Nothing (not even the first header) has been written to the journal.
  34184. **
  34185. ** WRITER_CACHEMOD:
  34186. **
  34187. ** A pager moves from WRITER_LOCKED state to this state when a page is
  34188. ** first modified by the upper layer. In rollback mode the journal file
  34189. ** is opened (if it is not already open) and a header written to the
  34190. ** start of it. The database file on disk has not been modified.
  34191. **
  34192. ** * A write transaction is active.
  34193. ** * A RESERVED or greater lock is held on the database file.
  34194. ** * The journal file is open and the first header has been written
  34195. ** to it, but the header has not been synced to disk.
  34196. ** * The contents of the page cache have been modified.
  34197. **
  34198. ** WRITER_DBMOD:
  34199. **
  34200. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  34201. ** when it modifies the contents of the database file. WAL connections
  34202. ** never enter this state (since they do not modify the database file,
  34203. ** just the log file).
  34204. **
  34205. ** * A write transaction is active.
  34206. ** * An EXCLUSIVE or greater lock is held on the database file.
  34207. ** * The journal file is open and the first header has been written
  34208. ** and synced to disk.
  34209. ** * The contents of the page cache have been modified (and possibly
  34210. ** written to disk).
  34211. **
  34212. ** WRITER_FINISHED:
  34213. **
  34214. ** It is not possible for a WAL connection to enter this state.
  34215. **
  34216. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  34217. ** state after the entire transaction has been successfully written into the
  34218. ** database file. In this state the transaction may be committed simply
  34219. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  34220. ** not possible to modify the database further. At this point, the upper
  34221. ** layer must either commit or rollback the transaction.
  34222. **
  34223. ** * A write transaction is active.
  34224. ** * An EXCLUSIVE or greater lock is held on the database file.
  34225. ** * All writing and syncing of journal and database data has finished.
  34226. ** If no error occured, all that remains is to finalize the journal to
  34227. ** commit the transaction. If an error did occur, the caller will need
  34228. ** to rollback the transaction.
  34229. **
  34230. ** ERROR:
  34231. **
  34232. ** The ERROR state is entered when an IO or disk-full error (including
  34233. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  34234. ** difficult to be sure that the in-memory pager state (cache contents,
  34235. ** db size etc.) are consistent with the contents of the file-system.
  34236. **
  34237. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  34238. ** cannot.
  34239. **
  34240. ** For example, if an IO error occurs while performing a rollback,
  34241. ** the contents of the page-cache may be left in an inconsistent state.
  34242. ** At this point it would be dangerous to change back to READER state
  34243. ** (as usually happens after a rollback). Any subsequent readers might
  34244. ** report database corruption (due to the inconsistent cache), and if
  34245. ** they upgrade to writers, they may inadvertently corrupt the database
  34246. ** file. To avoid this hazard, the pager switches into the ERROR state
  34247. ** instead of READER following such an error.
  34248. **
  34249. ** Once it has entered the ERROR state, any attempt to use the pager
  34250. ** to read or write data returns an error. Eventually, once all
  34251. ** outstanding transactions have been abandoned, the pager is able to
  34252. ** transition back to OPEN state, discarding the contents of the
  34253. ** page-cache and any other in-memory state at the same time. Everything
  34254. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  34255. ** when a read-transaction is next opened on the pager (transitioning
  34256. ** the pager into READER state). At that point the system has recovered
  34257. ** from the error.
  34258. **
  34259. ** Specifically, the pager jumps into the ERROR state if:
  34260. **
  34261. ** 1. An error occurs while attempting a rollback. This happens in
  34262. ** function sqlite3PagerRollback().
  34263. **
  34264. ** 2. An error occurs while attempting to finalize a journal file
  34265. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  34266. **
  34267. ** 3. An error occurs while attempting to write to the journal or
  34268. ** database file in function pagerStress() in order to free up
  34269. ** memory.
  34270. **
  34271. ** In other cases, the error is returned to the b-tree layer. The b-tree
  34272. ** layer then attempts a rollback operation. If the error condition
  34273. ** persists, the pager enters the ERROR state via condition (1) above.
  34274. **
  34275. ** Condition (3) is necessary because it can be triggered by a read-only
  34276. ** statement executed within a transaction. In this case, if the error
  34277. ** code were simply returned to the user, the b-tree layer would not
  34278. ** automatically attempt a rollback, as it assumes that an error in a
  34279. ** read-only statement cannot leave the pager in an internally inconsistent
  34280. ** state.
  34281. **
  34282. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  34283. ** * There are one or more outstanding references to pages (after the
  34284. ** last reference is dropped the pager should move back to OPEN state).
  34285. ** * The pager is not an in-memory pager.
  34286. **
  34287. **
  34288. ** Notes:
  34289. **
  34290. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  34291. ** connection is open in WAL mode. A WAL connection is always in one
  34292. ** of the first four states.
  34293. **
  34294. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  34295. ** state. There are two exceptions: immediately after exclusive-mode has
  34296. ** been turned on (and before any read or write transactions are
  34297. ** executed), and when the pager is leaving the "error state".
  34298. **
  34299. ** * See also: assert_pager_state().
  34300. */
  34301. #define PAGER_OPEN 0
  34302. #define PAGER_READER 1
  34303. #define PAGER_WRITER_LOCKED 2
  34304. #define PAGER_WRITER_CACHEMOD 3
  34305. #define PAGER_WRITER_DBMOD 4
  34306. #define PAGER_WRITER_FINISHED 5
  34307. #define PAGER_ERROR 6
  34308. /*
  34309. ** The Pager.eLock variable is almost always set to one of the
  34310. ** following locking-states, according to the lock currently held on
  34311. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  34312. ** This variable is kept up to date as locks are taken and released by
  34313. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  34314. **
  34315. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  34316. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  34317. ** the operation was successful. In these circumstances pagerLockDb() and
  34318. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  34319. ** when unlocking the file, and only updated when locking the file if the
  34320. ** VFS call is successful. This way, the Pager.eLock variable may be set
  34321. ** to a less exclusive (lower) value than the lock that is actually held
  34322. ** at the system level, but it is never set to a more exclusive value.
  34323. **
  34324. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  34325. ** be a few redundant xLock() calls or a lock may be held for longer than
  34326. ** required, but nothing really goes wrong.
  34327. **
  34328. ** The exception is when the database file is unlocked as the pager moves
  34329. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  34330. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  34331. ** transition, by the same pager or any other). If the call to xUnlock()
  34332. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  34333. ** can confuse the call to xCheckReservedLock() call made later as part
  34334. ** of hot-journal detection.
  34335. **
  34336. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  34337. ** lock held by this process or any others". So xCheckReservedLock may
  34338. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  34339. ** doesn't know it because of a previous error in xUnlock). If this happens
  34340. ** a hot-journal may be mistaken for a journal being created by an active
  34341. ** transaction in another process, causing SQLite to read from the database
  34342. ** without rolling it back.
  34343. **
  34344. ** To work around this, if a call to xUnlock() fails when unlocking the
  34345. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  34346. ** is only changed back to a real locking state after a successful call
  34347. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  34348. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  34349. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  34350. ** lock on the database file before attempting to roll it back. See function
  34351. ** PagerSharedLock() for more detail.
  34352. **
  34353. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  34354. ** PAGER_OPEN state.
  34355. */
  34356. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  34357. /*
  34358. ** A macro used for invoking the codec if there is one
  34359. */
  34360. #ifdef SQLITE_HAS_CODEC
  34361. # define CODEC1(P,D,N,X,E) \
  34362. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  34363. # define CODEC2(P,D,N,X,E,O) \
  34364. if( P->xCodec==0 ){ O=(char*)D; }else \
  34365. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  34366. #else
  34367. # define CODEC1(P,D,N,X,E) /* NO-OP */
  34368. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  34369. #endif
  34370. /*
  34371. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  34372. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  34373. ** This could conceivably cause corruption following a power failure on
  34374. ** such a system. This is currently an undocumented limit.
  34375. */
  34376. #define MAX_SECTOR_SIZE 0x10000
  34377. /*
  34378. ** An instance of the following structure is allocated for each active
  34379. ** savepoint and statement transaction in the system. All such structures
  34380. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  34381. ** resized using sqlite3Realloc().
  34382. **
  34383. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  34384. ** set to 0. If a journal-header is written into the main journal while
  34385. ** the savepoint is active, then iHdrOffset is set to the byte offset
  34386. ** immediately following the last journal record written into the main
  34387. ** journal before the journal-header. This is required during savepoint
  34388. ** rollback (see pagerPlaybackSavepoint()).
  34389. */
  34390. typedef struct PagerSavepoint PagerSavepoint;
  34391. struct PagerSavepoint {
  34392. i64 iOffset; /* Starting offset in main journal */
  34393. i64 iHdrOffset; /* See above */
  34394. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  34395. Pgno nOrig; /* Original number of pages in file */
  34396. Pgno iSubRec; /* Index of first record in sub-journal */
  34397. #ifndef SQLITE_OMIT_WAL
  34398. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  34399. #endif
  34400. };
  34401. /*
  34402. ** A open page cache is an instance of struct Pager. A description of
  34403. ** some of the more important member variables follows:
  34404. **
  34405. ** eState
  34406. **
  34407. ** The current 'state' of the pager object. See the comment and state
  34408. ** diagram above for a description of the pager state.
  34409. **
  34410. ** eLock
  34411. **
  34412. ** For a real on-disk database, the current lock held on the database file -
  34413. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  34414. **
  34415. ** For a temporary or in-memory database (neither of which require any
  34416. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  34417. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  34418. ** logic into thinking that it already has all the locks it will ever
  34419. ** need (and no reason to release them).
  34420. **
  34421. ** In some (obscure) circumstances, this variable may also be set to
  34422. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  34423. ** details.
  34424. **
  34425. ** changeCountDone
  34426. **
  34427. ** This boolean variable is used to make sure that the change-counter
  34428. ** (the 4-byte header field at byte offset 24 of the database file) is
  34429. ** not updated more often than necessary.
  34430. **
  34431. ** It is set to true when the change-counter field is updated, which
  34432. ** can only happen if an exclusive lock is held on the database file.
  34433. ** It is cleared (set to false) whenever an exclusive lock is
  34434. ** relinquished on the database file. Each time a transaction is committed,
  34435. ** The changeCountDone flag is inspected. If it is true, the work of
  34436. ** updating the change-counter is omitted for the current transaction.
  34437. **
  34438. ** This mechanism means that when running in exclusive mode, a connection
  34439. ** need only update the change-counter once, for the first transaction
  34440. ** committed.
  34441. **
  34442. ** setMaster
  34443. **
  34444. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  34445. ** (or may not) specify a master-journal name to be written into the
  34446. ** journal file before it is synced to disk.
  34447. **
  34448. ** Whether or not a journal file contains a master-journal pointer affects
  34449. ** the way in which the journal file is finalized after the transaction is
  34450. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  34451. ** If a journal file does not contain a master-journal pointer, it is
  34452. ** finalized by overwriting the first journal header with zeroes. If
  34453. ** it does contain a master-journal pointer the journal file is finalized
  34454. ** by truncating it to zero bytes, just as if the connection were
  34455. ** running in "journal_mode=truncate" mode.
  34456. **
  34457. ** Journal files that contain master journal pointers cannot be finalized
  34458. ** simply by overwriting the first journal-header with zeroes, as the
  34459. ** master journal pointer could interfere with hot-journal rollback of any
  34460. ** subsequently interrupted transaction that reuses the journal file.
  34461. **
  34462. ** The flag is cleared as soon as the journal file is finalized (either
  34463. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  34464. ** journal file from being successfully finalized, the setMaster flag
  34465. ** is cleared anyway (and the pager will move to ERROR state).
  34466. **
  34467. ** doNotSpill, doNotSyncSpill
  34468. **
  34469. ** These two boolean variables control the behaviour of cache-spills
  34470. ** (calls made by the pcache module to the pagerStress() routine to
  34471. ** write cached data to the file-system in order to free up memory).
  34472. **
  34473. ** When doNotSpill is non-zero, writing to the database from pagerStress()
  34474. ** is disabled altogether. This is done in a very obscure case that
  34475. ** comes up during savepoint rollback that requires the pcache module
  34476. ** to allocate a new page to prevent the journal file from being written
  34477. ** while it is being traversed by code in pager_playback().
  34478. **
  34479. ** If doNotSyncSpill is non-zero, writing to the database from pagerStress()
  34480. ** is permitted, but syncing the journal file is not. This flag is set
  34481. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  34482. ** the database page-size in order to prevent a journal sync from happening
  34483. ** in between the journalling of two pages on the same sector.
  34484. **
  34485. ** subjInMemory
  34486. **
  34487. ** This is a boolean variable. If true, then any required sub-journal
  34488. ** is opened as an in-memory journal file. If false, then in-memory
  34489. ** sub-journals are only used for in-memory pager files.
  34490. **
  34491. ** This variable is updated by the upper layer each time a new
  34492. ** write-transaction is opened.
  34493. **
  34494. ** dbSize, dbOrigSize, dbFileSize
  34495. **
  34496. ** Variable dbSize is set to the number of pages in the database file.
  34497. ** It is valid in PAGER_READER and higher states (all states except for
  34498. ** OPEN and ERROR).
  34499. **
  34500. ** dbSize is set based on the size of the database file, which may be
  34501. ** larger than the size of the database (the value stored at offset
  34502. ** 28 of the database header by the btree). If the size of the file
  34503. ** is not an integer multiple of the page-size, the value stored in
  34504. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  34505. ** Except, any file that is greater than 0 bytes in size is considered
  34506. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  34507. ** to dbSize==1).
  34508. **
  34509. ** During a write-transaction, if pages with page-numbers greater than
  34510. ** dbSize are modified in the cache, dbSize is updated accordingly.
  34511. ** Similarly, if the database is truncated using PagerTruncateImage(),
  34512. ** dbSize is updated.
  34513. **
  34514. ** Variables dbOrigSize and dbFileSize are valid in states
  34515. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  34516. ** variable at the start of the transaction. It is used during rollback,
  34517. ** and to determine whether or not pages need to be journalled before
  34518. ** being modified.
  34519. **
  34520. ** Throughout a write-transaction, dbFileSize contains the size of
  34521. ** the file on disk in pages. It is set to a copy of dbSize when the
  34522. ** write-transaction is first opened, and updated when VFS calls are made
  34523. ** to write or truncate the database file on disk.
  34524. **
  34525. ** The only reason the dbFileSize variable is required is to suppress
  34526. ** unnecessary calls to xTruncate() after committing a transaction. If,
  34527. ** when a transaction is committed, the dbFileSize variable indicates
  34528. ** that the database file is larger than the database image (Pager.dbSize),
  34529. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  34530. ** to measure the database file on disk, and then truncates it if required.
  34531. ** dbFileSize is not used when rolling back a transaction. In this case
  34532. ** pager_truncate() is called unconditionally (which means there may be
  34533. ** a call to xFilesize() that is not strictly required). In either case,
  34534. ** pager_truncate() may cause the file to become smaller or larger.
  34535. **
  34536. ** dbHintSize
  34537. **
  34538. ** The dbHintSize variable is used to limit the number of calls made to
  34539. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  34540. **
  34541. ** dbHintSize is set to a copy of the dbSize variable when a
  34542. ** write-transaction is opened (at the same time as dbFileSize and
  34543. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  34544. ** dbHintSize is increased to the number of pages that correspond to the
  34545. ** size-hint passed to the method call. See pager_write_pagelist() for
  34546. ** details.
  34547. **
  34548. ** errCode
  34549. **
  34550. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  34551. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  34552. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  34553. ** sub-codes.
  34554. */
  34555. struct Pager {
  34556. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  34557. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  34558. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  34559. u8 useJournal; /* Use a rollback journal on this file */
  34560. u8 noReadlock; /* Do not bother to obtain readlocks */
  34561. u8 noSync; /* Do not sync the journal if true */
  34562. u8 fullSync; /* Do extra syncs of the journal for robustness */
  34563. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  34564. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  34565. u8 tempFile; /* zFilename is a temporary file */
  34566. u8 readOnly; /* True for a read-only database */
  34567. u8 memDb; /* True to inhibit all file I/O */
  34568. /**************************************************************************
  34569. ** The following block contains those class members that change during
  34570. ** routine opertion. Class members not in this block are either fixed
  34571. ** when the pager is first created or else only change when there is a
  34572. ** significant mode change (such as changing the page_size, locking_mode,
  34573. ** or the journal_mode). From another view, these class members describe
  34574. ** the "state" of the pager, while other class members describe the
  34575. ** "configuration" of the pager.
  34576. */
  34577. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  34578. u8 eLock; /* Current lock held on database file */
  34579. u8 changeCountDone; /* Set after incrementing the change-counter */
  34580. u8 setMaster; /* True if a m-j name has been written to jrnl */
  34581. u8 doNotSpill; /* Do not spill the cache when non-zero */
  34582. u8 doNotSyncSpill; /* Do not do a spill that requires jrnl sync */
  34583. u8 subjInMemory; /* True to use in-memory sub-journals */
  34584. Pgno dbSize; /* Number of pages in the database */
  34585. Pgno dbOrigSize; /* dbSize before the current transaction */
  34586. Pgno dbFileSize; /* Number of pages in the database file */
  34587. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  34588. int errCode; /* One of several kinds of errors */
  34589. int nRec; /* Pages journalled since last j-header written */
  34590. u32 cksumInit; /* Quasi-random value added to every checksum */
  34591. u32 nSubRec; /* Number of records written to sub-journal */
  34592. Bitvec *pInJournal; /* One bit for each page in the database file */
  34593. sqlite3_file *fd; /* File descriptor for database */
  34594. sqlite3_file *jfd; /* File descriptor for main journal */
  34595. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  34596. i64 journalOff; /* Current write offset in the journal file */
  34597. i64 journalHdr; /* Byte offset to previous journal header */
  34598. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  34599. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  34600. int nSavepoint; /* Number of elements in aSavepoint[] */
  34601. char dbFileVers[16]; /* Changes whenever database file changes */
  34602. /*
  34603. ** End of the routinely-changing class members
  34604. ***************************************************************************/
  34605. u16 nExtra; /* Add this many bytes to each in-memory page */
  34606. i16 nReserve; /* Number of unused bytes at end of each page */
  34607. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  34608. u32 sectorSize; /* Assumed sector size during rollback */
  34609. int pageSize; /* Number of bytes in a page */
  34610. Pgno mxPgno; /* Maximum allowed size of the database */
  34611. i64 journalSizeLimit; /* Size limit for persistent journal files */
  34612. char *zFilename; /* Name of the database file */
  34613. char *zJournal; /* Name of the journal file */
  34614. int (*xBusyHandler)(void*); /* Function to call when busy */
  34615. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  34616. #ifdef SQLITE_TEST
  34617. int nHit, nMiss; /* Cache hits and missing */
  34618. int nRead, nWrite; /* Database pages read/written */
  34619. #endif
  34620. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  34621. #ifdef SQLITE_HAS_CODEC
  34622. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  34623. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  34624. void (*xCodecFree)(void*); /* Destructor for the codec */
  34625. void *pCodec; /* First argument to xCodec... methods */
  34626. #endif
  34627. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  34628. PCache *pPCache; /* Pointer to page cache object */
  34629. #ifndef SQLITE_OMIT_WAL
  34630. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  34631. char *zWal; /* File name for write-ahead log */
  34632. #endif
  34633. };
  34634. /*
  34635. ** The following global variables hold counters used for
  34636. ** testing purposes only. These variables do not exist in
  34637. ** a non-testing build. These variables are not thread-safe.
  34638. */
  34639. #ifdef SQLITE_TEST
  34640. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  34641. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  34642. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  34643. # define PAGER_INCR(v) v++
  34644. #else
  34645. # define PAGER_INCR(v)
  34646. #endif
  34647. /*
  34648. ** Journal files begin with the following magic string. The data
  34649. ** was obtained from /dev/random. It is used only as a sanity check.
  34650. **
  34651. ** Since version 2.8.0, the journal format contains additional sanity
  34652. ** checking information. If the power fails while the journal is being
  34653. ** written, semi-random garbage data might appear in the journal
  34654. ** file after power is restored. If an attempt is then made
  34655. ** to roll the journal back, the database could be corrupted. The additional
  34656. ** sanity checking data is an attempt to discover the garbage in the
  34657. ** journal and ignore it.
  34658. **
  34659. ** The sanity checking information for the new journal format consists
  34660. ** of a 32-bit checksum on each page of data. The checksum covers both
  34661. ** the page number and the pPager->pageSize bytes of data for the page.
  34662. ** This cksum is initialized to a 32-bit random value that appears in the
  34663. ** journal file right after the header. The random initializer is important,
  34664. ** because garbage data that appears at the end of a journal is likely
  34665. ** data that was once in other files that have now been deleted. If the
  34666. ** garbage data came from an obsolete journal file, the checksums might
  34667. ** be correct. But by initializing the checksum to random value which
  34668. ** is different for every journal, we minimize that risk.
  34669. */
  34670. static const unsigned char aJournalMagic[] = {
  34671. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  34672. };
  34673. /*
  34674. ** The size of the of each page record in the journal is given by
  34675. ** the following macro.
  34676. */
  34677. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  34678. /*
  34679. ** The journal header size for this pager. This is usually the same
  34680. ** size as a single disk sector. See also setSectorSize().
  34681. */
  34682. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  34683. /*
  34684. ** The macro MEMDB is true if we are dealing with an in-memory database.
  34685. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  34686. ** the value of MEMDB will be a constant and the compiler will optimize
  34687. ** out code that would never execute.
  34688. */
  34689. #ifdef SQLITE_OMIT_MEMORYDB
  34690. # define MEMDB 0
  34691. #else
  34692. # define MEMDB pPager->memDb
  34693. #endif
  34694. /*
  34695. ** The maximum legal page number is (2^31 - 1).
  34696. */
  34697. #define PAGER_MAX_PGNO 2147483647
  34698. /*
  34699. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  34700. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  34701. **
  34702. ** This is so that expressions can be written as:
  34703. **
  34704. ** if( isOpen(pPager->jfd) ){ ...
  34705. **
  34706. ** instead of
  34707. **
  34708. ** if( pPager->jfd->pMethods ){ ...
  34709. */
  34710. #define isOpen(pFd) ((pFd)->pMethods)
  34711. /*
  34712. ** Return true if this pager uses a write-ahead log instead of the usual
  34713. ** rollback journal. Otherwise false.
  34714. */
  34715. #ifndef SQLITE_OMIT_WAL
  34716. static int pagerUseWal(Pager *pPager){
  34717. return (pPager->pWal!=0);
  34718. }
  34719. #else
  34720. # define pagerUseWal(x) 0
  34721. # define pagerRollbackWal(x) 0
  34722. # define pagerWalFrames(v,w,x,y,z) 0
  34723. # define pagerOpenWalIfPresent(z) SQLITE_OK
  34724. # define pagerBeginReadTransaction(z) SQLITE_OK
  34725. #endif
  34726. #ifndef NDEBUG
  34727. /*
  34728. ** Usage:
  34729. **
  34730. ** assert( assert_pager_state(pPager) );
  34731. **
  34732. ** This function runs many asserts to try to find inconsistencies in
  34733. ** the internal state of the Pager object.
  34734. */
  34735. static int assert_pager_state(Pager *p){
  34736. Pager *pPager = p;
  34737. /* State must be valid. */
  34738. assert( p->eState==PAGER_OPEN
  34739. || p->eState==PAGER_READER
  34740. || p->eState==PAGER_WRITER_LOCKED
  34741. || p->eState==PAGER_WRITER_CACHEMOD
  34742. || p->eState==PAGER_WRITER_DBMOD
  34743. || p->eState==PAGER_WRITER_FINISHED
  34744. || p->eState==PAGER_ERROR
  34745. );
  34746. /* Regardless of the current state, a temp-file connection always behaves
  34747. ** as if it has an exclusive lock on the database file. It never updates
  34748. ** the change-counter field, so the changeCountDone flag is always set.
  34749. */
  34750. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  34751. assert( p->tempFile==0 || pPager->changeCountDone );
  34752. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  34753. ** And if the journal-mode is "OFF", the journal file must not be open.
  34754. */
  34755. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  34756. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  34757. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  34758. ** this means an in-memory pager performs no IO at all, it cannot encounter
  34759. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  34760. ** a journal file. (although the in-memory journal implementation may
  34761. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  34762. ** is therefore not possible for an in-memory pager to enter the ERROR
  34763. ** state.
  34764. */
  34765. if( MEMDB ){
  34766. assert( p->noSync );
  34767. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  34768. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  34769. );
  34770. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  34771. assert( pagerUseWal(p)==0 );
  34772. }
  34773. /* If changeCountDone is set, a RESERVED lock or greater must be held
  34774. ** on the file.
  34775. */
  34776. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  34777. assert( p->eLock!=PENDING_LOCK );
  34778. switch( p->eState ){
  34779. case PAGER_OPEN:
  34780. assert( !MEMDB );
  34781. assert( pPager->errCode==SQLITE_OK );
  34782. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  34783. break;
  34784. case PAGER_READER:
  34785. assert( pPager->errCode==SQLITE_OK );
  34786. assert( p->eLock!=UNKNOWN_LOCK );
  34787. assert( p->eLock>=SHARED_LOCK || p->noReadlock );
  34788. break;
  34789. case PAGER_WRITER_LOCKED:
  34790. assert( p->eLock!=UNKNOWN_LOCK );
  34791. assert( pPager->errCode==SQLITE_OK );
  34792. if( !pagerUseWal(pPager) ){
  34793. assert( p->eLock>=RESERVED_LOCK );
  34794. }
  34795. assert( pPager->dbSize==pPager->dbOrigSize );
  34796. assert( pPager->dbOrigSize==pPager->dbFileSize );
  34797. assert( pPager->dbOrigSize==pPager->dbHintSize );
  34798. assert( pPager->setMaster==0 );
  34799. break;
  34800. case PAGER_WRITER_CACHEMOD:
  34801. assert( p->eLock!=UNKNOWN_LOCK );
  34802. assert( pPager->errCode==SQLITE_OK );
  34803. if( !pagerUseWal(pPager) ){
  34804. /* It is possible that if journal_mode=wal here that neither the
  34805. ** journal file nor the WAL file are open. This happens during
  34806. ** a rollback transaction that switches from journal_mode=off
  34807. ** to journal_mode=wal.
  34808. */
  34809. assert( p->eLock>=RESERVED_LOCK );
  34810. assert( isOpen(p->jfd)
  34811. || p->journalMode==PAGER_JOURNALMODE_OFF
  34812. || p->journalMode==PAGER_JOURNALMODE_WAL
  34813. );
  34814. }
  34815. assert( pPager->dbOrigSize==pPager->dbFileSize );
  34816. assert( pPager->dbOrigSize==pPager->dbHintSize );
  34817. break;
  34818. case PAGER_WRITER_DBMOD:
  34819. assert( p->eLock==EXCLUSIVE_LOCK );
  34820. assert( pPager->errCode==SQLITE_OK );
  34821. assert( !pagerUseWal(pPager) );
  34822. assert( p->eLock>=EXCLUSIVE_LOCK );
  34823. assert( isOpen(p->jfd)
  34824. || p->journalMode==PAGER_JOURNALMODE_OFF
  34825. || p->journalMode==PAGER_JOURNALMODE_WAL
  34826. );
  34827. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  34828. break;
  34829. case PAGER_WRITER_FINISHED:
  34830. assert( p->eLock==EXCLUSIVE_LOCK );
  34831. assert( pPager->errCode==SQLITE_OK );
  34832. assert( !pagerUseWal(pPager) );
  34833. assert( isOpen(p->jfd)
  34834. || p->journalMode==PAGER_JOURNALMODE_OFF
  34835. || p->journalMode==PAGER_JOURNALMODE_WAL
  34836. );
  34837. break;
  34838. case PAGER_ERROR:
  34839. /* There must be at least one outstanding reference to the pager if
  34840. ** in ERROR state. Otherwise the pager should have already dropped
  34841. ** back to OPEN state.
  34842. */
  34843. assert( pPager->errCode!=SQLITE_OK );
  34844. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  34845. break;
  34846. }
  34847. return 1;
  34848. }
  34849. #endif /* ifndef NDEBUG */
  34850. #ifdef SQLITE_DEBUG
  34851. /*
  34852. ** Return a pointer to a human readable string in a static buffer
  34853. ** containing the state of the Pager object passed as an argument. This
  34854. ** is intended to be used within debuggers. For example, as an alternative
  34855. ** to "print *pPager" in gdb:
  34856. **
  34857. ** (gdb) printf "%s", print_pager_state(pPager)
  34858. */
  34859. static char *print_pager_state(Pager *p){
  34860. static char zRet[1024];
  34861. sqlite3_snprintf(1024, zRet,
  34862. "Filename: %s\n"
  34863. "State: %s errCode=%d\n"
  34864. "Lock: %s\n"
  34865. "Locking mode: locking_mode=%s\n"
  34866. "Journal mode: journal_mode=%s\n"
  34867. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  34868. "Journal: journalOff=%lld journalHdr=%lld\n"
  34869. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  34870. , p->zFilename
  34871. , p->eState==PAGER_OPEN ? "OPEN" :
  34872. p->eState==PAGER_READER ? "READER" :
  34873. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  34874. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  34875. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  34876. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  34877. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  34878. , (int)p->errCode
  34879. , p->eLock==NO_LOCK ? "NO_LOCK" :
  34880. p->eLock==RESERVED_LOCK ? "RESERVED" :
  34881. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  34882. p->eLock==SHARED_LOCK ? "SHARED" :
  34883. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  34884. , p->exclusiveMode ? "exclusive" : "normal"
  34885. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  34886. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  34887. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  34888. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  34889. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  34890. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  34891. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  34892. , p->journalOff, p->journalHdr
  34893. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  34894. );
  34895. return zRet;
  34896. }
  34897. #endif
  34898. /*
  34899. ** Return true if it is necessary to write page *pPg into the sub-journal.
  34900. ** A page needs to be written into the sub-journal if there exists one
  34901. ** or more open savepoints for which:
  34902. **
  34903. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  34904. ** * The bit corresponding to the page-number is not set in
  34905. ** PagerSavepoint.pInSavepoint.
  34906. */
  34907. static int subjRequiresPage(PgHdr *pPg){
  34908. Pgno pgno = pPg->pgno;
  34909. Pager *pPager = pPg->pPager;
  34910. int i;
  34911. for(i=0; i<pPager->nSavepoint; i++){
  34912. PagerSavepoint *p = &pPager->aSavepoint[i];
  34913. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  34914. return 1;
  34915. }
  34916. }
  34917. return 0;
  34918. }
  34919. /*
  34920. ** Return true if the page is already in the journal file.
  34921. */
  34922. static int pageInJournal(PgHdr *pPg){
  34923. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  34924. }
  34925. /*
  34926. ** Read a 32-bit integer from the given file descriptor. Store the integer
  34927. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  34928. ** error code is something goes wrong.
  34929. **
  34930. ** All values are stored on disk as big-endian.
  34931. */
  34932. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  34933. unsigned char ac[4];
  34934. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  34935. if( rc==SQLITE_OK ){
  34936. *pRes = sqlite3Get4byte(ac);
  34937. }
  34938. return rc;
  34939. }
  34940. /*
  34941. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  34942. */
  34943. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  34944. /*
  34945. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  34946. ** on success or an error code is something goes wrong.
  34947. */
  34948. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  34949. char ac[4];
  34950. put32bits(ac, val);
  34951. return sqlite3OsWrite(fd, ac, 4, offset);
  34952. }
  34953. /*
  34954. ** Unlock the database file to level eLock, which must be either NO_LOCK
  34955. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  34956. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  34957. **
  34958. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  34959. ** called, do not modify it. See the comment above the #define of
  34960. ** UNKNOWN_LOCK for an explanation of this.
  34961. */
  34962. static int pagerUnlockDb(Pager *pPager, int eLock){
  34963. int rc = SQLITE_OK;
  34964. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  34965. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  34966. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  34967. if( isOpen(pPager->fd) ){
  34968. assert( pPager->eLock>=eLock );
  34969. rc = sqlite3OsUnlock(pPager->fd, eLock);
  34970. if( pPager->eLock!=UNKNOWN_LOCK ){
  34971. pPager->eLock = (u8)eLock;
  34972. }
  34973. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  34974. }
  34975. return rc;
  34976. }
  34977. /*
  34978. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  34979. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  34980. ** Pager.eLock variable to the new locking state.
  34981. **
  34982. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  34983. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  34984. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  34985. ** of this.
  34986. */
  34987. static int pagerLockDb(Pager *pPager, int eLock){
  34988. int rc = SQLITE_OK;
  34989. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  34990. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  34991. rc = sqlite3OsLock(pPager->fd, eLock);
  34992. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  34993. pPager->eLock = (u8)eLock;
  34994. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  34995. }
  34996. }
  34997. return rc;
  34998. }
  34999. /*
  35000. ** This function determines whether or not the atomic-write optimization
  35001. ** can be used with this pager. The optimization can be used if:
  35002. **
  35003. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  35004. ** a database page may be written atomically, and
  35005. ** (b) the value returned by OsSectorSize() is less than or equal
  35006. ** to the page size.
  35007. **
  35008. ** The optimization is also always enabled for temporary files. It is
  35009. ** an error to call this function if pPager is opened on an in-memory
  35010. ** database.
  35011. **
  35012. ** If the optimization cannot be used, 0 is returned. If it can be used,
  35013. ** then the value returned is the size of the journal file when it
  35014. ** contains rollback data for exactly one page.
  35015. */
  35016. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  35017. static int jrnlBufferSize(Pager *pPager){
  35018. assert( !MEMDB );
  35019. if( !pPager->tempFile ){
  35020. int dc; /* Device characteristics */
  35021. int nSector; /* Sector size */
  35022. int szPage; /* Page size */
  35023. assert( isOpen(pPager->fd) );
  35024. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  35025. nSector = pPager->sectorSize;
  35026. szPage = pPager->pageSize;
  35027. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  35028. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  35029. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  35030. return 0;
  35031. }
  35032. }
  35033. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  35034. }
  35035. #endif
  35036. /*
  35037. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  35038. ** on the cache using a hash function. This is used for testing
  35039. ** and debugging only.
  35040. */
  35041. #ifdef SQLITE_CHECK_PAGES
  35042. /*
  35043. ** Return a 32-bit hash of the page data for pPage.
  35044. */
  35045. static u32 pager_datahash(int nByte, unsigned char *pData){
  35046. u32 hash = 0;
  35047. int i;
  35048. for(i=0; i<nByte; i++){
  35049. hash = (hash*1039) + pData[i];
  35050. }
  35051. return hash;
  35052. }
  35053. static u32 pager_pagehash(PgHdr *pPage){
  35054. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  35055. }
  35056. static void pager_set_pagehash(PgHdr *pPage){
  35057. pPage->pageHash = pager_pagehash(pPage);
  35058. }
  35059. /*
  35060. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  35061. ** is defined, and NDEBUG is not defined, an assert() statement checks
  35062. ** that the page is either dirty or still matches the calculated page-hash.
  35063. */
  35064. #define CHECK_PAGE(x) checkPage(x)
  35065. static void checkPage(PgHdr *pPg){
  35066. Pager *pPager = pPg->pPager;
  35067. assert( pPager->eState!=PAGER_ERROR );
  35068. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  35069. }
  35070. #else
  35071. #define pager_datahash(X,Y) 0
  35072. #define pager_pagehash(X) 0
  35073. #define pager_set_pagehash(X)
  35074. #define CHECK_PAGE(x)
  35075. #endif /* SQLITE_CHECK_PAGES */
  35076. /*
  35077. ** When this is called the journal file for pager pPager must be open.
  35078. ** This function attempts to read a master journal file name from the
  35079. ** end of the file and, if successful, copies it into memory supplied
  35080. ** by the caller. See comments above writeMasterJournal() for the format
  35081. ** used to store a master journal file name at the end of a journal file.
  35082. **
  35083. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  35084. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  35085. ** enough space to write the master journal name). If the master journal
  35086. ** name in the journal is longer than nMaster bytes (including a
  35087. ** nul-terminator), then this is handled as if no master journal name
  35088. ** were present in the journal.
  35089. **
  35090. ** If a master journal file name is present at the end of the journal
  35091. ** file, then it is copied into the buffer pointed to by zMaster. A
  35092. ** nul-terminator byte is appended to the buffer following the master
  35093. ** journal file name.
  35094. **
  35095. ** If it is determined that no master journal file name is present
  35096. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  35097. **
  35098. ** If an error occurs while reading from the journal file, an SQLite
  35099. ** error code is returned.
  35100. */
  35101. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  35102. int rc; /* Return code */
  35103. u32 len; /* Length in bytes of master journal name */
  35104. i64 szJ; /* Total size in bytes of journal file pJrnl */
  35105. u32 cksum; /* MJ checksum value read from journal */
  35106. u32 u; /* Unsigned loop counter */
  35107. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  35108. zMaster[0] = '\0';
  35109. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  35110. || szJ<16
  35111. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  35112. || len>=nMaster
  35113. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  35114. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  35115. || memcmp(aMagic, aJournalMagic, 8)
  35116. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  35117. ){
  35118. return rc;
  35119. }
  35120. /* See if the checksum matches the master journal name */
  35121. for(u=0; u<len; u++){
  35122. cksum -= zMaster[u];
  35123. }
  35124. if( cksum ){
  35125. /* If the checksum doesn't add up, then one or more of the disk sectors
  35126. ** containing the master journal filename is corrupted. This means
  35127. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  35128. ** master-journal filename.
  35129. */
  35130. len = 0;
  35131. }
  35132. zMaster[len] = '\0';
  35133. return SQLITE_OK;
  35134. }
  35135. /*
  35136. ** Return the offset of the sector boundary at or immediately
  35137. ** following the value in pPager->journalOff, assuming a sector
  35138. ** size of pPager->sectorSize bytes.
  35139. **
  35140. ** i.e for a sector size of 512:
  35141. **
  35142. ** Pager.journalOff Return value
  35143. ** ---------------------------------------
  35144. ** 0 0
  35145. ** 512 512
  35146. ** 100 512
  35147. ** 2000 2048
  35148. **
  35149. */
  35150. static i64 journalHdrOffset(Pager *pPager){
  35151. i64 offset = 0;
  35152. i64 c = pPager->journalOff;
  35153. if( c ){
  35154. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  35155. }
  35156. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  35157. assert( offset>=c );
  35158. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  35159. return offset;
  35160. }
  35161. /*
  35162. ** The journal file must be open when this function is called.
  35163. **
  35164. ** This function is a no-op if the journal file has not been written to
  35165. ** within the current transaction (i.e. if Pager.journalOff==0).
  35166. **
  35167. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  35168. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  35169. ** zero the 28-byte header at the start of the journal file. In either case,
  35170. ** if the pager is not in no-sync mode, sync the journal file immediately
  35171. ** after writing or truncating it.
  35172. **
  35173. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  35174. ** following the truncation or zeroing described above the size of the
  35175. ** journal file in bytes is larger than this value, then truncate the
  35176. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  35177. ** not need to be synced following this operation.
  35178. **
  35179. ** If an IO error occurs, abandon processing and return the IO error code.
  35180. ** Otherwise, return SQLITE_OK.
  35181. */
  35182. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  35183. int rc = SQLITE_OK; /* Return code */
  35184. assert( isOpen(pPager->jfd) );
  35185. if( pPager->journalOff ){
  35186. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  35187. IOTRACE(("JZEROHDR %p\n", pPager))
  35188. if( doTruncate || iLimit==0 ){
  35189. rc = sqlite3OsTruncate(pPager->jfd, 0);
  35190. }else{
  35191. static const char zeroHdr[28] = {0};
  35192. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  35193. }
  35194. if( rc==SQLITE_OK && !pPager->noSync ){
  35195. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  35196. }
  35197. /* At this point the transaction is committed but the write lock
  35198. ** is still held on the file. If there is a size limit configured for
  35199. ** the persistent journal and the journal file currently consumes more
  35200. ** space than that limit allows for, truncate it now. There is no need
  35201. ** to sync the file following this operation.
  35202. */
  35203. if( rc==SQLITE_OK && iLimit>0 ){
  35204. i64 sz;
  35205. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  35206. if( rc==SQLITE_OK && sz>iLimit ){
  35207. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  35208. }
  35209. }
  35210. }
  35211. return rc;
  35212. }
  35213. /*
  35214. ** The journal file must be open when this routine is called. A journal
  35215. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  35216. ** current location.
  35217. **
  35218. ** The format for the journal header is as follows:
  35219. ** - 8 bytes: Magic identifying journal format.
  35220. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  35221. ** - 4 bytes: Random number used for page hash.
  35222. ** - 4 bytes: Initial database page count.
  35223. ** - 4 bytes: Sector size used by the process that wrote this journal.
  35224. ** - 4 bytes: Database page size.
  35225. **
  35226. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  35227. */
  35228. static int writeJournalHdr(Pager *pPager){
  35229. int rc = SQLITE_OK; /* Return code */
  35230. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  35231. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  35232. u32 nWrite; /* Bytes of header sector written */
  35233. int ii; /* Loop counter */
  35234. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  35235. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  35236. nHeader = JOURNAL_HDR_SZ(pPager);
  35237. }
  35238. /* If there are active savepoints and any of them were created
  35239. ** since the most recent journal header was written, update the
  35240. ** PagerSavepoint.iHdrOffset fields now.
  35241. */
  35242. for(ii=0; ii<pPager->nSavepoint; ii++){
  35243. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  35244. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  35245. }
  35246. }
  35247. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  35248. /*
  35249. ** Write the nRec Field - the number of page records that follow this
  35250. ** journal header. Normally, zero is written to this value at this time.
  35251. ** After the records are added to the journal (and the journal synced,
  35252. ** if in full-sync mode), the zero is overwritten with the true number
  35253. ** of records (see syncJournal()).
  35254. **
  35255. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  35256. ** reading the journal this value tells SQLite to assume that the
  35257. ** rest of the journal file contains valid page records. This assumption
  35258. ** is dangerous, as if a failure occurred whilst writing to the journal
  35259. ** file it may contain some garbage data. There are two scenarios
  35260. ** where this risk can be ignored:
  35261. **
  35262. ** * When the pager is in no-sync mode. Corruption can follow a
  35263. ** power failure in this case anyway.
  35264. **
  35265. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  35266. ** that garbage data is never appended to the journal file.
  35267. */
  35268. assert( isOpen(pPager->fd) || pPager->noSync );
  35269. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  35270. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  35271. ){
  35272. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  35273. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  35274. }else{
  35275. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  35276. }
  35277. /* The random check-hash initialiser */
  35278. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  35279. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  35280. /* The initial database size */
  35281. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  35282. /* The assumed sector size for this process */
  35283. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  35284. /* The page size */
  35285. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  35286. /* Initializing the tail of the buffer is not necessary. Everything
  35287. ** works find if the following memset() is omitted. But initializing
  35288. ** the memory prevents valgrind from complaining, so we are willing to
  35289. ** take the performance hit.
  35290. */
  35291. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  35292. nHeader-(sizeof(aJournalMagic)+20));
  35293. /* In theory, it is only necessary to write the 28 bytes that the
  35294. ** journal header consumes to the journal file here. Then increment the
  35295. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  35296. ** record is written to the following sector (leaving a gap in the file
  35297. ** that will be implicitly filled in by the OS).
  35298. **
  35299. ** However it has been discovered that on some systems this pattern can
  35300. ** be significantly slower than contiguously writing data to the file,
  35301. ** even if that means explicitly writing data to the block of
  35302. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  35303. ** is done.
  35304. **
  35305. ** The loop is required here in case the sector-size is larger than the
  35306. ** database page size. Since the zHeader buffer is only Pager.pageSize
  35307. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  35308. ** to populate the entire journal header sector.
  35309. */
  35310. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  35311. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  35312. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  35313. assert( pPager->journalHdr <= pPager->journalOff );
  35314. pPager->journalOff += nHeader;
  35315. }
  35316. return rc;
  35317. }
  35318. /*
  35319. ** The journal file must be open when this is called. A journal header file
  35320. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  35321. ** file. The current location in the journal file is given by
  35322. ** pPager->journalOff. See comments above function writeJournalHdr() for
  35323. ** a description of the journal header format.
  35324. **
  35325. ** If the header is read successfully, *pNRec is set to the number of
  35326. ** page records following this header and *pDbSize is set to the size of the
  35327. ** database before the transaction began, in pages. Also, pPager->cksumInit
  35328. ** is set to the value read from the journal header. SQLITE_OK is returned
  35329. ** in this case.
  35330. **
  35331. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  35332. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  35333. ** cannot be read from the journal file an error code is returned.
  35334. */
  35335. static int readJournalHdr(
  35336. Pager *pPager, /* Pager object */
  35337. int isHot,
  35338. i64 journalSize, /* Size of the open journal file in bytes */
  35339. u32 *pNRec, /* OUT: Value read from the nRec field */
  35340. u32 *pDbSize /* OUT: Value of original database size field */
  35341. ){
  35342. int rc; /* Return code */
  35343. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  35344. i64 iHdrOff; /* Offset of journal header being read */
  35345. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  35346. /* Advance Pager.journalOff to the start of the next sector. If the
  35347. ** journal file is too small for there to be a header stored at this
  35348. ** point, return SQLITE_DONE.
  35349. */
  35350. pPager->journalOff = journalHdrOffset(pPager);
  35351. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  35352. return SQLITE_DONE;
  35353. }
  35354. iHdrOff = pPager->journalOff;
  35355. /* Read in the first 8 bytes of the journal header. If they do not match
  35356. ** the magic string found at the start of each journal header, return
  35357. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  35358. ** proceed.
  35359. */
  35360. if( isHot || iHdrOff!=pPager->journalHdr ){
  35361. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  35362. if( rc ){
  35363. return rc;
  35364. }
  35365. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  35366. return SQLITE_DONE;
  35367. }
  35368. }
  35369. /* Read the first three 32-bit fields of the journal header: The nRec
  35370. ** field, the checksum-initializer and the database size at the start
  35371. ** of the transaction. Return an error code if anything goes wrong.
  35372. */
  35373. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  35374. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  35375. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  35376. ){
  35377. return rc;
  35378. }
  35379. if( pPager->journalOff==0 ){
  35380. u32 iPageSize; /* Page-size field of journal header */
  35381. u32 iSectorSize; /* Sector-size field of journal header */
  35382. /* Read the page-size and sector-size journal header fields. */
  35383. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  35384. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  35385. ){
  35386. return rc;
  35387. }
  35388. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  35389. ** journal header to zero. In this case, assume that the Pager.pageSize
  35390. ** variable is already set to the correct page size.
  35391. */
  35392. if( iPageSize==0 ){
  35393. iPageSize = pPager->pageSize;
  35394. }
  35395. /* Check that the values read from the page-size and sector-size fields
  35396. ** are within range. To be 'in range', both values need to be a power
  35397. ** of two greater than or equal to 512 or 32, and not greater than their
  35398. ** respective compile time maximum limits.
  35399. */
  35400. if( iPageSize<512 || iSectorSize<32
  35401. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  35402. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  35403. ){
  35404. /* If the either the page-size or sector-size in the journal-header is
  35405. ** invalid, then the process that wrote the journal-header must have
  35406. ** crashed before the header was synced. In this case stop reading
  35407. ** the journal file here.
  35408. */
  35409. return SQLITE_DONE;
  35410. }
  35411. /* Update the page-size to match the value read from the journal.
  35412. ** Use a testcase() macro to make sure that malloc failure within
  35413. ** PagerSetPagesize() is tested.
  35414. */
  35415. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  35416. testcase( rc!=SQLITE_OK );
  35417. /* Update the assumed sector-size to match the value used by
  35418. ** the process that created this journal. If this journal was
  35419. ** created by a process other than this one, then this routine
  35420. ** is being called from within pager_playback(). The local value
  35421. ** of Pager.sectorSize is restored at the end of that routine.
  35422. */
  35423. pPager->sectorSize = iSectorSize;
  35424. }
  35425. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  35426. return rc;
  35427. }
  35428. /*
  35429. ** Write the supplied master journal name into the journal file for pager
  35430. ** pPager at the current location. The master journal name must be the last
  35431. ** thing written to a journal file. If the pager is in full-sync mode, the
  35432. ** journal file descriptor is advanced to the next sector boundary before
  35433. ** anything is written. The format is:
  35434. **
  35435. ** + 4 bytes: PAGER_MJ_PGNO.
  35436. ** + N bytes: Master journal filename in utf-8.
  35437. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  35438. ** + 4 bytes: Master journal name checksum.
  35439. ** + 8 bytes: aJournalMagic[].
  35440. **
  35441. ** The master journal page checksum is the sum of the bytes in the master
  35442. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  35443. **
  35444. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  35445. ** this call is a no-op.
  35446. */
  35447. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  35448. int rc; /* Return code */
  35449. int nMaster; /* Length of string zMaster */
  35450. i64 iHdrOff; /* Offset of header in journal file */
  35451. i64 jrnlSize; /* Size of journal file on disk */
  35452. u32 cksum = 0; /* Checksum of string zMaster */
  35453. assert( pPager->setMaster==0 );
  35454. assert( !pagerUseWal(pPager) );
  35455. if( !zMaster
  35456. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  35457. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  35458. ){
  35459. return SQLITE_OK;
  35460. }
  35461. pPager->setMaster = 1;
  35462. assert( isOpen(pPager->jfd) );
  35463. assert( pPager->journalHdr <= pPager->journalOff );
  35464. /* Calculate the length in bytes and the checksum of zMaster */
  35465. for(nMaster=0; zMaster[nMaster]; nMaster++){
  35466. cksum += zMaster[nMaster];
  35467. }
  35468. /* If in full-sync mode, advance to the next disk sector before writing
  35469. ** the master journal name. This is in case the previous page written to
  35470. ** the journal has already been synced.
  35471. */
  35472. if( pPager->fullSync ){
  35473. pPager->journalOff = journalHdrOffset(pPager);
  35474. }
  35475. iHdrOff = pPager->journalOff;
  35476. /* Write the master journal data to the end of the journal file. If
  35477. ** an error occurs, return the error code to the caller.
  35478. */
  35479. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  35480. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  35481. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  35482. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  35483. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  35484. ){
  35485. return rc;
  35486. }
  35487. pPager->journalOff += (nMaster+20);
  35488. /* If the pager is in peristent-journal mode, then the physical
  35489. ** journal-file may extend past the end of the master-journal name
  35490. ** and 8 bytes of magic data just written to the file. This is
  35491. ** dangerous because the code to rollback a hot-journal file
  35492. ** will not be able to find the master-journal name to determine
  35493. ** whether or not the journal is hot.
  35494. **
  35495. ** Easiest thing to do in this scenario is to truncate the journal
  35496. ** file to the required size.
  35497. */
  35498. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  35499. && jrnlSize>pPager->journalOff
  35500. ){
  35501. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  35502. }
  35503. return rc;
  35504. }
  35505. /*
  35506. ** Find a page in the hash table given its page number. Return
  35507. ** a pointer to the page or NULL if the requested page is not
  35508. ** already in memory.
  35509. */
  35510. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  35511. PgHdr *p; /* Return value */
  35512. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  35513. ** fail, since no attempt to allocate dynamic memory will be made.
  35514. */
  35515. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  35516. return p;
  35517. }
  35518. /*
  35519. ** Discard the entire contents of the in-memory page-cache.
  35520. */
  35521. static void pager_reset(Pager *pPager){
  35522. sqlite3BackupRestart(pPager->pBackup);
  35523. sqlite3PcacheClear(pPager->pPCache);
  35524. }
  35525. /*
  35526. ** Free all structures in the Pager.aSavepoint[] array and set both
  35527. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  35528. ** if it is open and the pager is not in exclusive mode.
  35529. */
  35530. static void releaseAllSavepoints(Pager *pPager){
  35531. int ii; /* Iterator for looping through Pager.aSavepoint */
  35532. for(ii=0; ii<pPager->nSavepoint; ii++){
  35533. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  35534. }
  35535. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  35536. sqlite3OsClose(pPager->sjfd);
  35537. }
  35538. sqlite3_free(pPager->aSavepoint);
  35539. pPager->aSavepoint = 0;
  35540. pPager->nSavepoint = 0;
  35541. pPager->nSubRec = 0;
  35542. }
  35543. /*
  35544. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  35545. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  35546. ** or SQLITE_NOMEM if a malloc failure occurs.
  35547. */
  35548. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  35549. int ii; /* Loop counter */
  35550. int rc = SQLITE_OK; /* Result code */
  35551. for(ii=0; ii<pPager->nSavepoint; ii++){
  35552. PagerSavepoint *p = &pPager->aSavepoint[ii];
  35553. if( pgno<=p->nOrig ){
  35554. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  35555. testcase( rc==SQLITE_NOMEM );
  35556. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  35557. }
  35558. }
  35559. return rc;
  35560. }
  35561. /*
  35562. ** This function is a no-op if the pager is in exclusive mode and not
  35563. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  35564. ** state.
  35565. **
  35566. ** If the pager is not in exclusive-access mode, the database file is
  35567. ** completely unlocked. If the file is unlocked and the file-system does
  35568. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  35569. ** closed (if it is open).
  35570. **
  35571. ** If the pager is in ERROR state when this function is called, the
  35572. ** contents of the pager cache are discarded before switching back to
  35573. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  35574. ** or not, any journal file left in the file-system will be treated
  35575. ** as a hot-journal and rolled back the next time a read-transaction
  35576. ** is opened (by this or by any other connection).
  35577. */
  35578. static void pager_unlock(Pager *pPager){
  35579. assert( pPager->eState==PAGER_READER
  35580. || pPager->eState==PAGER_OPEN
  35581. || pPager->eState==PAGER_ERROR
  35582. );
  35583. sqlite3BitvecDestroy(pPager->pInJournal);
  35584. pPager->pInJournal = 0;
  35585. releaseAllSavepoints(pPager);
  35586. if( pagerUseWal(pPager) ){
  35587. assert( !isOpen(pPager->jfd) );
  35588. sqlite3WalEndReadTransaction(pPager->pWal);
  35589. pPager->eState = PAGER_OPEN;
  35590. }else if( !pPager->exclusiveMode ){
  35591. int rc; /* Error code returned by pagerUnlockDb() */
  35592. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  35593. /* If the operating system support deletion of open files, then
  35594. ** close the journal file when dropping the database lock. Otherwise
  35595. ** another connection with journal_mode=delete might delete the file
  35596. ** out from under us.
  35597. */
  35598. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  35599. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  35600. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  35601. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  35602. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  35603. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  35604. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  35605. || 1!=(pPager->journalMode & 5)
  35606. ){
  35607. sqlite3OsClose(pPager->jfd);
  35608. }
  35609. /* If the pager is in the ERROR state and the call to unlock the database
  35610. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  35611. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  35612. ** is necessary.
  35613. */
  35614. rc = pagerUnlockDb(pPager, NO_LOCK);
  35615. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  35616. pPager->eLock = UNKNOWN_LOCK;
  35617. }
  35618. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  35619. ** without clearing the error code. This is intentional - the error
  35620. ** code is cleared and the cache reset in the block below.
  35621. */
  35622. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  35623. pPager->changeCountDone = 0;
  35624. pPager->eState = PAGER_OPEN;
  35625. }
  35626. /* If Pager.errCode is set, the contents of the pager cache cannot be
  35627. ** trusted. Now that there are no outstanding references to the pager,
  35628. ** it can safely move back to PAGER_OPEN state. This happens in both
  35629. ** normal and exclusive-locking mode.
  35630. */
  35631. if( pPager->errCode ){
  35632. assert( !MEMDB );
  35633. pager_reset(pPager);
  35634. pPager->changeCountDone = pPager->tempFile;
  35635. pPager->eState = PAGER_OPEN;
  35636. pPager->errCode = SQLITE_OK;
  35637. }
  35638. pPager->journalOff = 0;
  35639. pPager->journalHdr = 0;
  35640. pPager->setMaster = 0;
  35641. }
  35642. /*
  35643. ** This function is called whenever an IOERR or FULL error that requires
  35644. ** the pager to transition into the ERROR state may ahve occurred.
  35645. ** The first argument is a pointer to the pager structure, the second
  35646. ** the error-code about to be returned by a pager API function. The
  35647. ** value returned is a copy of the second argument to this function.
  35648. **
  35649. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  35650. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  35651. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  35652. ** all major API calls on the Pager will immediately return Pager.errCode.
  35653. **
  35654. ** The ERROR state indicates that the contents of the pager-cache
  35655. ** cannot be trusted. This state can be cleared by completely discarding
  35656. ** the contents of the pager-cache. If a transaction was active when
  35657. ** the persistent error occurred, then the rollback journal may need
  35658. ** to be replayed to restore the contents of the database file (as if
  35659. ** it were a hot-journal).
  35660. */
  35661. static int pager_error(Pager *pPager, int rc){
  35662. int rc2 = rc & 0xff;
  35663. assert( rc==SQLITE_OK || !MEMDB );
  35664. assert(
  35665. pPager->errCode==SQLITE_FULL ||
  35666. pPager->errCode==SQLITE_OK ||
  35667. (pPager->errCode & 0xff)==SQLITE_IOERR
  35668. );
  35669. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  35670. pPager->errCode = rc;
  35671. pPager->eState = PAGER_ERROR;
  35672. }
  35673. return rc;
  35674. }
  35675. /*
  35676. ** This routine ends a transaction. A transaction is usually ended by
  35677. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  35678. ** after rollback of a hot-journal, or if an error occurs while opening
  35679. ** the journal file or writing the very first journal-header of a
  35680. ** database transaction.
  35681. **
  35682. ** This routine is never called in PAGER_ERROR state. If it is called
  35683. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  35684. ** exclusive than a RESERVED lock, it is a no-op.
  35685. **
  35686. ** Otherwise, any active savepoints are released.
  35687. **
  35688. ** If the journal file is open, then it is "finalized". Once a journal
  35689. ** file has been finalized it is not possible to use it to roll back a
  35690. ** transaction. Nor will it be considered to be a hot-journal by this
  35691. ** or any other database connection. Exactly how a journal is finalized
  35692. ** depends on whether or not the pager is running in exclusive mode and
  35693. ** the current journal-mode (Pager.journalMode value), as follows:
  35694. **
  35695. ** journalMode==MEMORY
  35696. ** Journal file descriptor is simply closed. This destroys an
  35697. ** in-memory journal.
  35698. **
  35699. ** journalMode==TRUNCATE
  35700. ** Journal file is truncated to zero bytes in size.
  35701. **
  35702. ** journalMode==PERSIST
  35703. ** The first 28 bytes of the journal file are zeroed. This invalidates
  35704. ** the first journal header in the file, and hence the entire journal
  35705. ** file. An invalid journal file cannot be rolled back.
  35706. **
  35707. ** journalMode==DELETE
  35708. ** The journal file is closed and deleted using sqlite3OsDelete().
  35709. **
  35710. ** If the pager is running in exclusive mode, this method of finalizing
  35711. ** the journal file is never used. Instead, if the journalMode is
  35712. ** DELETE and the pager is in exclusive mode, the method described under
  35713. ** journalMode==PERSIST is used instead.
  35714. **
  35715. ** After the journal is finalized, the pager moves to PAGER_READER state.
  35716. ** If running in non-exclusive rollback mode, the lock on the file is
  35717. ** downgraded to a SHARED_LOCK.
  35718. **
  35719. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  35720. ** any of the IO operations to finalize the journal file or unlock the
  35721. ** database then the IO error code is returned to the user. If the
  35722. ** operation to finalize the journal file fails, then the code still
  35723. ** tries to unlock the database file if not in exclusive mode. If the
  35724. ** unlock operation fails as well, then the first error code related
  35725. ** to the first error encountered (the journal finalization one) is
  35726. ** returned.
  35727. */
  35728. static int pager_end_transaction(Pager *pPager, int hasMaster){
  35729. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  35730. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  35731. /* Do nothing if the pager does not have an open write transaction
  35732. ** or at least a RESERVED lock. This function may be called when there
  35733. ** is no write-transaction active but a RESERVED or greater lock is
  35734. ** held under two circumstances:
  35735. **
  35736. ** 1. After a successful hot-journal rollback, it is called with
  35737. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  35738. **
  35739. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  35740. ** lock switches back to locking_mode=normal and then executes a
  35741. ** read-transaction, this function is called with eState==PAGER_READER
  35742. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  35743. */
  35744. assert( assert_pager_state(pPager) );
  35745. assert( pPager->eState!=PAGER_ERROR );
  35746. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  35747. return SQLITE_OK;
  35748. }
  35749. releaseAllSavepoints(pPager);
  35750. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  35751. if( isOpen(pPager->jfd) ){
  35752. assert( !pagerUseWal(pPager) );
  35753. /* Finalize the journal file. */
  35754. if( sqlite3IsMemJournal(pPager->jfd) ){
  35755. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  35756. sqlite3OsClose(pPager->jfd);
  35757. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  35758. if( pPager->journalOff==0 ){
  35759. rc = SQLITE_OK;
  35760. }else{
  35761. rc = sqlite3OsTruncate(pPager->jfd, 0);
  35762. }
  35763. pPager->journalOff = 0;
  35764. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  35765. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  35766. ){
  35767. rc = zeroJournalHdr(pPager, hasMaster);
  35768. pPager->journalOff = 0;
  35769. }else{
  35770. /* This branch may be executed with Pager.journalMode==MEMORY if
  35771. ** a hot-journal was just rolled back. In this case the journal
  35772. ** file should be closed and deleted. If this connection writes to
  35773. ** the database file, it will do so using an in-memory journal.
  35774. */
  35775. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  35776. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  35777. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  35778. );
  35779. sqlite3OsClose(pPager->jfd);
  35780. if( !pPager->tempFile ){
  35781. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  35782. }
  35783. }
  35784. }
  35785. #ifdef SQLITE_CHECK_PAGES
  35786. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  35787. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  35788. PgHdr *p = pager_lookup(pPager, 1);
  35789. if( p ){
  35790. p->pageHash = 0;
  35791. sqlite3PagerUnref(p);
  35792. }
  35793. }
  35794. #endif
  35795. sqlite3BitvecDestroy(pPager->pInJournal);
  35796. pPager->pInJournal = 0;
  35797. pPager->nRec = 0;
  35798. sqlite3PcacheCleanAll(pPager->pPCache);
  35799. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  35800. if( pagerUseWal(pPager) ){
  35801. /* Drop the WAL write-lock, if any. Also, if the connection was in
  35802. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  35803. ** lock held on the database file.
  35804. */
  35805. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  35806. assert( rc2==SQLITE_OK );
  35807. }
  35808. if( !pPager->exclusiveMode
  35809. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  35810. ){
  35811. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  35812. pPager->changeCountDone = 0;
  35813. }
  35814. pPager->eState = PAGER_READER;
  35815. pPager->setMaster = 0;
  35816. return (rc==SQLITE_OK?rc2:rc);
  35817. }
  35818. /*
  35819. ** Execute a rollback if a transaction is active and unlock the
  35820. ** database file.
  35821. **
  35822. ** If the pager has already entered the ERROR state, do not attempt
  35823. ** the rollback at this time. Instead, pager_unlock() is called. The
  35824. ** call to pager_unlock() will discard all in-memory pages, unlock
  35825. ** the database file and move the pager back to OPEN state. If this
  35826. ** means that there is a hot-journal left in the file-system, the next
  35827. ** connection to obtain a shared lock on the pager (which may be this one)
  35828. ** will roll it back.
  35829. **
  35830. ** If the pager has not already entered the ERROR state, but an IO or
  35831. ** malloc error occurs during a rollback, then this will itself cause
  35832. ** the pager to enter the ERROR state. Which will be cleared by the
  35833. ** call to pager_unlock(), as described above.
  35834. */
  35835. static void pagerUnlockAndRollback(Pager *pPager){
  35836. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  35837. assert( assert_pager_state(pPager) );
  35838. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  35839. sqlite3BeginBenignMalloc();
  35840. sqlite3PagerRollback(pPager);
  35841. sqlite3EndBenignMalloc();
  35842. }else if( !pPager->exclusiveMode ){
  35843. assert( pPager->eState==PAGER_READER );
  35844. pager_end_transaction(pPager, 0);
  35845. }
  35846. }
  35847. pager_unlock(pPager);
  35848. }
  35849. /*
  35850. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  35851. ** of data. Compute and return a checksum based ont the contents of the
  35852. ** page of data and the current value of pPager->cksumInit.
  35853. **
  35854. ** This is not a real checksum. It is really just the sum of the
  35855. ** random initial value (pPager->cksumInit) and every 200th byte
  35856. ** of the page data, starting with byte offset (pPager->pageSize%200).
  35857. ** Each byte is interpreted as an 8-bit unsigned integer.
  35858. **
  35859. ** Changing the formula used to compute this checksum results in an
  35860. ** incompatible journal file format.
  35861. **
  35862. ** If journal corruption occurs due to a power failure, the most likely
  35863. ** scenario is that one end or the other of the record will be changed.
  35864. ** It is much less likely that the two ends of the journal record will be
  35865. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  35866. ** though fast and simple, catches the mostly likely kind of corruption.
  35867. */
  35868. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  35869. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  35870. int i = pPager->pageSize-200; /* Loop counter */
  35871. while( i>0 ){
  35872. cksum += aData[i];
  35873. i -= 200;
  35874. }
  35875. return cksum;
  35876. }
  35877. /*
  35878. ** Report the current page size and number of reserved bytes back
  35879. ** to the codec.
  35880. */
  35881. #ifdef SQLITE_HAS_CODEC
  35882. static void pagerReportSize(Pager *pPager){
  35883. if( pPager->xCodecSizeChng ){
  35884. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  35885. (int)pPager->nReserve);
  35886. }
  35887. }
  35888. #else
  35889. # define pagerReportSize(X) /* No-op if we do not support a codec */
  35890. #endif
  35891. /*
  35892. ** Read a single page from either the journal file (if isMainJrnl==1) or
  35893. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  35894. ** The page begins at offset *pOffset into the file. The *pOffset
  35895. ** value is increased to the start of the next page in the journal.
  35896. **
  35897. ** The main rollback journal uses checksums - the statement journal does
  35898. ** not.
  35899. **
  35900. ** If the page number of the page record read from the (sub-)journal file
  35901. ** is greater than the current value of Pager.dbSize, then playback is
  35902. ** skipped and SQLITE_OK is returned.
  35903. **
  35904. ** If pDone is not NULL, then it is a record of pages that have already
  35905. ** been played back. If the page at *pOffset has already been played back
  35906. ** (if the corresponding pDone bit is set) then skip the playback.
  35907. ** Make sure the pDone bit corresponding to the *pOffset page is set
  35908. ** prior to returning.
  35909. **
  35910. ** If the page record is successfully read from the (sub-)journal file
  35911. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  35912. ** while reading the record from the (sub-)journal file or while writing
  35913. ** to the database file, then the IO error code is returned. If data
  35914. ** is successfully read from the (sub-)journal file but appears to be
  35915. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  35916. ** two circumstances:
  35917. **
  35918. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  35919. ** * If the record is being rolled back from the main journal file
  35920. ** and the checksum field does not match the record content.
  35921. **
  35922. ** Neither of these two scenarios are possible during a savepoint rollback.
  35923. **
  35924. ** If this is a savepoint rollback, then memory may have to be dynamically
  35925. ** allocated by this function. If this is the case and an allocation fails,
  35926. ** SQLITE_NOMEM is returned.
  35927. */
  35928. static int pager_playback_one_page(
  35929. Pager *pPager, /* The pager being played back */
  35930. i64 *pOffset, /* Offset of record to playback */
  35931. Bitvec *pDone, /* Bitvec of pages already played back */
  35932. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  35933. int isSavepnt /* True for a savepoint rollback */
  35934. ){
  35935. int rc;
  35936. PgHdr *pPg; /* An existing page in the cache */
  35937. Pgno pgno; /* The page number of a page in journal */
  35938. u32 cksum; /* Checksum used for sanity checking */
  35939. char *aData; /* Temporary storage for the page */
  35940. sqlite3_file *jfd; /* The file descriptor for the journal file */
  35941. int isSynced; /* True if journal page is synced */
  35942. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  35943. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  35944. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  35945. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  35946. aData = pPager->pTmpSpace;
  35947. assert( aData ); /* Temp storage must have already been allocated */
  35948. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  35949. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  35950. ** or savepoint rollback done at the request of the caller) or this is
  35951. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  35952. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  35953. ** only reads from the main journal, not the sub-journal.
  35954. */
  35955. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  35956. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  35957. );
  35958. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  35959. /* Read the page number and page data from the journal or sub-journal
  35960. ** file. Return an error code to the caller if an IO error occurs.
  35961. */
  35962. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  35963. rc = read32bits(jfd, *pOffset, &pgno);
  35964. if( rc!=SQLITE_OK ) return rc;
  35965. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  35966. if( rc!=SQLITE_OK ) return rc;
  35967. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  35968. /* Sanity checking on the page. This is more important that I originally
  35969. ** thought. If a power failure occurs while the journal is being written,
  35970. ** it could cause invalid data to be written into the journal. We need to
  35971. ** detect this invalid data (with high probability) and ignore it.
  35972. */
  35973. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  35974. assert( !isSavepnt );
  35975. return SQLITE_DONE;
  35976. }
  35977. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  35978. return SQLITE_OK;
  35979. }
  35980. if( isMainJrnl ){
  35981. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  35982. if( rc ) return rc;
  35983. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  35984. return SQLITE_DONE;
  35985. }
  35986. }
  35987. /* If this page has already been played by before during the current
  35988. ** rollback, then don't bother to play it back again.
  35989. */
  35990. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  35991. return rc;
  35992. }
  35993. /* When playing back page 1, restore the nReserve setting
  35994. */
  35995. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  35996. pPager->nReserve = ((u8*)aData)[20];
  35997. pagerReportSize(pPager);
  35998. }
  35999. /* If the pager is in CACHEMOD state, then there must be a copy of this
  36000. ** page in the pager cache. In this case just update the pager cache,
  36001. ** not the database file. The page is left marked dirty in this case.
  36002. **
  36003. ** An exception to the above rule: If the database is in no-sync mode
  36004. ** and a page is moved during an incremental vacuum then the page may
  36005. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  36006. ** during a Movepage() call, then the page may not be in the cache
  36007. ** either. So the condition described in the above paragraph is not
  36008. ** assert()able.
  36009. **
  36010. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  36011. ** pager cache if it exists and the main file. The page is then marked
  36012. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  36013. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  36014. ** if the pager is in OPEN state.
  36015. **
  36016. ** Ticket #1171: The statement journal might contain page content that is
  36017. ** different from the page content at the start of the transaction.
  36018. ** This occurs when a page is changed prior to the start of a statement
  36019. ** then changed again within the statement. When rolling back such a
  36020. ** statement we must not write to the original database unless we know
  36021. ** for certain that original page contents are synced into the main rollback
  36022. ** journal. Otherwise, a power loss might leave modified data in the
  36023. ** database file without an entry in the rollback journal that can
  36024. ** restore the database to its original form. Two conditions must be
  36025. ** met before writing to the database files. (1) the database must be
  36026. ** locked. (2) we know that the original page content is fully synced
  36027. ** in the main journal either because the page is not in cache or else
  36028. ** the page is marked as needSync==0.
  36029. **
  36030. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  36031. ** is possible to fail a statement on a database that does not yet exist.
  36032. ** Do not attempt to write if database file has never been opened.
  36033. */
  36034. if( pagerUseWal(pPager) ){
  36035. pPg = 0;
  36036. }else{
  36037. pPg = pager_lookup(pPager, pgno);
  36038. }
  36039. assert( pPg || !MEMDB );
  36040. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  36041. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  36042. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  36043. (isMainJrnl?"main-journal":"sub-journal")
  36044. ));
  36045. if( isMainJrnl ){
  36046. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  36047. }else{
  36048. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  36049. }
  36050. if( isOpen(pPager->fd)
  36051. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  36052. && isSynced
  36053. ){
  36054. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  36055. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  36056. assert( !pagerUseWal(pPager) );
  36057. rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
  36058. if( pgno>pPager->dbFileSize ){
  36059. pPager->dbFileSize = pgno;
  36060. }
  36061. if( pPager->pBackup ){
  36062. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  36063. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  36064. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  36065. }
  36066. }else if( !isMainJrnl && pPg==0 ){
  36067. /* If this is a rollback of a savepoint and data was not written to
  36068. ** the database and the page is not in-memory, there is a potential
  36069. ** problem. When the page is next fetched by the b-tree layer, it
  36070. ** will be read from the database file, which may or may not be
  36071. ** current.
  36072. **
  36073. ** There are a couple of different ways this can happen. All are quite
  36074. ** obscure. When running in synchronous mode, this can only happen
  36075. ** if the page is on the free-list at the start of the transaction, then
  36076. ** populated, then moved using sqlite3PagerMovepage().
  36077. **
  36078. ** The solution is to add an in-memory page to the cache containing
  36079. ** the data just read from the sub-journal. Mark the page as dirty
  36080. ** and if the pager requires a journal-sync, then mark the page as
  36081. ** requiring a journal-sync before it is written.
  36082. */
  36083. assert( isSavepnt );
  36084. assert( pPager->doNotSpill==0 );
  36085. pPager->doNotSpill++;
  36086. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  36087. assert( pPager->doNotSpill==1 );
  36088. pPager->doNotSpill--;
  36089. if( rc!=SQLITE_OK ) return rc;
  36090. pPg->flags &= ~PGHDR_NEED_READ;
  36091. sqlite3PcacheMakeDirty(pPg);
  36092. }
  36093. if( pPg ){
  36094. /* No page should ever be explicitly rolled back that is in use, except
  36095. ** for page 1 which is held in use in order to keep the lock on the
  36096. ** database active. However such a page may be rolled back as a result
  36097. ** of an internal error resulting in an automatic call to
  36098. ** sqlite3PagerRollback().
  36099. */
  36100. void *pData;
  36101. pData = pPg->pData;
  36102. memcpy(pData, (u8*)aData, pPager->pageSize);
  36103. pPager->xReiniter(pPg);
  36104. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  36105. /* If the contents of this page were just restored from the main
  36106. ** journal file, then its content must be as they were when the
  36107. ** transaction was first opened. In this case we can mark the page
  36108. ** as clean, since there will be no need to write it out to the
  36109. ** database.
  36110. **
  36111. ** There is one exception to this rule. If the page is being rolled
  36112. ** back as part of a savepoint (or statement) rollback from an
  36113. ** unsynced portion of the main journal file, then it is not safe
  36114. ** to mark the page as clean. This is because marking the page as
  36115. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  36116. ** already in the journal file (recorded in Pager.pInJournal) and
  36117. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  36118. ** again within this transaction, it will be marked as dirty but
  36119. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  36120. ** be written out into the database file before its journal file
  36121. ** segment is synced. If a crash occurs during or following this,
  36122. ** database corruption may ensue.
  36123. */
  36124. assert( !pagerUseWal(pPager) );
  36125. sqlite3PcacheMakeClean(pPg);
  36126. }
  36127. pager_set_pagehash(pPg);
  36128. /* If this was page 1, then restore the value of Pager.dbFileVers.
  36129. ** Do this before any decoding. */
  36130. if( pgno==1 ){
  36131. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  36132. }
  36133. /* Decode the page just read from disk */
  36134. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  36135. sqlite3PcacheRelease(pPg);
  36136. }
  36137. return rc;
  36138. }
  36139. /*
  36140. ** Parameter zMaster is the name of a master journal file. A single journal
  36141. ** file that referred to the master journal file has just been rolled back.
  36142. ** This routine checks if it is possible to delete the master journal file,
  36143. ** and does so if it is.
  36144. **
  36145. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  36146. ** available for use within this function.
  36147. **
  36148. ** When a master journal file is created, it is populated with the names
  36149. ** of all of its child journals, one after another, formatted as utf-8
  36150. ** encoded text. The end of each child journal file is marked with a
  36151. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  36152. ** file for a transaction involving two databases might be:
  36153. **
  36154. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  36155. **
  36156. ** A master journal file may only be deleted once all of its child
  36157. ** journals have been rolled back.
  36158. **
  36159. ** This function reads the contents of the master-journal file into
  36160. ** memory and loops through each of the child journal names. For
  36161. ** each child journal, it checks if:
  36162. **
  36163. ** * if the child journal exists, and if so
  36164. ** * if the child journal contains a reference to master journal
  36165. ** file zMaster
  36166. **
  36167. ** If a child journal can be found that matches both of the criteria
  36168. ** above, this function returns without doing anything. Otherwise, if
  36169. ** no such child journal can be found, file zMaster is deleted from
  36170. ** the file-system using sqlite3OsDelete().
  36171. **
  36172. ** If an IO error within this function, an error code is returned. This
  36173. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  36174. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  36175. ** occur, SQLITE_OK is returned.
  36176. **
  36177. ** TODO: This function allocates a single block of memory to load
  36178. ** the entire contents of the master journal file. This could be
  36179. ** a couple of kilobytes or so - potentially larger than the page
  36180. ** size.
  36181. */
  36182. static int pager_delmaster(Pager *pPager, const char *zMaster){
  36183. sqlite3_vfs *pVfs = pPager->pVfs;
  36184. int rc; /* Return code */
  36185. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  36186. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  36187. char *zMasterJournal = 0; /* Contents of master journal file */
  36188. i64 nMasterJournal; /* Size of master journal file */
  36189. char *zJournal; /* Pointer to one journal within MJ file */
  36190. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  36191. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  36192. /* Allocate space for both the pJournal and pMaster file descriptors.
  36193. ** If successful, open the master journal file for reading.
  36194. */
  36195. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  36196. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  36197. if( !pMaster ){
  36198. rc = SQLITE_NOMEM;
  36199. }else{
  36200. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  36201. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  36202. }
  36203. if( rc!=SQLITE_OK ) goto delmaster_out;
  36204. /* Load the entire master journal file into space obtained from
  36205. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  36206. ** sufficient space (in zMasterPtr) to hold the names of master
  36207. ** journal files extracted from regular rollback-journals.
  36208. */
  36209. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  36210. if( rc!=SQLITE_OK ) goto delmaster_out;
  36211. nMasterPtr = pVfs->mxPathname+1;
  36212. zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  36213. if( !zMasterJournal ){
  36214. rc = SQLITE_NOMEM;
  36215. goto delmaster_out;
  36216. }
  36217. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  36218. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  36219. if( rc!=SQLITE_OK ) goto delmaster_out;
  36220. zMasterJournal[nMasterJournal] = 0;
  36221. zJournal = zMasterJournal;
  36222. while( (zJournal-zMasterJournal)<nMasterJournal ){
  36223. int exists;
  36224. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  36225. if( rc!=SQLITE_OK ){
  36226. goto delmaster_out;
  36227. }
  36228. if( exists ){
  36229. /* One of the journals pointed to by the master journal exists.
  36230. ** Open it and check if it points at the master journal. If
  36231. ** so, return without deleting the master journal file.
  36232. */
  36233. int c;
  36234. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  36235. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  36236. if( rc!=SQLITE_OK ){
  36237. goto delmaster_out;
  36238. }
  36239. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  36240. sqlite3OsClose(pJournal);
  36241. if( rc!=SQLITE_OK ){
  36242. goto delmaster_out;
  36243. }
  36244. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  36245. if( c ){
  36246. /* We have a match. Do not delete the master journal file. */
  36247. goto delmaster_out;
  36248. }
  36249. }
  36250. zJournal += (sqlite3Strlen30(zJournal)+1);
  36251. }
  36252. sqlite3OsClose(pMaster);
  36253. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  36254. delmaster_out:
  36255. sqlite3_free(zMasterJournal);
  36256. if( pMaster ){
  36257. sqlite3OsClose(pMaster);
  36258. assert( !isOpen(pJournal) );
  36259. sqlite3_free(pMaster);
  36260. }
  36261. return rc;
  36262. }
  36263. /*
  36264. ** This function is used to change the actual size of the database
  36265. ** file in the file-system. This only happens when committing a transaction,
  36266. ** or rolling back a transaction (including rolling back a hot-journal).
  36267. **
  36268. ** If the main database file is not open, or the pager is not in either
  36269. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  36270. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  36271. ** If the file on disk is currently larger than nPage pages, then use the VFS
  36272. ** xTruncate() method to truncate it.
  36273. **
  36274. ** Or, it might might be the case that the file on disk is smaller than
  36275. ** nPage pages. Some operating system implementations can get confused if
  36276. ** you try to truncate a file to some size that is larger than it
  36277. ** currently is, so detect this case and write a single zero byte to
  36278. ** the end of the new file instead.
  36279. **
  36280. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  36281. ** the database file, return the error code to the caller.
  36282. */
  36283. static int pager_truncate(Pager *pPager, Pgno nPage){
  36284. int rc = SQLITE_OK;
  36285. assert( pPager->eState!=PAGER_ERROR );
  36286. assert( pPager->eState!=PAGER_READER );
  36287. if( isOpen(pPager->fd)
  36288. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  36289. ){
  36290. i64 currentSize, newSize;
  36291. int szPage = pPager->pageSize;
  36292. assert( pPager->eLock==EXCLUSIVE_LOCK );
  36293. /* TODO: Is it safe to use Pager.dbFileSize here? */
  36294. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  36295. newSize = szPage*(i64)nPage;
  36296. if( rc==SQLITE_OK && currentSize!=newSize ){
  36297. if( currentSize>newSize ){
  36298. rc = sqlite3OsTruncate(pPager->fd, newSize);
  36299. }else{
  36300. char *pTmp = pPager->pTmpSpace;
  36301. memset(pTmp, 0, szPage);
  36302. testcase( (newSize-szPage) < currentSize );
  36303. testcase( (newSize-szPage) == currentSize );
  36304. testcase( (newSize-szPage) > currentSize );
  36305. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  36306. }
  36307. if( rc==SQLITE_OK ){
  36308. pPager->dbFileSize = nPage;
  36309. }
  36310. }
  36311. }
  36312. return rc;
  36313. }
  36314. /*
  36315. ** Set the value of the Pager.sectorSize variable for the given
  36316. ** pager based on the value returned by the xSectorSize method
  36317. ** of the open database file. The sector size will be used used
  36318. ** to determine the size and alignment of journal header and
  36319. ** master journal pointers within created journal files.
  36320. **
  36321. ** For temporary files the effective sector size is always 512 bytes.
  36322. **
  36323. ** Otherwise, for non-temporary files, the effective sector size is
  36324. ** the value returned by the xSectorSize() method rounded up to 32 if
  36325. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  36326. ** is greater than MAX_SECTOR_SIZE.
  36327. */
  36328. static void setSectorSize(Pager *pPager){
  36329. assert( isOpen(pPager->fd) || pPager->tempFile );
  36330. if( !pPager->tempFile ){
  36331. /* Sector size doesn't matter for temporary files. Also, the file
  36332. ** may not have been opened yet, in which case the OsSectorSize()
  36333. ** call will segfault.
  36334. */
  36335. pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
  36336. }
  36337. if( pPager->sectorSize<32 ){
  36338. pPager->sectorSize = 512;
  36339. }
  36340. if( pPager->sectorSize>MAX_SECTOR_SIZE ){
  36341. assert( MAX_SECTOR_SIZE>=512 );
  36342. pPager->sectorSize = MAX_SECTOR_SIZE;
  36343. }
  36344. }
  36345. /*
  36346. ** Playback the journal and thus restore the database file to
  36347. ** the state it was in before we started making changes.
  36348. **
  36349. ** The journal file format is as follows:
  36350. **
  36351. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  36352. ** (2) 4 byte big-endian integer which is the number of valid page records
  36353. ** in the journal. If this value is 0xffffffff, then compute the
  36354. ** number of page records from the journal size.
  36355. ** (3) 4 byte big-endian integer which is the initial value for the
  36356. ** sanity checksum.
  36357. ** (4) 4 byte integer which is the number of pages to truncate the
  36358. ** database to during a rollback.
  36359. ** (5) 4 byte big-endian integer which is the sector size. The header
  36360. ** is this many bytes in size.
  36361. ** (6) 4 byte big-endian integer which is the page size.
  36362. ** (7) zero padding out to the next sector size.
  36363. ** (8) Zero or more pages instances, each as follows:
  36364. ** + 4 byte page number.
  36365. ** + pPager->pageSize bytes of data.
  36366. ** + 4 byte checksum
  36367. **
  36368. ** When we speak of the journal header, we mean the first 7 items above.
  36369. ** Each entry in the journal is an instance of the 8th item.
  36370. **
  36371. ** Call the value from the second bullet "nRec". nRec is the number of
  36372. ** valid page entries in the journal. In most cases, you can compute the
  36373. ** value of nRec from the size of the journal file. But if a power
  36374. ** failure occurred while the journal was being written, it could be the
  36375. ** case that the size of the journal file had already been increased but
  36376. ** the extra entries had not yet made it safely to disk. In such a case,
  36377. ** the value of nRec computed from the file size would be too large. For
  36378. ** that reason, we always use the nRec value in the header.
  36379. **
  36380. ** If the nRec value is 0xffffffff it means that nRec should be computed
  36381. ** from the file size. This value is used when the user selects the
  36382. ** no-sync option for the journal. A power failure could lead to corruption
  36383. ** in this case. But for things like temporary table (which will be
  36384. ** deleted when the power is restored) we don't care.
  36385. **
  36386. ** If the file opened as the journal file is not a well-formed
  36387. ** journal file then all pages up to the first corrupted page are rolled
  36388. ** back (or no pages if the journal header is corrupted). The journal file
  36389. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  36390. ** been encountered.
  36391. **
  36392. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  36393. ** and an error code is returned.
  36394. **
  36395. ** The isHot parameter indicates that we are trying to rollback a journal
  36396. ** that might be a hot journal. Or, it could be that the journal is
  36397. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  36398. ** If the journal really is hot, reset the pager cache prior rolling
  36399. ** back any content. If the journal is merely persistent, no reset is
  36400. ** needed.
  36401. */
  36402. static int pager_playback(Pager *pPager, int isHot){
  36403. sqlite3_vfs *pVfs = pPager->pVfs;
  36404. i64 szJ; /* Size of the journal file in bytes */
  36405. u32 nRec; /* Number of Records in the journal */
  36406. u32 u; /* Unsigned loop counter */
  36407. Pgno mxPg = 0; /* Size of the original file in pages */
  36408. int rc; /* Result code of a subroutine */
  36409. int res = 1; /* Value returned by sqlite3OsAccess() */
  36410. char *zMaster = 0; /* Name of master journal file if any */
  36411. int needPagerReset; /* True to reset page prior to first page rollback */
  36412. /* Figure out how many records are in the journal. Abort early if
  36413. ** the journal is empty.
  36414. */
  36415. assert( isOpen(pPager->jfd) );
  36416. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  36417. if( rc!=SQLITE_OK ){
  36418. goto end_playback;
  36419. }
  36420. /* Read the master journal name from the journal, if it is present.
  36421. ** If a master journal file name is specified, but the file is not
  36422. ** present on disk, then the journal is not hot and does not need to be
  36423. ** played back.
  36424. **
  36425. ** TODO: Technically the following is an error because it assumes that
  36426. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  36427. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  36428. ** mxPathname is 512, which is the same as the minimum allowable value
  36429. ** for pageSize.
  36430. */
  36431. zMaster = pPager->pTmpSpace;
  36432. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  36433. if( rc==SQLITE_OK && zMaster[0] ){
  36434. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  36435. }
  36436. zMaster = 0;
  36437. if( rc!=SQLITE_OK || !res ){
  36438. goto end_playback;
  36439. }
  36440. pPager->journalOff = 0;
  36441. needPagerReset = isHot;
  36442. /* This loop terminates either when a readJournalHdr() or
  36443. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  36444. ** occurs.
  36445. */
  36446. while( 1 ){
  36447. /* Read the next journal header from the journal file. If there are
  36448. ** not enough bytes left in the journal file for a complete header, or
  36449. ** it is corrupted, then a process must have failed while writing it.
  36450. ** This indicates nothing more needs to be rolled back.
  36451. */
  36452. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  36453. if( rc!=SQLITE_OK ){
  36454. if( rc==SQLITE_DONE ){
  36455. rc = SQLITE_OK;
  36456. }
  36457. goto end_playback;
  36458. }
  36459. /* If nRec is 0xffffffff, then this journal was created by a process
  36460. ** working in no-sync mode. This means that the rest of the journal
  36461. ** file consists of pages, there are no more journal headers. Compute
  36462. ** the value of nRec based on this assumption.
  36463. */
  36464. if( nRec==0xffffffff ){
  36465. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  36466. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  36467. }
  36468. /* If nRec is 0 and this rollback is of a transaction created by this
  36469. ** process and if this is the final header in the journal, then it means
  36470. ** that this part of the journal was being filled but has not yet been
  36471. ** synced to disk. Compute the number of pages based on the remaining
  36472. ** size of the file.
  36473. **
  36474. ** The third term of the test was added to fix ticket #2565.
  36475. ** When rolling back a hot journal, nRec==0 always means that the next
  36476. ** chunk of the journal contains zero pages to be rolled back. But
  36477. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  36478. ** the journal, it means that the journal might contain additional
  36479. ** pages that need to be rolled back and that the number of pages
  36480. ** should be computed based on the journal file size.
  36481. */
  36482. if( nRec==0 && !isHot &&
  36483. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  36484. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  36485. }
  36486. /* If this is the first header read from the journal, truncate the
  36487. ** database file back to its original size.
  36488. */
  36489. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  36490. rc = pager_truncate(pPager, mxPg);
  36491. if( rc!=SQLITE_OK ){
  36492. goto end_playback;
  36493. }
  36494. pPager->dbSize = mxPg;
  36495. }
  36496. /* Copy original pages out of the journal and back into the
  36497. ** database file and/or page cache.
  36498. */
  36499. for(u=0; u<nRec; u++){
  36500. if( needPagerReset ){
  36501. pager_reset(pPager);
  36502. needPagerReset = 0;
  36503. }
  36504. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  36505. if( rc!=SQLITE_OK ){
  36506. if( rc==SQLITE_DONE ){
  36507. rc = SQLITE_OK;
  36508. pPager->journalOff = szJ;
  36509. break;
  36510. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  36511. /* If the journal has been truncated, simply stop reading and
  36512. ** processing the journal. This might happen if the journal was
  36513. ** not completely written and synced prior to a crash. In that
  36514. ** case, the database should have never been written in the
  36515. ** first place so it is OK to simply abandon the rollback. */
  36516. rc = SQLITE_OK;
  36517. goto end_playback;
  36518. }else{
  36519. /* If we are unable to rollback, quit and return the error
  36520. ** code. This will cause the pager to enter the error state
  36521. ** so that no further harm will be done. Perhaps the next
  36522. ** process to come along will be able to rollback the database.
  36523. */
  36524. goto end_playback;
  36525. }
  36526. }
  36527. }
  36528. }
  36529. /*NOTREACHED*/
  36530. assert( 0 );
  36531. end_playback:
  36532. /* Following a rollback, the database file should be back in its original
  36533. ** state prior to the start of the transaction, so invoke the
  36534. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  36535. ** assertion that the transaction counter was modified.
  36536. */
  36537. assert(
  36538. pPager->fd->pMethods==0 ||
  36539. sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
  36540. );
  36541. /* If this playback is happening automatically as a result of an IO or
  36542. ** malloc error that occurred after the change-counter was updated but
  36543. ** before the transaction was committed, then the change-counter
  36544. ** modification may just have been reverted. If this happens in exclusive
  36545. ** mode, then subsequent transactions performed by the connection will not
  36546. ** update the change-counter at all. This may lead to cache inconsistency
  36547. ** problems for other processes at some point in the future. So, just
  36548. ** in case this has happened, clear the changeCountDone flag now.
  36549. */
  36550. pPager->changeCountDone = pPager->tempFile;
  36551. if( rc==SQLITE_OK ){
  36552. zMaster = pPager->pTmpSpace;
  36553. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  36554. testcase( rc!=SQLITE_OK );
  36555. }
  36556. if( rc==SQLITE_OK
  36557. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  36558. ){
  36559. rc = sqlite3PagerSync(pPager);
  36560. }
  36561. if( rc==SQLITE_OK ){
  36562. rc = pager_end_transaction(pPager, zMaster[0]!='\0');
  36563. testcase( rc!=SQLITE_OK );
  36564. }
  36565. if( rc==SQLITE_OK && zMaster[0] && res ){
  36566. /* If there was a master journal and this routine will return success,
  36567. ** see if it is possible to delete the master journal.
  36568. */
  36569. rc = pager_delmaster(pPager, zMaster);
  36570. testcase( rc!=SQLITE_OK );
  36571. }
  36572. /* The Pager.sectorSize variable may have been updated while rolling
  36573. ** back a journal created by a process with a different sector size
  36574. ** value. Reset it to the correct value for this process.
  36575. */
  36576. setSectorSize(pPager);
  36577. return rc;
  36578. }
  36579. /*
  36580. ** Read the content for page pPg out of the database file and into
  36581. ** pPg->pData. A shared lock or greater must be held on the database
  36582. ** file before this function is called.
  36583. **
  36584. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  36585. ** the value read from the database file.
  36586. **
  36587. ** If an IO error occurs, then the IO error is returned to the caller.
  36588. ** Otherwise, SQLITE_OK is returned.
  36589. */
  36590. static int readDbPage(PgHdr *pPg){
  36591. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  36592. Pgno pgno = pPg->pgno; /* Page number to read */
  36593. int rc = SQLITE_OK; /* Return code */
  36594. int isInWal = 0; /* True if page is in log file */
  36595. int pgsz = pPager->pageSize; /* Number of bytes to read */
  36596. assert( pPager->eState>=PAGER_READER && !MEMDB );
  36597. assert( isOpen(pPager->fd) );
  36598. if( NEVER(!isOpen(pPager->fd)) ){
  36599. assert( pPager->tempFile );
  36600. memset(pPg->pData, 0, pPager->pageSize);
  36601. return SQLITE_OK;
  36602. }
  36603. if( pagerUseWal(pPager) ){
  36604. /* Try to pull the page from the write-ahead log. */
  36605. rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
  36606. }
  36607. if( rc==SQLITE_OK && !isInWal ){
  36608. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  36609. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  36610. if( rc==SQLITE_IOERR_SHORT_READ ){
  36611. rc = SQLITE_OK;
  36612. }
  36613. }
  36614. if( pgno==1 ){
  36615. if( rc ){
  36616. /* If the read is unsuccessful, set the dbFileVers[] to something
  36617. ** that will never be a valid file version. dbFileVers[] is a copy
  36618. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  36619. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  36620. ** should be page numbers which are never 0xffffffff. So filling
  36621. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  36622. **
  36623. ** For an encrypted database, the situation is more complex: bytes
  36624. ** 24..39 of the database are white noise. But the probability of
  36625. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  36626. ** we should still be ok.
  36627. */
  36628. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  36629. }else{
  36630. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  36631. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  36632. }
  36633. }
  36634. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  36635. PAGER_INCR(sqlite3_pager_readdb_count);
  36636. PAGER_INCR(pPager->nRead);
  36637. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  36638. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  36639. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  36640. return rc;
  36641. }
  36642. /*
  36643. ** Update the value of the change-counter at offsets 24 and 92 in
  36644. ** the header and the sqlite version number at offset 96.
  36645. **
  36646. ** This is an unconditional update. See also the pager_incr_changecounter()
  36647. ** routine which only updates the change-counter if the update is actually
  36648. ** needed, as determined by the pPager->changeCountDone state variable.
  36649. */
  36650. static void pager_write_changecounter(PgHdr *pPg){
  36651. u32 change_counter;
  36652. /* Increment the value just read and write it back to byte 24. */
  36653. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  36654. put32bits(((char*)pPg->pData)+24, change_counter);
  36655. /* Also store the SQLite version number in bytes 96..99 and in
  36656. ** bytes 92..95 store the change counter for which the version number
  36657. ** is valid. */
  36658. put32bits(((char*)pPg->pData)+92, change_counter);
  36659. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  36660. }
  36661. #ifndef SQLITE_OMIT_WAL
  36662. /*
  36663. ** This function is invoked once for each page that has already been
  36664. ** written into the log file when a WAL transaction is rolled back.
  36665. ** Parameter iPg is the page number of said page. The pCtx argument
  36666. ** is actually a pointer to the Pager structure.
  36667. **
  36668. ** If page iPg is present in the cache, and has no outstanding references,
  36669. ** it is discarded. Otherwise, if there are one or more outstanding
  36670. ** references, the page content is reloaded from the database. If the
  36671. ** attempt to reload content from the database is required and fails,
  36672. ** return an SQLite error code. Otherwise, SQLITE_OK.
  36673. */
  36674. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  36675. int rc = SQLITE_OK;
  36676. Pager *pPager = (Pager *)pCtx;
  36677. PgHdr *pPg;
  36678. pPg = sqlite3PagerLookup(pPager, iPg);
  36679. if( pPg ){
  36680. if( sqlite3PcachePageRefcount(pPg)==1 ){
  36681. sqlite3PcacheDrop(pPg);
  36682. }else{
  36683. rc = readDbPage(pPg);
  36684. if( rc==SQLITE_OK ){
  36685. pPager->xReiniter(pPg);
  36686. }
  36687. sqlite3PagerUnref(pPg);
  36688. }
  36689. }
  36690. /* Normally, if a transaction is rolled back, any backup processes are
  36691. ** updated as data is copied out of the rollback journal and into the
  36692. ** database. This is not generally possible with a WAL database, as
  36693. ** rollback involves simply truncating the log file. Therefore, if one
  36694. ** or more frames have already been written to the log (and therefore
  36695. ** also copied into the backup databases) as part of this transaction,
  36696. ** the backups must be restarted.
  36697. */
  36698. sqlite3BackupRestart(pPager->pBackup);
  36699. return rc;
  36700. }
  36701. /*
  36702. ** This function is called to rollback a transaction on a WAL database.
  36703. */
  36704. static int pagerRollbackWal(Pager *pPager){
  36705. int rc; /* Return Code */
  36706. PgHdr *pList; /* List of dirty pages to revert */
  36707. /* For all pages in the cache that are currently dirty or have already
  36708. ** been written (but not committed) to the log file, do one of the
  36709. ** following:
  36710. **
  36711. ** + Discard the cached page (if refcount==0), or
  36712. ** + Reload page content from the database (if refcount>0).
  36713. */
  36714. pPager->dbSize = pPager->dbOrigSize;
  36715. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  36716. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  36717. while( pList && rc==SQLITE_OK ){
  36718. PgHdr *pNext = pList->pDirty;
  36719. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  36720. pList = pNext;
  36721. }
  36722. return rc;
  36723. }
  36724. /*
  36725. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  36726. ** the contents of the list of pages headed by pList (connected by pDirty),
  36727. ** this function notifies any active backup processes that the pages have
  36728. ** changed.
  36729. **
  36730. ** The list of pages passed into this routine is always sorted by page number.
  36731. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  36732. */
  36733. static int pagerWalFrames(
  36734. Pager *pPager, /* Pager object */
  36735. PgHdr *pList, /* List of frames to log */
  36736. Pgno nTruncate, /* Database size after this commit */
  36737. int isCommit, /* True if this is a commit */
  36738. int syncFlags /* Flags to pass to OsSync() (or 0) */
  36739. ){
  36740. int rc; /* Return code */
  36741. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  36742. PgHdr *p; /* For looping over pages */
  36743. #endif
  36744. assert( pPager->pWal );
  36745. #ifdef SQLITE_DEBUG
  36746. /* Verify that the page list is in accending order */
  36747. for(p=pList; p && p->pDirty; p=p->pDirty){
  36748. assert( p->pgno < p->pDirty->pgno );
  36749. }
  36750. #endif
  36751. if( isCommit ){
  36752. /* If a WAL transaction is being committed, there is no point in writing
  36753. ** any pages with page numbers greater than nTruncate into the WAL file.
  36754. ** They will never be read by any client. So remove them from the pDirty
  36755. ** list here. */
  36756. PgHdr *p;
  36757. PgHdr **ppNext = &pList;
  36758. for(p=pList; (*ppNext = p); p=p->pDirty){
  36759. if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
  36760. }
  36761. assert( pList );
  36762. }
  36763. if( pList->pgno==1 ) pager_write_changecounter(pList);
  36764. rc = sqlite3WalFrames(pPager->pWal,
  36765. pPager->pageSize, pList, nTruncate, isCommit, syncFlags
  36766. );
  36767. if( rc==SQLITE_OK && pPager->pBackup ){
  36768. PgHdr *p;
  36769. for(p=pList; p; p=p->pDirty){
  36770. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  36771. }
  36772. }
  36773. #ifdef SQLITE_CHECK_PAGES
  36774. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  36775. for(p=pList; p; p=p->pDirty){
  36776. pager_set_pagehash(p);
  36777. }
  36778. #endif
  36779. return rc;
  36780. }
  36781. /*
  36782. ** Begin a read transaction on the WAL.
  36783. **
  36784. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  36785. ** makes a snapshot of the database at the current point in time and preserves
  36786. ** that snapshot for use by the reader in spite of concurrently changes by
  36787. ** other writers or checkpointers.
  36788. */
  36789. static int pagerBeginReadTransaction(Pager *pPager){
  36790. int rc; /* Return code */
  36791. int changed = 0; /* True if cache must be reset */
  36792. assert( pagerUseWal(pPager) );
  36793. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  36794. /* sqlite3WalEndReadTransaction() was not called for the previous
  36795. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  36796. ** are in locking_mode=NORMAL and EndRead() was previously called,
  36797. ** the duplicate call is harmless.
  36798. */
  36799. sqlite3WalEndReadTransaction(pPager->pWal);
  36800. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  36801. if( rc!=SQLITE_OK || changed ){
  36802. pager_reset(pPager);
  36803. }
  36804. return rc;
  36805. }
  36806. #endif
  36807. /*
  36808. ** This function is called as part of the transition from PAGER_OPEN
  36809. ** to PAGER_READER state to determine the size of the database file
  36810. ** in pages (assuming the page size currently stored in Pager.pageSize).
  36811. **
  36812. ** If no error occurs, SQLITE_OK is returned and the size of the database
  36813. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  36814. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  36815. */
  36816. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  36817. Pgno nPage; /* Value to return via *pnPage */
  36818. /* Query the WAL sub-system for the database size. The WalDbsize()
  36819. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  36820. ** if the database size is not available. The database size is not
  36821. ** available from the WAL sub-system if the log file is empty or
  36822. ** contains no valid committed transactions.
  36823. */
  36824. assert( pPager->eState==PAGER_OPEN );
  36825. assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
  36826. nPage = sqlite3WalDbsize(pPager->pWal);
  36827. /* If the database size was not available from the WAL sub-system,
  36828. ** determine it based on the size of the database file. If the size
  36829. ** of the database file is not an integer multiple of the page-size,
  36830. ** round down to the nearest page. Except, any file larger than 0
  36831. ** bytes in size is considered to contain at least one page.
  36832. */
  36833. if( nPage==0 ){
  36834. i64 n = 0; /* Size of db file in bytes */
  36835. assert( isOpen(pPager->fd) || pPager->tempFile );
  36836. if( isOpen(pPager->fd) ){
  36837. int rc = sqlite3OsFileSize(pPager->fd, &n);
  36838. if( rc!=SQLITE_OK ){
  36839. return rc;
  36840. }
  36841. }
  36842. nPage = (Pgno)(n / pPager->pageSize);
  36843. if( nPage==0 && n>0 ){
  36844. nPage = 1;
  36845. }
  36846. }
  36847. /* If the current number of pages in the file is greater than the
  36848. ** configured maximum pager number, increase the allowed limit so
  36849. ** that the file can be read.
  36850. */
  36851. if( nPage>pPager->mxPgno ){
  36852. pPager->mxPgno = (Pgno)nPage;
  36853. }
  36854. *pnPage = nPage;
  36855. return SQLITE_OK;
  36856. }
  36857. #ifndef SQLITE_OMIT_WAL
  36858. /*
  36859. ** Check if the *-wal file that corresponds to the database opened by pPager
  36860. ** exists if the database is not empy, or verify that the *-wal file does
  36861. ** not exist (by deleting it) if the database file is empty.
  36862. **
  36863. ** If the database is not empty and the *-wal file exists, open the pager
  36864. ** in WAL mode. If the database is empty or if no *-wal file exists and
  36865. ** if no error occurs, make sure Pager.journalMode is not set to
  36866. ** PAGER_JOURNALMODE_WAL.
  36867. **
  36868. ** Return SQLITE_OK or an error code.
  36869. **
  36870. ** The caller must hold a SHARED lock on the database file to call this
  36871. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  36872. ** a WAL on a none-empty database, this ensures there is no race condition
  36873. ** between the xAccess() below and an xDelete() being executed by some
  36874. ** other connection.
  36875. */
  36876. static int pagerOpenWalIfPresent(Pager *pPager){
  36877. int rc = SQLITE_OK;
  36878. assert( pPager->eState==PAGER_OPEN );
  36879. assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
  36880. if( !pPager->tempFile ){
  36881. int isWal; /* True if WAL file exists */
  36882. Pgno nPage; /* Size of the database file */
  36883. rc = pagerPagecount(pPager, &nPage);
  36884. if( rc ) return rc;
  36885. if( nPage==0 ){
  36886. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  36887. isWal = 0;
  36888. }else{
  36889. rc = sqlite3OsAccess(
  36890. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  36891. );
  36892. }
  36893. if( rc==SQLITE_OK ){
  36894. if( isWal ){
  36895. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  36896. rc = sqlite3PagerOpenWal(pPager, 0);
  36897. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  36898. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  36899. }
  36900. }
  36901. }
  36902. return rc;
  36903. }
  36904. #endif
  36905. /*
  36906. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  36907. ** the entire master journal file. The case pSavepoint==NULL occurs when
  36908. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  36909. ** savepoint.
  36910. **
  36911. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  36912. ** being rolled back), then the rollback consists of up to three stages,
  36913. ** performed in the order specified:
  36914. **
  36915. ** * Pages are played back from the main journal starting at byte
  36916. ** offset PagerSavepoint.iOffset and continuing to
  36917. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  36918. ** file if PagerSavepoint.iHdrOffset is zero.
  36919. **
  36920. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  36921. ** back starting from the journal header immediately following
  36922. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  36923. **
  36924. ** * Pages are then played back from the sub-journal file, starting
  36925. ** with the PagerSavepoint.iSubRec and continuing to the end of
  36926. ** the journal file.
  36927. **
  36928. ** Throughout the rollback process, each time a page is rolled back, the
  36929. ** corresponding bit is set in a bitvec structure (variable pDone in the
  36930. ** implementation below). This is used to ensure that a page is only
  36931. ** rolled back the first time it is encountered in either journal.
  36932. **
  36933. ** If pSavepoint is NULL, then pages are only played back from the main
  36934. ** journal file. There is no need for a bitvec in this case.
  36935. **
  36936. ** In either case, before playback commences the Pager.dbSize variable
  36937. ** is reset to the value that it held at the start of the savepoint
  36938. ** (or transaction). No page with a page-number greater than this value
  36939. ** is played back. If one is encountered it is simply skipped.
  36940. */
  36941. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  36942. i64 szJ; /* Effective size of the main journal */
  36943. i64 iHdrOff; /* End of first segment of main-journal records */
  36944. int rc = SQLITE_OK; /* Return code */
  36945. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  36946. assert( pPager->eState!=PAGER_ERROR );
  36947. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  36948. /* Allocate a bitvec to use to store the set of pages rolled back */
  36949. if( pSavepoint ){
  36950. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  36951. if( !pDone ){
  36952. return SQLITE_NOMEM;
  36953. }
  36954. }
  36955. /* Set the database size back to the value it was before the savepoint
  36956. ** being reverted was opened.
  36957. */
  36958. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  36959. pPager->changeCountDone = pPager->tempFile;
  36960. if( !pSavepoint && pagerUseWal(pPager) ){
  36961. return pagerRollbackWal(pPager);
  36962. }
  36963. /* Use pPager->journalOff as the effective size of the main rollback
  36964. ** journal. The actual file might be larger than this in
  36965. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  36966. ** past pPager->journalOff is off-limits to us.
  36967. */
  36968. szJ = pPager->journalOff;
  36969. assert( pagerUseWal(pPager)==0 || szJ==0 );
  36970. /* Begin by rolling back records from the main journal starting at
  36971. ** PagerSavepoint.iOffset and continuing to the next journal header.
  36972. ** There might be records in the main journal that have a page number
  36973. ** greater than the current database size (pPager->dbSize) but those
  36974. ** will be skipped automatically. Pages are added to pDone as they
  36975. ** are played back.
  36976. */
  36977. if( pSavepoint && !pagerUseWal(pPager) ){
  36978. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  36979. pPager->journalOff = pSavepoint->iOffset;
  36980. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  36981. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  36982. }
  36983. assert( rc!=SQLITE_DONE );
  36984. }else{
  36985. pPager->journalOff = 0;
  36986. }
  36987. /* Continue rolling back records out of the main journal starting at
  36988. ** the first journal header seen and continuing until the effective end
  36989. ** of the main journal file. Continue to skip out-of-range pages and
  36990. ** continue adding pages rolled back to pDone.
  36991. */
  36992. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  36993. u32 ii; /* Loop counter */
  36994. u32 nJRec = 0; /* Number of Journal Records */
  36995. u32 dummy;
  36996. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  36997. assert( rc!=SQLITE_DONE );
  36998. /*
  36999. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  37000. ** test is related to ticket #2565. See the discussion in the
  37001. ** pager_playback() function for additional information.
  37002. */
  37003. if( nJRec==0
  37004. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  37005. ){
  37006. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  37007. }
  37008. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  37009. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  37010. }
  37011. assert( rc!=SQLITE_DONE );
  37012. }
  37013. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  37014. /* Finally, rollback pages from the sub-journal. Page that were
  37015. ** previously rolled back out of the main journal (and are hence in pDone)
  37016. ** will be skipped. Out-of-range pages are also skipped.
  37017. */
  37018. if( pSavepoint ){
  37019. u32 ii; /* Loop counter */
  37020. i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
  37021. if( pagerUseWal(pPager) ){
  37022. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  37023. }
  37024. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  37025. assert( offset==ii*(4+pPager->pageSize) );
  37026. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  37027. }
  37028. assert( rc!=SQLITE_DONE );
  37029. }
  37030. sqlite3BitvecDestroy(pDone);
  37031. if( rc==SQLITE_OK ){
  37032. pPager->journalOff = szJ;
  37033. }
  37034. return rc;
  37035. }
  37036. /*
  37037. ** Change the maximum number of in-memory pages that are allowed.
  37038. */
  37039. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  37040. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  37041. }
  37042. /*
  37043. ** Adjust the robustness of the database to damage due to OS crashes
  37044. ** or power failures by changing the number of syncs()s when writing
  37045. ** the rollback journal. There are three levels:
  37046. **
  37047. ** OFF sqlite3OsSync() is never called. This is the default
  37048. ** for temporary and transient files.
  37049. **
  37050. ** NORMAL The journal is synced once before writes begin on the
  37051. ** database. This is normally adequate protection, but
  37052. ** it is theoretically possible, though very unlikely,
  37053. ** that an inopertune power failure could leave the journal
  37054. ** in a state which would cause damage to the database
  37055. ** when it is rolled back.
  37056. **
  37057. ** FULL The journal is synced twice before writes begin on the
  37058. ** database (with some additional information - the nRec field
  37059. ** of the journal header - being written in between the two
  37060. ** syncs). If we assume that writing a
  37061. ** single disk sector is atomic, then this mode provides
  37062. ** assurance that the journal will not be corrupted to the
  37063. ** point of causing damage to the database during rollback.
  37064. **
  37065. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  37066. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  37067. ** prior to the start of checkpoint and that the database file is synced
  37068. ** at the conclusion of the checkpoint if the entire content of the WAL
  37069. ** was written back into the database. But no sync operations occur for
  37070. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  37071. ** file is synced following each commit operation, in addition to the
  37072. ** syncs associated with NORMAL.
  37073. **
  37074. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  37075. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  37076. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  37077. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  37078. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  37079. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  37080. ** the xSync primitive is called and is relevant to all platforms.
  37081. **
  37082. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  37083. ** and FULL=3.
  37084. */
  37085. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  37086. SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
  37087. Pager *pPager, /* The pager to set safety level for */
  37088. int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
  37089. int bFullFsync, /* PRAGMA fullfsync */
  37090. int bCkptFullFsync /* PRAGMA checkpoint_fullfsync */
  37091. ){
  37092. assert( level>=1 && level<=3 );
  37093. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  37094. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  37095. if( pPager->noSync ){
  37096. pPager->syncFlags = 0;
  37097. pPager->ckptSyncFlags = 0;
  37098. }else if( bFullFsync ){
  37099. pPager->syncFlags = SQLITE_SYNC_FULL;
  37100. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  37101. }else if( bCkptFullFsync ){
  37102. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  37103. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  37104. }else{
  37105. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  37106. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  37107. }
  37108. }
  37109. #endif
  37110. /*
  37111. ** The following global variable is incremented whenever the library
  37112. ** attempts to open a temporary file. This information is used for
  37113. ** testing and analysis only.
  37114. */
  37115. #ifdef SQLITE_TEST
  37116. SQLITE_API int sqlite3_opentemp_count = 0;
  37117. #endif
  37118. /*
  37119. ** Open a temporary file.
  37120. **
  37121. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  37122. ** or some other error code if we fail. The OS will automatically
  37123. ** delete the temporary file when it is closed.
  37124. **
  37125. ** The flags passed to the VFS layer xOpen() call are those specified
  37126. ** by parameter vfsFlags ORed with the following:
  37127. **
  37128. ** SQLITE_OPEN_READWRITE
  37129. ** SQLITE_OPEN_CREATE
  37130. ** SQLITE_OPEN_EXCLUSIVE
  37131. ** SQLITE_OPEN_DELETEONCLOSE
  37132. */
  37133. static int pagerOpentemp(
  37134. Pager *pPager, /* The pager object */
  37135. sqlite3_file *pFile, /* Write the file descriptor here */
  37136. int vfsFlags /* Flags passed through to the VFS */
  37137. ){
  37138. int rc; /* Return code */
  37139. #ifdef SQLITE_TEST
  37140. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  37141. #endif
  37142. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  37143. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  37144. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  37145. assert( rc!=SQLITE_OK || isOpen(pFile) );
  37146. return rc;
  37147. }
  37148. /*
  37149. ** Set the busy handler function.
  37150. **
  37151. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  37152. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  37153. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  37154. ** lock. It does *not* invoke the busy handler when upgrading from
  37155. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  37156. ** (which occurs during hot-journal rollback). Summary:
  37157. **
  37158. ** Transition | Invokes xBusyHandler
  37159. ** --------------------------------------------------------
  37160. ** NO_LOCK -> SHARED_LOCK | Yes
  37161. ** SHARED_LOCK -> RESERVED_LOCK | No
  37162. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  37163. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  37164. **
  37165. ** If the busy-handler callback returns non-zero, the lock is
  37166. ** retried. If it returns zero, then the SQLITE_BUSY error is
  37167. ** returned to the caller of the pager API function.
  37168. */
  37169. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  37170. Pager *pPager, /* Pager object */
  37171. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  37172. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  37173. ){
  37174. pPager->xBusyHandler = xBusyHandler;
  37175. pPager->pBusyHandlerArg = pBusyHandlerArg;
  37176. }
  37177. /*
  37178. ** Change the page size used by the Pager object. The new page size
  37179. ** is passed in *pPageSize.
  37180. **
  37181. ** If the pager is in the error state when this function is called, it
  37182. ** is a no-op. The value returned is the error state error code (i.e.
  37183. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  37184. **
  37185. ** Otherwise, if all of the following are true:
  37186. **
  37187. ** * the new page size (value of *pPageSize) is valid (a power
  37188. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  37189. **
  37190. ** * there are no outstanding page references, and
  37191. **
  37192. ** * the database is either not an in-memory database or it is
  37193. ** an in-memory database that currently consists of zero pages.
  37194. **
  37195. ** then the pager object page size is set to *pPageSize.
  37196. **
  37197. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  37198. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  37199. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  37200. ** In all other cases, SQLITE_OK is returned.
  37201. **
  37202. ** If the page size is not changed, either because one of the enumerated
  37203. ** conditions above is not true, the pager was in error state when this
  37204. ** function was called, or because the memory allocation attempt failed,
  37205. ** then *pPageSize is set to the old, retained page size before returning.
  37206. */
  37207. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  37208. int rc = SQLITE_OK;
  37209. /* It is not possible to do a full assert_pager_state() here, as this
  37210. ** function may be called from within PagerOpen(), before the state
  37211. ** of the Pager object is internally consistent.
  37212. **
  37213. ** At one point this function returned an error if the pager was in
  37214. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  37215. ** there is at least one outstanding page reference, this function
  37216. ** is a no-op for that case anyhow.
  37217. */
  37218. u32 pageSize = *pPageSize;
  37219. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  37220. if( (pPager->memDb==0 || pPager->dbSize==0)
  37221. && sqlite3PcacheRefCount(pPager->pPCache)==0
  37222. && pageSize && pageSize!=(u32)pPager->pageSize
  37223. ){
  37224. char *pNew = NULL; /* New temp space */
  37225. i64 nByte = 0;
  37226. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  37227. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  37228. }
  37229. if( rc==SQLITE_OK ){
  37230. pNew = (char *)sqlite3PageMalloc(pageSize);
  37231. if( !pNew ) rc = SQLITE_NOMEM;
  37232. }
  37233. if( rc==SQLITE_OK ){
  37234. pager_reset(pPager);
  37235. pPager->dbSize = (Pgno)(nByte/pageSize);
  37236. pPager->pageSize = pageSize;
  37237. sqlite3PageFree(pPager->pTmpSpace);
  37238. pPager->pTmpSpace = pNew;
  37239. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  37240. }
  37241. }
  37242. *pPageSize = pPager->pageSize;
  37243. if( rc==SQLITE_OK ){
  37244. if( nReserve<0 ) nReserve = pPager->nReserve;
  37245. assert( nReserve>=0 && nReserve<1000 );
  37246. pPager->nReserve = (i16)nReserve;
  37247. pagerReportSize(pPager);
  37248. }
  37249. return rc;
  37250. }
  37251. /*
  37252. ** Return a pointer to the "temporary page" buffer held internally
  37253. ** by the pager. This is a buffer that is big enough to hold the
  37254. ** entire content of a database page. This buffer is used internally
  37255. ** during rollback and will be overwritten whenever a rollback
  37256. ** occurs. But other modules are free to use it too, as long as
  37257. ** no rollbacks are happening.
  37258. */
  37259. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  37260. return pPager->pTmpSpace;
  37261. }
  37262. /*
  37263. ** Attempt to set the maximum database page count if mxPage is positive.
  37264. ** Make no changes if mxPage is zero or negative. And never reduce the
  37265. ** maximum page count below the current size of the database.
  37266. **
  37267. ** Regardless of mxPage, return the current maximum page count.
  37268. */
  37269. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  37270. if( mxPage>0 ){
  37271. pPager->mxPgno = mxPage;
  37272. }
  37273. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  37274. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  37275. return pPager->mxPgno;
  37276. }
  37277. /*
  37278. ** The following set of routines are used to disable the simulated
  37279. ** I/O error mechanism. These routines are used to avoid simulated
  37280. ** errors in places where we do not care about errors.
  37281. **
  37282. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  37283. ** and generate no code.
  37284. */
  37285. #ifdef SQLITE_TEST
  37286. SQLITE_API extern int sqlite3_io_error_pending;
  37287. SQLITE_API extern int sqlite3_io_error_hit;
  37288. static int saved_cnt;
  37289. void disable_simulated_io_errors(void){
  37290. saved_cnt = sqlite3_io_error_pending;
  37291. sqlite3_io_error_pending = -1;
  37292. }
  37293. void enable_simulated_io_errors(void){
  37294. sqlite3_io_error_pending = saved_cnt;
  37295. }
  37296. #else
  37297. # define disable_simulated_io_errors()
  37298. # define enable_simulated_io_errors()
  37299. #endif
  37300. /*
  37301. ** Read the first N bytes from the beginning of the file into memory
  37302. ** that pDest points to.
  37303. **
  37304. ** If the pager was opened on a transient file (zFilename==""), or
  37305. ** opened on a file less than N bytes in size, the output buffer is
  37306. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  37307. ** function is used to read database headers, and a new transient or
  37308. ** zero sized database has a header than consists entirely of zeroes.
  37309. **
  37310. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  37311. ** the error code is returned to the caller and the contents of the
  37312. ** output buffer undefined.
  37313. */
  37314. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  37315. int rc = SQLITE_OK;
  37316. memset(pDest, 0, N);
  37317. assert( isOpen(pPager->fd) || pPager->tempFile );
  37318. /* This routine is only called by btree immediately after creating
  37319. ** the Pager object. There has not been an opportunity to transition
  37320. ** to WAL mode yet.
  37321. */
  37322. assert( !pagerUseWal(pPager) );
  37323. if( isOpen(pPager->fd) ){
  37324. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  37325. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  37326. if( rc==SQLITE_IOERR_SHORT_READ ){
  37327. rc = SQLITE_OK;
  37328. }
  37329. }
  37330. return rc;
  37331. }
  37332. /*
  37333. ** This function may only be called when a read-transaction is open on
  37334. ** the pager. It returns the total number of pages in the database.
  37335. **
  37336. ** However, if the file is between 1 and <page-size> bytes in size, then
  37337. ** this is considered a 1 page file.
  37338. */
  37339. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  37340. assert( pPager->eState>=PAGER_READER );
  37341. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  37342. *pnPage = (int)pPager->dbSize;
  37343. }
  37344. /*
  37345. ** Try to obtain a lock of type locktype on the database file. If
  37346. ** a similar or greater lock is already held, this function is a no-op
  37347. ** (returning SQLITE_OK immediately).
  37348. **
  37349. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  37350. ** the busy callback if the lock is currently not available. Repeat
  37351. ** until the busy callback returns false or until the attempt to
  37352. ** obtain the lock succeeds.
  37353. **
  37354. ** Return SQLITE_OK on success and an error code if we cannot obtain
  37355. ** the lock. If the lock is obtained successfully, set the Pager.state
  37356. ** variable to locktype before returning.
  37357. */
  37358. static int pager_wait_on_lock(Pager *pPager, int locktype){
  37359. int rc; /* Return code */
  37360. /* Check that this is either a no-op (because the requested lock is
  37361. ** already held, or one of the transistions that the busy-handler
  37362. ** may be invoked during, according to the comment above
  37363. ** sqlite3PagerSetBusyhandler().
  37364. */
  37365. assert( (pPager->eLock>=locktype)
  37366. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  37367. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  37368. );
  37369. do {
  37370. rc = pagerLockDb(pPager, locktype);
  37371. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  37372. return rc;
  37373. }
  37374. /*
  37375. ** Function assertTruncateConstraint(pPager) checks that one of the
  37376. ** following is true for all dirty pages currently in the page-cache:
  37377. **
  37378. ** a) The page number is less than or equal to the size of the
  37379. ** current database image, in pages, OR
  37380. **
  37381. ** b) if the page content were written at this time, it would not
  37382. ** be necessary to write the current content out to the sub-journal
  37383. ** (as determined by function subjRequiresPage()).
  37384. **
  37385. ** If the condition asserted by this function were not true, and the
  37386. ** dirty page were to be discarded from the cache via the pagerStress()
  37387. ** routine, pagerStress() would not write the current page content to
  37388. ** the database file. If a savepoint transaction were rolled back after
  37389. ** this happened, the correct behaviour would be to restore the current
  37390. ** content of the page. However, since this content is not present in either
  37391. ** the database file or the portion of the rollback journal and
  37392. ** sub-journal rolled back the content could not be restored and the
  37393. ** database image would become corrupt. It is therefore fortunate that
  37394. ** this circumstance cannot arise.
  37395. */
  37396. #if defined(SQLITE_DEBUG)
  37397. static void assertTruncateConstraintCb(PgHdr *pPg){
  37398. assert( pPg->flags&PGHDR_DIRTY );
  37399. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  37400. }
  37401. static void assertTruncateConstraint(Pager *pPager){
  37402. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  37403. }
  37404. #else
  37405. # define assertTruncateConstraint(pPager)
  37406. #endif
  37407. /*
  37408. ** Truncate the in-memory database file image to nPage pages. This
  37409. ** function does not actually modify the database file on disk. It
  37410. ** just sets the internal state of the pager object so that the
  37411. ** truncation will be done when the current transaction is committed.
  37412. */
  37413. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  37414. assert( pPager->dbSize>=nPage );
  37415. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  37416. pPager->dbSize = nPage;
  37417. assertTruncateConstraint(pPager);
  37418. }
  37419. /*
  37420. ** This function is called before attempting a hot-journal rollback. It
  37421. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  37422. ** size of the journal file so that the pager_playback() routine knows
  37423. ** that the entire journal file has been synced.
  37424. **
  37425. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  37426. ** that if a power-failure occurs during the rollback, the process that
  37427. ** attempts rollback following system recovery sees the same journal
  37428. ** content as this process.
  37429. **
  37430. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  37431. ** an SQLite error code.
  37432. */
  37433. static int pagerSyncHotJournal(Pager *pPager){
  37434. int rc = SQLITE_OK;
  37435. if( !pPager->noSync ){
  37436. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  37437. }
  37438. if( rc==SQLITE_OK ){
  37439. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  37440. }
  37441. return rc;
  37442. }
  37443. /*
  37444. ** Shutdown the page cache. Free all memory and close all files.
  37445. **
  37446. ** If a transaction was in progress when this routine is called, that
  37447. ** transaction is rolled back. All outstanding pages are invalidated
  37448. ** and their memory is freed. Any attempt to use a page associated
  37449. ** with this page cache after this function returns will likely
  37450. ** result in a coredump.
  37451. **
  37452. ** This function always succeeds. If a transaction is active an attempt
  37453. ** is made to roll it back. If an error occurs during the rollback
  37454. ** a hot journal may be left in the filesystem but no error is returned
  37455. ** to the caller.
  37456. */
  37457. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  37458. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  37459. disable_simulated_io_errors();
  37460. sqlite3BeginBenignMalloc();
  37461. /* pPager->errCode = 0; */
  37462. pPager->exclusiveMode = 0;
  37463. #ifndef SQLITE_OMIT_WAL
  37464. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  37465. pPager->pWal = 0;
  37466. #endif
  37467. pager_reset(pPager);
  37468. if( MEMDB ){
  37469. pager_unlock(pPager);
  37470. }else{
  37471. /* If it is open, sync the journal file before calling UnlockAndRollback.
  37472. ** If this is not done, then an unsynced portion of the open journal
  37473. ** file may be played back into the database. If a power failure occurs
  37474. ** while this is happening, the database could become corrupt.
  37475. **
  37476. ** If an error occurs while trying to sync the journal, shift the pager
  37477. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  37478. ** database and close the journal file without attempting to roll it
  37479. ** back or finalize it. The next database user will have to do hot-journal
  37480. ** rollback before accessing the database file.
  37481. */
  37482. if( isOpen(pPager->jfd) ){
  37483. pager_error(pPager, pagerSyncHotJournal(pPager));
  37484. }
  37485. pagerUnlockAndRollback(pPager);
  37486. }
  37487. sqlite3EndBenignMalloc();
  37488. enable_simulated_io_errors();
  37489. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  37490. IOTRACE(("CLOSE %p\n", pPager))
  37491. sqlite3OsClose(pPager->jfd);
  37492. sqlite3OsClose(pPager->fd);
  37493. sqlite3PageFree(pTmp);
  37494. sqlite3PcacheClose(pPager->pPCache);
  37495. #ifdef SQLITE_HAS_CODEC
  37496. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  37497. #endif
  37498. assert( !pPager->aSavepoint && !pPager->pInJournal );
  37499. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  37500. sqlite3_free(pPager);
  37501. return SQLITE_OK;
  37502. }
  37503. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  37504. /*
  37505. ** Return the page number for page pPg.
  37506. */
  37507. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  37508. return pPg->pgno;
  37509. }
  37510. #endif
  37511. /*
  37512. ** Increment the reference count for page pPg.
  37513. */
  37514. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  37515. sqlite3PcacheRef(pPg);
  37516. }
  37517. /*
  37518. ** Sync the journal. In other words, make sure all the pages that have
  37519. ** been written to the journal have actually reached the surface of the
  37520. ** disk and can be restored in the event of a hot-journal rollback.
  37521. **
  37522. ** If the Pager.noSync flag is set, then this function is a no-op.
  37523. ** Otherwise, the actions required depend on the journal-mode and the
  37524. ** device characteristics of the the file-system, as follows:
  37525. **
  37526. ** * If the journal file is an in-memory journal file, no action need
  37527. ** be taken.
  37528. **
  37529. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  37530. ** then the nRec field of the most recently written journal header
  37531. ** is updated to contain the number of journal records that have
  37532. ** been written following it. If the pager is operating in full-sync
  37533. ** mode, then the journal file is synced before this field is updated.
  37534. **
  37535. ** * If the device does not support the SEQUENTIAL property, then
  37536. ** journal file is synced.
  37537. **
  37538. ** Or, in pseudo-code:
  37539. **
  37540. ** if( NOT <in-memory journal> ){
  37541. ** if( NOT SAFE_APPEND ){
  37542. ** if( <full-sync mode> ) xSync(<journal file>);
  37543. ** <update nRec field>
  37544. ** }
  37545. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  37546. ** }
  37547. **
  37548. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  37549. ** page currently held in memory before returning SQLITE_OK. If an IO
  37550. ** error is encountered, then the IO error code is returned to the caller.
  37551. */
  37552. static int syncJournal(Pager *pPager, int newHdr){
  37553. int rc; /* Return code */
  37554. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  37555. || pPager->eState==PAGER_WRITER_DBMOD
  37556. );
  37557. assert( assert_pager_state(pPager) );
  37558. assert( !pagerUseWal(pPager) );
  37559. rc = sqlite3PagerExclusiveLock(pPager);
  37560. if( rc!=SQLITE_OK ) return rc;
  37561. if( !pPager->noSync ){
  37562. assert( !pPager->tempFile );
  37563. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  37564. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  37565. assert( isOpen(pPager->jfd) );
  37566. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  37567. /* This block deals with an obscure problem. If the last connection
  37568. ** that wrote to this database was operating in persistent-journal
  37569. ** mode, then the journal file may at this point actually be larger
  37570. ** than Pager.journalOff bytes. If the next thing in the journal
  37571. ** file happens to be a journal-header (written as part of the
  37572. ** previous connection's transaction), and a crash or power-failure
  37573. ** occurs after nRec is updated but before this connection writes
  37574. ** anything else to the journal file (or commits/rolls back its
  37575. ** transaction), then SQLite may become confused when doing the
  37576. ** hot-journal rollback following recovery. It may roll back all
  37577. ** of this connections data, then proceed to rolling back the old,
  37578. ** out-of-date data that follows it. Database corruption.
  37579. **
  37580. ** To work around this, if the journal file does appear to contain
  37581. ** a valid header following Pager.journalOff, then write a 0x00
  37582. ** byte to the start of it to prevent it from being recognized.
  37583. **
  37584. ** Variable iNextHdrOffset is set to the offset at which this
  37585. ** problematic header will occur, if it exists. aMagic is used
  37586. ** as a temporary buffer to inspect the first couple of bytes of
  37587. ** the potential journal header.
  37588. */
  37589. i64 iNextHdrOffset;
  37590. u8 aMagic[8];
  37591. u8 zHeader[sizeof(aJournalMagic)+4];
  37592. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  37593. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  37594. iNextHdrOffset = journalHdrOffset(pPager);
  37595. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  37596. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  37597. static const u8 zerobyte = 0;
  37598. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  37599. }
  37600. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  37601. return rc;
  37602. }
  37603. /* Write the nRec value into the journal file header. If in
  37604. ** full-synchronous mode, sync the journal first. This ensures that
  37605. ** all data has really hit the disk before nRec is updated to mark
  37606. ** it as a candidate for rollback.
  37607. **
  37608. ** This is not required if the persistent media supports the
  37609. ** SAFE_APPEND property. Because in this case it is not possible
  37610. ** for garbage data to be appended to the file, the nRec field
  37611. ** is populated with 0xFFFFFFFF when the journal header is written
  37612. ** and never needs to be updated.
  37613. */
  37614. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  37615. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  37616. IOTRACE(("JSYNC %p\n", pPager))
  37617. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  37618. if( rc!=SQLITE_OK ) return rc;
  37619. }
  37620. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  37621. rc = sqlite3OsWrite(
  37622. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  37623. );
  37624. if( rc!=SQLITE_OK ) return rc;
  37625. }
  37626. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  37627. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  37628. IOTRACE(("JSYNC %p\n", pPager))
  37629. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  37630. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  37631. );
  37632. if( rc!=SQLITE_OK ) return rc;
  37633. }
  37634. pPager->journalHdr = pPager->journalOff;
  37635. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  37636. pPager->nRec = 0;
  37637. rc = writeJournalHdr(pPager);
  37638. if( rc!=SQLITE_OK ) return rc;
  37639. }
  37640. }else{
  37641. pPager->journalHdr = pPager->journalOff;
  37642. }
  37643. }
  37644. /* Unless the pager is in noSync mode, the journal file was just
  37645. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  37646. ** all pages.
  37647. */
  37648. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  37649. pPager->eState = PAGER_WRITER_DBMOD;
  37650. assert( assert_pager_state(pPager) );
  37651. return SQLITE_OK;
  37652. }
  37653. /*
  37654. ** The argument is the first in a linked list of dirty pages connected
  37655. ** by the PgHdr.pDirty pointer. This function writes each one of the
  37656. ** in-memory pages in the list to the database file. The argument may
  37657. ** be NULL, representing an empty list. In this case this function is
  37658. ** a no-op.
  37659. **
  37660. ** The pager must hold at least a RESERVED lock when this function
  37661. ** is called. Before writing anything to the database file, this lock
  37662. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  37663. ** SQLITE_BUSY is returned and no data is written to the database file.
  37664. **
  37665. ** If the pager is a temp-file pager and the actual file-system file
  37666. ** is not yet open, it is created and opened before any data is
  37667. ** written out.
  37668. **
  37669. ** Once the lock has been upgraded and, if necessary, the file opened,
  37670. ** the pages are written out to the database file in list order. Writing
  37671. ** a page is skipped if it meets either of the following criteria:
  37672. **
  37673. ** * The page number is greater than Pager.dbSize, or
  37674. ** * The PGHDR_DONT_WRITE flag is set on the page.
  37675. **
  37676. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  37677. ** is updated accordingly. If page 1 is written out, then the value cached
  37678. ** in Pager.dbFileVers[] is updated to match the new value stored in
  37679. ** the database file.
  37680. **
  37681. ** If everything is successful, SQLITE_OK is returned. If an IO error
  37682. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  37683. ** be obtained, SQLITE_BUSY is returned.
  37684. */
  37685. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  37686. int rc = SQLITE_OK; /* Return code */
  37687. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  37688. assert( !pagerUseWal(pPager) );
  37689. assert( pPager->eState==PAGER_WRITER_DBMOD );
  37690. assert( pPager->eLock==EXCLUSIVE_LOCK );
  37691. /* If the file is a temp-file has not yet been opened, open it now. It
  37692. ** is not possible for rc to be other than SQLITE_OK if this branch
  37693. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  37694. */
  37695. if( !isOpen(pPager->fd) ){
  37696. assert( pPager->tempFile && rc==SQLITE_OK );
  37697. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  37698. }
  37699. /* Before the first write, give the VFS a hint of what the final
  37700. ** file size will be.
  37701. */
  37702. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  37703. if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
  37704. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  37705. sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  37706. pPager->dbHintSize = pPager->dbSize;
  37707. }
  37708. while( rc==SQLITE_OK && pList ){
  37709. Pgno pgno = pList->pgno;
  37710. /* If there are dirty pages in the page cache with page numbers greater
  37711. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  37712. ** make the file smaller (presumably by auto-vacuum code). Do not write
  37713. ** any such pages to the file.
  37714. **
  37715. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  37716. ** set (set by sqlite3PagerDontWrite()).
  37717. */
  37718. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  37719. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  37720. char *pData; /* Data to write */
  37721. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  37722. if( pList->pgno==1 ) pager_write_changecounter(pList);
  37723. /* Encode the database */
  37724. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  37725. /* Write out the page data. */
  37726. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  37727. /* If page 1 was just written, update Pager.dbFileVers to match
  37728. ** the value now stored in the database file. If writing this
  37729. ** page caused the database file to grow, update dbFileSize.
  37730. */
  37731. if( pgno==1 ){
  37732. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  37733. }
  37734. if( pgno>pPager->dbFileSize ){
  37735. pPager->dbFileSize = pgno;
  37736. }
  37737. /* Update any backup objects copying the contents of this pager. */
  37738. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  37739. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  37740. PAGERID(pPager), pgno, pager_pagehash(pList)));
  37741. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  37742. PAGER_INCR(sqlite3_pager_writedb_count);
  37743. PAGER_INCR(pPager->nWrite);
  37744. }else{
  37745. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  37746. }
  37747. pager_set_pagehash(pList);
  37748. pList = pList->pDirty;
  37749. }
  37750. return rc;
  37751. }
  37752. /*
  37753. ** Ensure that the sub-journal file is open. If it is already open, this
  37754. ** function is a no-op.
  37755. **
  37756. ** SQLITE_OK is returned if everything goes according to plan. An
  37757. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  37758. ** fails.
  37759. */
  37760. static int openSubJournal(Pager *pPager){
  37761. int rc = SQLITE_OK;
  37762. if( !isOpen(pPager->sjfd) ){
  37763. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  37764. sqlite3MemJournalOpen(pPager->sjfd);
  37765. }else{
  37766. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  37767. }
  37768. }
  37769. return rc;
  37770. }
  37771. /*
  37772. ** Append a record of the current state of page pPg to the sub-journal.
  37773. ** It is the callers responsibility to use subjRequiresPage() to check
  37774. ** that it is really required before calling this function.
  37775. **
  37776. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  37777. ** for all open savepoints before returning.
  37778. **
  37779. ** This function returns SQLITE_OK if everything is successful, an IO
  37780. ** error code if the attempt to write to the sub-journal fails, or
  37781. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  37782. ** bitvec.
  37783. */
  37784. static int subjournalPage(PgHdr *pPg){
  37785. int rc = SQLITE_OK;
  37786. Pager *pPager = pPg->pPager;
  37787. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  37788. /* Open the sub-journal, if it has not already been opened */
  37789. assert( pPager->useJournal );
  37790. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  37791. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  37792. assert( pagerUseWal(pPager)
  37793. || pageInJournal(pPg)
  37794. || pPg->pgno>pPager->dbOrigSize
  37795. );
  37796. rc = openSubJournal(pPager);
  37797. /* If the sub-journal was opened successfully (or was already open),
  37798. ** write the journal record into the file. */
  37799. if( rc==SQLITE_OK ){
  37800. void *pData = pPg->pData;
  37801. i64 offset = pPager->nSubRec*(4+pPager->pageSize);
  37802. char *pData2;
  37803. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  37804. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  37805. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  37806. if( rc==SQLITE_OK ){
  37807. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  37808. }
  37809. }
  37810. }
  37811. if( rc==SQLITE_OK ){
  37812. pPager->nSubRec++;
  37813. assert( pPager->nSavepoint>0 );
  37814. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  37815. }
  37816. return rc;
  37817. }
  37818. /*
  37819. ** This function is called by the pcache layer when it has reached some
  37820. ** soft memory limit. The first argument is a pointer to a Pager object
  37821. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  37822. ** database). The second argument is a reference to a page that is
  37823. ** currently dirty but has no outstanding references. The page
  37824. ** is always associated with the Pager object passed as the first
  37825. ** argument.
  37826. **
  37827. ** The job of this function is to make pPg clean by writing its contents
  37828. ** out to the database file, if possible. This may involve syncing the
  37829. ** journal file.
  37830. **
  37831. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  37832. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  37833. ** page clean, the IO error code is returned. If the page cannot be
  37834. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  37835. ** is returned by sqlite3PcacheMakeClean() is not called.
  37836. */
  37837. static int pagerStress(void *p, PgHdr *pPg){
  37838. Pager *pPager = (Pager *)p;
  37839. int rc = SQLITE_OK;
  37840. assert( pPg->pPager==pPager );
  37841. assert( pPg->flags&PGHDR_DIRTY );
  37842. /* The doNotSyncSpill flag is set during times when doing a sync of
  37843. ** journal (and adding a new header) is not allowed. This occurs
  37844. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  37845. ** pages belonging to the same sector.
  37846. **
  37847. ** The doNotSpill flag inhibits all cache spilling regardless of whether
  37848. ** or not a sync is required. This is set during a rollback.
  37849. **
  37850. ** Spilling is also prohibited when in an error state since that could
  37851. ** lead to database corruption. In the current implementaton it
  37852. ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
  37853. ** while in the error state, hence it is impossible for this routine to
  37854. ** be called in the error state. Nevertheless, we include a NEVER()
  37855. ** test for the error state as a safeguard against future changes.
  37856. */
  37857. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  37858. if( pPager->doNotSpill ) return SQLITE_OK;
  37859. if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
  37860. return SQLITE_OK;
  37861. }
  37862. pPg->pDirty = 0;
  37863. if( pagerUseWal(pPager) ){
  37864. /* Write a single frame for this page to the log. */
  37865. if( subjRequiresPage(pPg) ){
  37866. rc = subjournalPage(pPg);
  37867. }
  37868. if( rc==SQLITE_OK ){
  37869. rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
  37870. }
  37871. }else{
  37872. /* Sync the journal file if required. */
  37873. if( pPg->flags&PGHDR_NEED_SYNC
  37874. || pPager->eState==PAGER_WRITER_CACHEMOD
  37875. ){
  37876. rc = syncJournal(pPager, 1);
  37877. }
  37878. /* If the page number of this page is larger than the current size of
  37879. ** the database image, it may need to be written to the sub-journal.
  37880. ** This is because the call to pager_write_pagelist() below will not
  37881. ** actually write data to the file in this case.
  37882. **
  37883. ** Consider the following sequence of events:
  37884. **
  37885. ** BEGIN;
  37886. ** <journal page X>
  37887. ** <modify page X>
  37888. ** SAVEPOINT sp;
  37889. ** <shrink database file to Y pages>
  37890. ** pagerStress(page X)
  37891. ** ROLLBACK TO sp;
  37892. **
  37893. ** If (X>Y), then when pagerStress is called page X will not be written
  37894. ** out to the database file, but will be dropped from the cache. Then,
  37895. ** following the "ROLLBACK TO sp" statement, reading page X will read
  37896. ** data from the database file. This will be the copy of page X as it
  37897. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  37898. ** was executed.
  37899. **
  37900. ** The solution is to write the current data for page X into the
  37901. ** sub-journal file now (if it is not already there), so that it will
  37902. ** be restored to its current value when the "ROLLBACK TO sp" is
  37903. ** executed.
  37904. */
  37905. if( NEVER(
  37906. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  37907. ) ){
  37908. rc = subjournalPage(pPg);
  37909. }
  37910. /* Write the contents of the page out to the database file. */
  37911. if( rc==SQLITE_OK ){
  37912. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  37913. rc = pager_write_pagelist(pPager, pPg);
  37914. }
  37915. }
  37916. /* Mark the page as clean. */
  37917. if( rc==SQLITE_OK ){
  37918. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  37919. sqlite3PcacheMakeClean(pPg);
  37920. }
  37921. return pager_error(pPager, rc);
  37922. }
  37923. /*
  37924. ** Allocate and initialize a new Pager object and put a pointer to it
  37925. ** in *ppPager. The pager should eventually be freed by passing it
  37926. ** to sqlite3PagerClose().
  37927. **
  37928. ** The zFilename argument is the path to the database file to open.
  37929. ** If zFilename is NULL then a randomly-named temporary file is created
  37930. ** and used as the file to be cached. Temporary files are be deleted
  37931. ** automatically when they are closed. If zFilename is ":memory:" then
  37932. ** all information is held in cache. It is never written to disk.
  37933. ** This can be used to implement an in-memory database.
  37934. **
  37935. ** The nExtra parameter specifies the number of bytes of space allocated
  37936. ** along with each page reference. This space is available to the user
  37937. ** via the sqlite3PagerGetExtra() API.
  37938. **
  37939. ** The flags argument is used to specify properties that affect the
  37940. ** operation of the pager. It should be passed some bitwise combination
  37941. ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
  37942. **
  37943. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  37944. ** of the xOpen() method of the supplied VFS when opening files.
  37945. **
  37946. ** If the pager object is allocated and the specified file opened
  37947. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  37948. ** the new pager object. If an error occurs, *ppPager is set to NULL
  37949. ** and error code returned. This function may return SQLITE_NOMEM
  37950. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  37951. ** various SQLITE_IO_XXX errors.
  37952. */
  37953. SQLITE_PRIVATE int sqlite3PagerOpen(
  37954. sqlite3_vfs *pVfs, /* The virtual file system to use */
  37955. Pager **ppPager, /* OUT: Return the Pager structure here */
  37956. const char *zFilename, /* Name of the database file to open */
  37957. int nExtra, /* Extra bytes append to each in-memory page */
  37958. int flags, /* flags controlling this file */
  37959. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  37960. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  37961. ){
  37962. u8 *pPtr;
  37963. Pager *pPager = 0; /* Pager object to allocate and return */
  37964. int rc = SQLITE_OK; /* Return code */
  37965. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  37966. int memDb = 0; /* True if this is an in-memory file */
  37967. int readOnly = 0; /* True if this is a read-only file */
  37968. int journalFileSize; /* Bytes to allocate for each journal fd */
  37969. char *zPathname = 0; /* Full path to database file */
  37970. int nPathname = 0; /* Number of bytes in zPathname */
  37971. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  37972. int noReadlock = (flags & PAGER_NO_READLOCK)!=0; /* True to omit read-lock */
  37973. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  37974. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  37975. /* Figure out how much space is required for each journal file-handle
  37976. ** (there are two of them, the main journal and the sub-journal). This
  37977. ** is the maximum space required for an in-memory journal file handle
  37978. ** and a regular journal file-handle. Note that a "regular journal-handle"
  37979. ** may be a wrapper capable of caching the first portion of the journal
  37980. ** file in memory to implement the atomic-write optimization (see
  37981. ** source file journal.c).
  37982. */
  37983. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  37984. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  37985. }else{
  37986. journalFileSize = ROUND8(sqlite3MemJournalSize());
  37987. }
  37988. /* Set the output variable to NULL in case an error occurs. */
  37989. *ppPager = 0;
  37990. #ifndef SQLITE_OMIT_MEMORYDB
  37991. if( flags & PAGER_MEMORY ){
  37992. memDb = 1;
  37993. zFilename = 0;
  37994. }
  37995. #endif
  37996. /* Compute and store the full pathname in an allocated buffer pointed
  37997. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  37998. ** leave both nPathname and zPathname set to 0.
  37999. */
  38000. if( zFilename && zFilename[0] ){
  38001. nPathname = pVfs->mxPathname+1;
  38002. zPathname = sqlite3Malloc(nPathname*2);
  38003. if( zPathname==0 ){
  38004. return SQLITE_NOMEM;
  38005. }
  38006. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  38007. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  38008. nPathname = sqlite3Strlen30(zPathname);
  38009. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  38010. /* This branch is taken when the journal path required by
  38011. ** the database being opened will be more than pVfs->mxPathname
  38012. ** bytes in length. This means the database cannot be opened,
  38013. ** as it will not be possible to open the journal file or even
  38014. ** check for a hot-journal before reading.
  38015. */
  38016. rc = SQLITE_CANTOPEN_BKPT;
  38017. }
  38018. if( rc!=SQLITE_OK ){
  38019. sqlite3_free(zPathname);
  38020. return rc;
  38021. }
  38022. }
  38023. /* Allocate memory for the Pager structure, PCache object, the
  38024. ** three file descriptors, the database file name and the journal
  38025. ** file name. The layout in memory is as follows:
  38026. **
  38027. ** Pager object (sizeof(Pager) bytes)
  38028. ** PCache object (sqlite3PcacheSize() bytes)
  38029. ** Database file handle (pVfs->szOsFile bytes)
  38030. ** Sub-journal file handle (journalFileSize bytes)
  38031. ** Main journal file handle (journalFileSize bytes)
  38032. ** Database file name (nPathname+1 bytes)
  38033. ** Journal file name (nPathname+8+1 bytes)
  38034. */
  38035. pPtr = (u8 *)sqlite3MallocZero(
  38036. ROUND8(sizeof(*pPager)) + /* Pager structure */
  38037. ROUND8(pcacheSize) + /* PCache object */
  38038. ROUND8(pVfs->szOsFile) + /* The main db file */
  38039. journalFileSize * 2 + /* The two journal files */
  38040. nPathname + 1 + /* zFilename */
  38041. nPathname + 8 + 1 /* zJournal */
  38042. #ifndef SQLITE_OMIT_WAL
  38043. + nPathname + 4 + 1 /* zWal */
  38044. #endif
  38045. );
  38046. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  38047. if( !pPtr ){
  38048. sqlite3_free(zPathname);
  38049. return SQLITE_NOMEM;
  38050. }
  38051. pPager = (Pager*)(pPtr);
  38052. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  38053. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  38054. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  38055. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  38056. pPager->zFilename = (char*)(pPtr += journalFileSize);
  38057. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  38058. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  38059. if( zPathname ){
  38060. assert( nPathname>0 );
  38061. pPager->zJournal = (char*)(pPtr += nPathname + 1);
  38062. memcpy(pPager->zFilename, zPathname, nPathname);
  38063. memcpy(pPager->zJournal, zPathname, nPathname);
  38064. memcpy(&pPager->zJournal[nPathname], "-journal", 8);
  38065. #ifndef SQLITE_OMIT_WAL
  38066. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  38067. memcpy(pPager->zWal, zPathname, nPathname);
  38068. memcpy(&pPager->zWal[nPathname], "-wal", 4);
  38069. #endif
  38070. sqlite3_free(zPathname);
  38071. }
  38072. pPager->pVfs = pVfs;
  38073. pPager->vfsFlags = vfsFlags;
  38074. /* Open the pager file.
  38075. */
  38076. if( zFilename && zFilename[0] ){
  38077. int fout = 0; /* VFS flags returned by xOpen() */
  38078. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  38079. assert( !memDb );
  38080. readOnly = (fout&SQLITE_OPEN_READONLY);
  38081. /* If the file was successfully opened for read/write access,
  38082. ** choose a default page size in case we have to create the
  38083. ** database file. The default page size is the maximum of:
  38084. **
  38085. ** + SQLITE_DEFAULT_PAGE_SIZE,
  38086. ** + The value returned by sqlite3OsSectorSize()
  38087. ** + The largest page size that can be written atomically.
  38088. */
  38089. if( rc==SQLITE_OK && !readOnly ){
  38090. setSectorSize(pPager);
  38091. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  38092. if( szPageDflt<pPager->sectorSize ){
  38093. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  38094. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  38095. }else{
  38096. szPageDflt = (u32)pPager->sectorSize;
  38097. }
  38098. }
  38099. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  38100. {
  38101. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  38102. int ii;
  38103. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  38104. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  38105. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  38106. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  38107. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  38108. szPageDflt = ii;
  38109. }
  38110. }
  38111. }
  38112. #endif
  38113. }
  38114. }else{
  38115. /* If a temporary file is requested, it is not opened immediately.
  38116. ** In this case we accept the default page size and delay actually
  38117. ** opening the file until the first call to OsWrite().
  38118. **
  38119. ** This branch is also run for an in-memory database. An in-memory
  38120. ** database is the same as a temp-file that is never written out to
  38121. ** disk and uses an in-memory rollback journal.
  38122. */
  38123. tempFile = 1;
  38124. pPager->eState = PAGER_READER;
  38125. pPager->eLock = EXCLUSIVE_LOCK;
  38126. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  38127. }
  38128. /* The following call to PagerSetPagesize() serves to set the value of
  38129. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  38130. */
  38131. if( rc==SQLITE_OK ){
  38132. assert( pPager->memDb==0 );
  38133. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  38134. testcase( rc!=SQLITE_OK );
  38135. }
  38136. /* If an error occurred in either of the blocks above, free the
  38137. ** Pager structure and close the file.
  38138. */
  38139. if( rc!=SQLITE_OK ){
  38140. assert( !pPager->pTmpSpace );
  38141. sqlite3OsClose(pPager->fd);
  38142. sqlite3_free(pPager);
  38143. return rc;
  38144. }
  38145. /* Initialize the PCache object. */
  38146. assert( nExtra<1000 );
  38147. nExtra = ROUND8(nExtra);
  38148. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  38149. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  38150. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  38151. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  38152. pPager->useJournal = (u8)useJournal;
  38153. pPager->noReadlock = (noReadlock && readOnly) ?1:0;
  38154. /* pPager->stmtOpen = 0; */
  38155. /* pPager->stmtInUse = 0; */
  38156. /* pPager->nRef = 0; */
  38157. /* pPager->stmtSize = 0; */
  38158. /* pPager->stmtJSize = 0; */
  38159. /* pPager->nPage = 0; */
  38160. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  38161. /* pPager->state = PAGER_UNLOCK; */
  38162. #if 0
  38163. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  38164. #endif
  38165. /* pPager->errMask = 0; */
  38166. pPager->tempFile = (u8)tempFile;
  38167. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  38168. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  38169. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  38170. pPager->exclusiveMode = (u8)tempFile;
  38171. pPager->changeCountDone = pPager->tempFile;
  38172. pPager->memDb = (u8)memDb;
  38173. pPager->readOnly = (u8)readOnly;
  38174. assert( useJournal || pPager->tempFile );
  38175. pPager->noSync = pPager->tempFile;
  38176. pPager->fullSync = pPager->noSync ?0:1;
  38177. pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
  38178. pPager->ckptSyncFlags = pPager->syncFlags;
  38179. /* pPager->pFirst = 0; */
  38180. /* pPager->pFirstSynced = 0; */
  38181. /* pPager->pLast = 0; */
  38182. pPager->nExtra = (u16)nExtra;
  38183. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  38184. assert( isOpen(pPager->fd) || tempFile );
  38185. setSectorSize(pPager);
  38186. if( !useJournal ){
  38187. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  38188. }else if( memDb ){
  38189. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  38190. }
  38191. /* pPager->xBusyHandler = 0; */
  38192. /* pPager->pBusyHandlerArg = 0; */
  38193. pPager->xReiniter = xReinit;
  38194. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  38195. *ppPager = pPager;
  38196. return SQLITE_OK;
  38197. }
  38198. /*
  38199. ** This function is called after transitioning from PAGER_UNLOCK to
  38200. ** PAGER_SHARED state. It tests if there is a hot journal present in
  38201. ** the file-system for the given pager. A hot journal is one that
  38202. ** needs to be played back. According to this function, a hot-journal
  38203. ** file exists if the following criteria are met:
  38204. **
  38205. ** * The journal file exists in the file system, and
  38206. ** * No process holds a RESERVED or greater lock on the database file, and
  38207. ** * The database file itself is greater than 0 bytes in size, and
  38208. ** * The first byte of the journal file exists and is not 0x00.
  38209. **
  38210. ** If the current size of the database file is 0 but a journal file
  38211. ** exists, that is probably an old journal left over from a prior
  38212. ** database with the same name. In this case the journal file is
  38213. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  38214. ** is returned.
  38215. **
  38216. ** This routine does not check if there is a master journal filename
  38217. ** at the end of the file. If there is, and that master journal file
  38218. ** does not exist, then the journal file is not really hot. In this
  38219. ** case this routine will return a false-positive. The pager_playback()
  38220. ** routine will discover that the journal file is not really hot and
  38221. ** will not roll it back.
  38222. **
  38223. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  38224. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  38225. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  38226. ** to determine whether or not a hot-journal file exists, the IO error
  38227. ** code is returned and the value of *pExists is undefined.
  38228. */
  38229. static int hasHotJournal(Pager *pPager, int *pExists){
  38230. sqlite3_vfs * const pVfs = pPager->pVfs;
  38231. int rc = SQLITE_OK; /* Return code */
  38232. int exists = 1; /* True if a journal file is present */
  38233. int jrnlOpen = !!isOpen(pPager->jfd);
  38234. assert( pPager->useJournal );
  38235. assert( isOpen(pPager->fd) );
  38236. assert( pPager->eState==PAGER_OPEN );
  38237. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  38238. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  38239. ));
  38240. *pExists = 0;
  38241. if( !jrnlOpen ){
  38242. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  38243. }
  38244. if( rc==SQLITE_OK && exists ){
  38245. int locked = 0; /* True if some process holds a RESERVED lock */
  38246. /* Race condition here: Another process might have been holding the
  38247. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  38248. ** call above, but then delete the journal and drop the lock before
  38249. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  38250. ** is the case, this routine might think there is a hot journal when
  38251. ** in fact there is none. This results in a false-positive which will
  38252. ** be dealt with by the playback routine. Ticket #3883.
  38253. */
  38254. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  38255. if( rc==SQLITE_OK && !locked ){
  38256. Pgno nPage; /* Number of pages in database file */
  38257. /* Check the size of the database file. If it consists of 0 pages,
  38258. ** then delete the journal file. See the header comment above for
  38259. ** the reasoning here. Delete the obsolete journal file under
  38260. ** a RESERVED lock to avoid race conditions and to avoid violating
  38261. ** [H33020].
  38262. */
  38263. rc = pagerPagecount(pPager, &nPage);
  38264. if( rc==SQLITE_OK ){
  38265. if( nPage==0 ){
  38266. sqlite3BeginBenignMalloc();
  38267. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  38268. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  38269. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  38270. }
  38271. sqlite3EndBenignMalloc();
  38272. }else{
  38273. /* The journal file exists and no other connection has a reserved
  38274. ** or greater lock on the database file. Now check that there is
  38275. ** at least one non-zero bytes at the start of the journal file.
  38276. ** If there is, then we consider this journal to be hot. If not,
  38277. ** it can be ignored.
  38278. */
  38279. if( !jrnlOpen ){
  38280. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  38281. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  38282. }
  38283. if( rc==SQLITE_OK ){
  38284. u8 first = 0;
  38285. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  38286. if( rc==SQLITE_IOERR_SHORT_READ ){
  38287. rc = SQLITE_OK;
  38288. }
  38289. if( !jrnlOpen ){
  38290. sqlite3OsClose(pPager->jfd);
  38291. }
  38292. *pExists = (first!=0);
  38293. }else if( rc==SQLITE_CANTOPEN ){
  38294. /* If we cannot open the rollback journal file in order to see if
  38295. ** its has a zero header, that might be due to an I/O error, or
  38296. ** it might be due to the race condition described above and in
  38297. ** ticket #3883. Either way, assume that the journal is hot.
  38298. ** This might be a false positive. But if it is, then the
  38299. ** automatic journal playback and recovery mechanism will deal
  38300. ** with it under an EXCLUSIVE lock where we do not need to
  38301. ** worry so much with race conditions.
  38302. */
  38303. *pExists = 1;
  38304. rc = SQLITE_OK;
  38305. }
  38306. }
  38307. }
  38308. }
  38309. }
  38310. return rc;
  38311. }
  38312. /*
  38313. ** This function is called to obtain a shared lock on the database file.
  38314. ** It is illegal to call sqlite3PagerAcquire() until after this function
  38315. ** has been successfully called. If a shared-lock is already held when
  38316. ** this function is called, it is a no-op.
  38317. **
  38318. ** The following operations are also performed by this function.
  38319. **
  38320. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  38321. ** on the database file), then an attempt is made to obtain a
  38322. ** SHARED lock on the database file. Immediately after obtaining
  38323. ** the SHARED lock, the file-system is checked for a hot-journal,
  38324. ** which is played back if present. Following any hot-journal
  38325. ** rollback, the contents of the cache are validated by checking
  38326. ** the 'change-counter' field of the database file header and
  38327. ** discarded if they are found to be invalid.
  38328. **
  38329. ** 2) If the pager is running in exclusive-mode, and there are currently
  38330. ** no outstanding references to any pages, and is in the error state,
  38331. ** then an attempt is made to clear the error state by discarding
  38332. ** the contents of the page cache and rolling back any open journal
  38333. ** file.
  38334. **
  38335. ** If everything is successful, SQLITE_OK is returned. If an IO error
  38336. ** occurs while locking the database, checking for a hot-journal file or
  38337. ** rolling back a journal file, the IO error code is returned.
  38338. */
  38339. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  38340. int rc = SQLITE_OK; /* Return code */
  38341. /* This routine is only called from b-tree and only when there are no
  38342. ** outstanding pages. This implies that the pager state should either
  38343. ** be OPEN or READER. READER is only possible if the pager is or was in
  38344. ** exclusive access mode.
  38345. */
  38346. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  38347. assert( assert_pager_state(pPager) );
  38348. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  38349. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  38350. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  38351. int bHotJournal = 1; /* True if there exists a hot journal-file */
  38352. assert( !MEMDB );
  38353. assert( pPager->noReadlock==0 || pPager->readOnly );
  38354. if( pPager->noReadlock==0 ){
  38355. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  38356. if( rc!=SQLITE_OK ){
  38357. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  38358. goto failed;
  38359. }
  38360. }
  38361. /* If a journal file exists, and there is no RESERVED lock on the
  38362. ** database file, then it either needs to be played back or deleted.
  38363. */
  38364. if( pPager->eLock<=SHARED_LOCK ){
  38365. rc = hasHotJournal(pPager, &bHotJournal);
  38366. }
  38367. if( rc!=SQLITE_OK ){
  38368. goto failed;
  38369. }
  38370. if( bHotJournal ){
  38371. /* Get an EXCLUSIVE lock on the database file. At this point it is
  38372. ** important that a RESERVED lock is not obtained on the way to the
  38373. ** EXCLUSIVE lock. If it were, another process might open the
  38374. ** database file, detect the RESERVED lock, and conclude that the
  38375. ** database is safe to read while this process is still rolling the
  38376. ** hot-journal back.
  38377. **
  38378. ** Because the intermediate RESERVED lock is not requested, any
  38379. ** other process attempting to access the database file will get to
  38380. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  38381. ** on the database file.
  38382. **
  38383. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  38384. ** downgraded to SHARED_LOCK before this function returns.
  38385. */
  38386. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  38387. if( rc!=SQLITE_OK ){
  38388. goto failed;
  38389. }
  38390. /* If it is not already open and the file exists on disk, open the
  38391. ** journal for read/write access. Write access is required because
  38392. ** in exclusive-access mode the file descriptor will be kept open
  38393. ** and possibly used for a transaction later on. Also, write-access
  38394. ** is usually required to finalize the journal in journal_mode=persist
  38395. ** mode (and also for journal_mode=truncate on some systems).
  38396. **
  38397. ** If the journal does not exist, it usually means that some
  38398. ** other connection managed to get in and roll it back before
  38399. ** this connection obtained the exclusive lock above. Or, it
  38400. ** may mean that the pager was in the error-state when this
  38401. ** function was called and the journal file does not exist.
  38402. */
  38403. if( !isOpen(pPager->jfd) ){
  38404. sqlite3_vfs * const pVfs = pPager->pVfs;
  38405. int bExists; /* True if journal file exists */
  38406. rc = sqlite3OsAccess(
  38407. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  38408. if( rc==SQLITE_OK && bExists ){
  38409. int fout = 0;
  38410. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  38411. assert( !pPager->tempFile );
  38412. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  38413. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  38414. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  38415. rc = SQLITE_CANTOPEN_BKPT;
  38416. sqlite3OsClose(pPager->jfd);
  38417. }
  38418. }
  38419. }
  38420. /* Playback and delete the journal. Drop the database write
  38421. ** lock and reacquire the read lock. Purge the cache before
  38422. ** playing back the hot-journal so that we don't end up with
  38423. ** an inconsistent cache. Sync the hot journal before playing
  38424. ** it back since the process that crashed and left the hot journal
  38425. ** probably did not sync it and we are required to always sync
  38426. ** the journal before playing it back.
  38427. */
  38428. if( isOpen(pPager->jfd) ){
  38429. assert( rc==SQLITE_OK );
  38430. rc = pagerSyncHotJournal(pPager);
  38431. if( rc==SQLITE_OK ){
  38432. rc = pager_playback(pPager, 1);
  38433. pPager->eState = PAGER_OPEN;
  38434. }
  38435. }else if( !pPager->exclusiveMode ){
  38436. pagerUnlockDb(pPager, SHARED_LOCK);
  38437. }
  38438. if( rc!=SQLITE_OK ){
  38439. /* This branch is taken if an error occurs while trying to open
  38440. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  38441. ** pager_unlock() routine will be called before returning to unlock
  38442. ** the file. If the unlock attempt fails, then Pager.eLock must be
  38443. ** set to UNKNOWN_LOCK (see the comment above the #define for
  38444. ** UNKNOWN_LOCK above for an explanation).
  38445. **
  38446. ** In order to get pager_unlock() to do this, set Pager.eState to
  38447. ** PAGER_ERROR now. This is not actually counted as a transition
  38448. ** to ERROR state in the state diagram at the top of this file,
  38449. ** since we know that the same call to pager_unlock() will very
  38450. ** shortly transition the pager object to the OPEN state. Calling
  38451. ** assert_pager_state() would fail now, as it should not be possible
  38452. ** to be in ERROR state when there are zero outstanding page
  38453. ** references.
  38454. */
  38455. pager_error(pPager, rc);
  38456. goto failed;
  38457. }
  38458. assert( pPager->eState==PAGER_OPEN );
  38459. assert( (pPager->eLock==SHARED_LOCK)
  38460. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  38461. );
  38462. }
  38463. if( !pPager->tempFile
  38464. && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
  38465. ){
  38466. /* The shared-lock has just been acquired on the database file
  38467. ** and there are already pages in the cache (from a previous
  38468. ** read or write transaction). Check to see if the database
  38469. ** has been modified. If the database has changed, flush the
  38470. ** cache.
  38471. **
  38472. ** Database changes is detected by looking at 15 bytes beginning
  38473. ** at offset 24 into the file. The first 4 of these 16 bytes are
  38474. ** a 32-bit counter that is incremented with each change. The
  38475. ** other bytes change randomly with each file change when
  38476. ** a codec is in use.
  38477. **
  38478. ** There is a vanishingly small chance that a change will not be
  38479. ** detected. The chance of an undetected change is so small that
  38480. ** it can be neglected.
  38481. */
  38482. Pgno nPage = 0;
  38483. char dbFileVers[sizeof(pPager->dbFileVers)];
  38484. rc = pagerPagecount(pPager, &nPage);
  38485. if( rc ) goto failed;
  38486. if( nPage>0 ){
  38487. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  38488. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  38489. if( rc!=SQLITE_OK ){
  38490. goto failed;
  38491. }
  38492. }else{
  38493. memset(dbFileVers, 0, sizeof(dbFileVers));
  38494. }
  38495. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  38496. pager_reset(pPager);
  38497. }
  38498. }
  38499. /* If there is a WAL file in the file-system, open this database in WAL
  38500. ** mode. Otherwise, the following function call is a no-op.
  38501. */
  38502. rc = pagerOpenWalIfPresent(pPager);
  38503. #ifndef SQLITE_OMIT_WAL
  38504. assert( pPager->pWal==0 || rc==SQLITE_OK );
  38505. #endif
  38506. }
  38507. if( pagerUseWal(pPager) ){
  38508. assert( rc==SQLITE_OK );
  38509. rc = pagerBeginReadTransaction(pPager);
  38510. }
  38511. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  38512. rc = pagerPagecount(pPager, &pPager->dbSize);
  38513. }
  38514. failed:
  38515. if( rc!=SQLITE_OK ){
  38516. assert( !MEMDB );
  38517. pager_unlock(pPager);
  38518. assert( pPager->eState==PAGER_OPEN );
  38519. }else{
  38520. pPager->eState = PAGER_READER;
  38521. }
  38522. return rc;
  38523. }
  38524. /*
  38525. ** If the reference count has reached zero, rollback any active
  38526. ** transaction and unlock the pager.
  38527. **
  38528. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  38529. ** the rollback journal, the unlock is not performed and there is
  38530. ** nothing to rollback, so this routine is a no-op.
  38531. */
  38532. static void pagerUnlockIfUnused(Pager *pPager){
  38533. if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  38534. pagerUnlockAndRollback(pPager);
  38535. }
  38536. }
  38537. /*
  38538. ** Acquire a reference to page number pgno in pager pPager (a page
  38539. ** reference has type DbPage*). If the requested reference is
  38540. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  38541. **
  38542. ** If the requested page is already in the cache, it is returned.
  38543. ** Otherwise, a new page object is allocated and populated with data
  38544. ** read from the database file. In some cases, the pcache module may
  38545. ** choose not to allocate a new page object and may reuse an existing
  38546. ** object with no outstanding references.
  38547. **
  38548. ** The extra data appended to a page is always initialized to zeros the
  38549. ** first time a page is loaded into memory. If the page requested is
  38550. ** already in the cache when this function is called, then the extra
  38551. ** data is left as it was when the page object was last used.
  38552. **
  38553. ** If the database image is smaller than the requested page or if a
  38554. ** non-zero value is passed as the noContent parameter and the
  38555. ** requested page is not already stored in the cache, then no
  38556. ** actual disk read occurs. In this case the memory image of the
  38557. ** page is initialized to all zeros.
  38558. **
  38559. ** If noContent is true, it means that we do not care about the contents
  38560. ** of the page. This occurs in two seperate scenarios:
  38561. **
  38562. ** a) When reading a free-list leaf page from the database, and
  38563. **
  38564. ** b) When a savepoint is being rolled back and we need to load
  38565. ** a new page into the cache to be filled with the data read
  38566. ** from the savepoint journal.
  38567. **
  38568. ** If noContent is true, then the data returned is zeroed instead of
  38569. ** being read from the database. Additionally, the bits corresponding
  38570. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  38571. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  38572. ** savepoints are set. This means if the page is made writable at any
  38573. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  38574. ** will not be journaled. This saves IO.
  38575. **
  38576. ** The acquisition might fail for several reasons. In all cases,
  38577. ** an appropriate error code is returned and *ppPage is set to NULL.
  38578. **
  38579. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  38580. ** to find a page in the in-memory cache first. If the page is not already
  38581. ** in memory, this routine goes to disk to read it in whereas Lookup()
  38582. ** just returns 0. This routine acquires a read-lock the first time it
  38583. ** has to go to disk, and could also playback an old journal if necessary.
  38584. ** Since Lookup() never goes to disk, it never has to deal with locks
  38585. ** or journal files.
  38586. */
  38587. SQLITE_PRIVATE int sqlite3PagerAcquire(
  38588. Pager *pPager, /* The pager open on the database file */
  38589. Pgno pgno, /* Page number to fetch */
  38590. DbPage **ppPage, /* Write a pointer to the page here */
  38591. int noContent /* Do not bother reading content from disk if true */
  38592. ){
  38593. int rc;
  38594. PgHdr *pPg;
  38595. assert( pPager->eState>=PAGER_READER );
  38596. assert( assert_pager_state(pPager) );
  38597. if( pgno==0 ){
  38598. return SQLITE_CORRUPT_BKPT;
  38599. }
  38600. /* If the pager is in the error state, return an error immediately.
  38601. ** Otherwise, request the page from the PCache layer. */
  38602. if( pPager->errCode!=SQLITE_OK ){
  38603. rc = pPager->errCode;
  38604. }else{
  38605. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  38606. }
  38607. if( rc!=SQLITE_OK ){
  38608. /* Either the call to sqlite3PcacheFetch() returned an error or the
  38609. ** pager was already in the error-state when this function was called.
  38610. ** Set pPg to 0 and jump to the exception handler. */
  38611. pPg = 0;
  38612. goto pager_acquire_err;
  38613. }
  38614. assert( (*ppPage)->pgno==pgno );
  38615. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  38616. if( (*ppPage)->pPager && !noContent ){
  38617. /* In this case the pcache already contains an initialized copy of
  38618. ** the page. Return without further ado. */
  38619. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  38620. PAGER_INCR(pPager->nHit);
  38621. return SQLITE_OK;
  38622. }else{
  38623. /* The pager cache has created a new page. Its content needs to
  38624. ** be initialized. */
  38625. PAGER_INCR(pPager->nMiss);
  38626. pPg = *ppPage;
  38627. pPg->pPager = pPager;
  38628. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  38629. ** number greater than this, or the unused locking-page, is requested. */
  38630. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  38631. rc = SQLITE_CORRUPT_BKPT;
  38632. goto pager_acquire_err;
  38633. }
  38634. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  38635. if( pgno>pPager->mxPgno ){
  38636. rc = SQLITE_FULL;
  38637. goto pager_acquire_err;
  38638. }
  38639. if( noContent ){
  38640. /* Failure to set the bits in the InJournal bit-vectors is benign.
  38641. ** It merely means that we might do some extra work to journal a
  38642. ** page that does not need to be journaled. Nevertheless, be sure
  38643. ** to test the case where a malloc error occurs while trying to set
  38644. ** a bit in a bit vector.
  38645. */
  38646. sqlite3BeginBenignMalloc();
  38647. if( pgno<=pPager->dbOrigSize ){
  38648. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  38649. testcase( rc==SQLITE_NOMEM );
  38650. }
  38651. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  38652. testcase( rc==SQLITE_NOMEM );
  38653. sqlite3EndBenignMalloc();
  38654. }
  38655. memset(pPg->pData, 0, pPager->pageSize);
  38656. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  38657. }else{
  38658. assert( pPg->pPager==pPager );
  38659. rc = readDbPage(pPg);
  38660. if( rc!=SQLITE_OK ){
  38661. goto pager_acquire_err;
  38662. }
  38663. }
  38664. pager_set_pagehash(pPg);
  38665. }
  38666. return SQLITE_OK;
  38667. pager_acquire_err:
  38668. assert( rc!=SQLITE_OK );
  38669. if( pPg ){
  38670. sqlite3PcacheDrop(pPg);
  38671. }
  38672. pagerUnlockIfUnused(pPager);
  38673. *ppPage = 0;
  38674. return rc;
  38675. }
  38676. /*
  38677. ** Acquire a page if it is already in the in-memory cache. Do
  38678. ** not read the page from disk. Return a pointer to the page,
  38679. ** or 0 if the page is not in cache.
  38680. **
  38681. ** See also sqlite3PagerGet(). The difference between this routine
  38682. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  38683. ** in the page if the page is not already in cache. This routine
  38684. ** returns NULL if the page is not in cache or if a disk I/O error
  38685. ** has ever happened.
  38686. */
  38687. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  38688. PgHdr *pPg = 0;
  38689. assert( pPager!=0 );
  38690. assert( pgno!=0 );
  38691. assert( pPager->pPCache!=0 );
  38692. assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
  38693. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  38694. return pPg;
  38695. }
  38696. /*
  38697. ** Release a page reference.
  38698. **
  38699. ** If the number of references to the page drop to zero, then the
  38700. ** page is added to the LRU list. When all references to all pages
  38701. ** are released, a rollback occurs and the lock on the database is
  38702. ** removed.
  38703. */
  38704. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  38705. if( pPg ){
  38706. Pager *pPager = pPg->pPager;
  38707. sqlite3PcacheRelease(pPg);
  38708. pagerUnlockIfUnused(pPager);
  38709. }
  38710. }
  38711. /*
  38712. ** This function is called at the start of every write transaction.
  38713. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  38714. ** file when this routine is called.
  38715. **
  38716. ** Open the journal file for pager pPager and write a journal header
  38717. ** to the start of it. If there are active savepoints, open the sub-journal
  38718. ** as well. This function is only used when the journal file is being
  38719. ** opened to write a rollback log for a transaction. It is not used
  38720. ** when opening a hot journal file to roll it back.
  38721. **
  38722. ** If the journal file is already open (as it may be in exclusive mode),
  38723. ** then this function just writes a journal header to the start of the
  38724. ** already open file.
  38725. **
  38726. ** Whether or not the journal file is opened by this function, the
  38727. ** Pager.pInJournal bitvec structure is allocated.
  38728. **
  38729. ** Return SQLITE_OK if everything is successful. Otherwise, return
  38730. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  38731. ** an IO error code if opening or writing the journal file fails.
  38732. */
  38733. static int pager_open_journal(Pager *pPager){
  38734. int rc = SQLITE_OK; /* Return code */
  38735. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  38736. assert( pPager->eState==PAGER_WRITER_LOCKED );
  38737. assert( assert_pager_state(pPager) );
  38738. assert( pPager->pInJournal==0 );
  38739. /* If already in the error state, this function is a no-op. But on
  38740. ** the other hand, this routine is never called if we are already in
  38741. ** an error state. */
  38742. if( NEVER(pPager->errCode) ) return pPager->errCode;
  38743. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  38744. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  38745. if( pPager->pInJournal==0 ){
  38746. return SQLITE_NOMEM;
  38747. }
  38748. /* Open the journal file if it is not already open. */
  38749. if( !isOpen(pPager->jfd) ){
  38750. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  38751. sqlite3MemJournalOpen(pPager->jfd);
  38752. }else{
  38753. const int flags = /* VFS flags to open journal file */
  38754. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  38755. (pPager->tempFile ?
  38756. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  38757. (SQLITE_OPEN_MAIN_JOURNAL)
  38758. );
  38759. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  38760. rc = sqlite3JournalOpen(
  38761. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  38762. );
  38763. #else
  38764. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  38765. #endif
  38766. }
  38767. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  38768. }
  38769. /* Write the first journal header to the journal file and open
  38770. ** the sub-journal if necessary.
  38771. */
  38772. if( rc==SQLITE_OK ){
  38773. /* TODO: Check if all of these are really required. */
  38774. pPager->nRec = 0;
  38775. pPager->journalOff = 0;
  38776. pPager->setMaster = 0;
  38777. pPager->journalHdr = 0;
  38778. rc = writeJournalHdr(pPager);
  38779. }
  38780. }
  38781. if( rc!=SQLITE_OK ){
  38782. sqlite3BitvecDestroy(pPager->pInJournal);
  38783. pPager->pInJournal = 0;
  38784. }else{
  38785. assert( pPager->eState==PAGER_WRITER_LOCKED );
  38786. pPager->eState = PAGER_WRITER_CACHEMOD;
  38787. }
  38788. return rc;
  38789. }
  38790. /*
  38791. ** Begin a write-transaction on the specified pager object. If a
  38792. ** write-transaction has already been opened, this function is a no-op.
  38793. **
  38794. ** If the exFlag argument is false, then acquire at least a RESERVED
  38795. ** lock on the database file. If exFlag is true, then acquire at least
  38796. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  38797. ** functions need be called.
  38798. **
  38799. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  38800. ** within this transaction will be opened as an in-memory file. This
  38801. ** has no effect if the sub-journal is already opened (as it may be when
  38802. ** running in exclusive mode) or if the transaction does not require a
  38803. ** sub-journal. If the subjInMemory argument is zero, then any required
  38804. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  38805. ** or using a temporary file otherwise.
  38806. */
  38807. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  38808. int rc = SQLITE_OK;
  38809. if( pPager->errCode ) return pPager->errCode;
  38810. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  38811. pPager->subjInMemory = (u8)subjInMemory;
  38812. if( ALWAYS(pPager->eState==PAGER_READER) ){
  38813. assert( pPager->pInJournal==0 );
  38814. if( pagerUseWal(pPager) ){
  38815. /* If the pager is configured to use locking_mode=exclusive, and an
  38816. ** exclusive lock on the database is not already held, obtain it now.
  38817. */
  38818. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  38819. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  38820. if( rc!=SQLITE_OK ){
  38821. return rc;
  38822. }
  38823. sqlite3WalExclusiveMode(pPager->pWal, 1);
  38824. }
  38825. /* Grab the write lock on the log file. If successful, upgrade to
  38826. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  38827. ** The busy-handler is not invoked if another connection already
  38828. ** holds the write-lock. If possible, the upper layer will call it.
  38829. */
  38830. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  38831. }else{
  38832. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  38833. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  38834. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  38835. ** lock, but not when obtaining the RESERVED lock.
  38836. */
  38837. rc = pagerLockDb(pPager, RESERVED_LOCK);
  38838. if( rc==SQLITE_OK && exFlag ){
  38839. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  38840. }
  38841. }
  38842. if( rc==SQLITE_OK ){
  38843. /* Change to WRITER_LOCKED state.
  38844. **
  38845. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  38846. ** when it has an open transaction, but never to DBMOD or FINISHED.
  38847. ** This is because in those states the code to roll back savepoint
  38848. ** transactions may copy data from the sub-journal into the database
  38849. ** file as well as into the page cache. Which would be incorrect in
  38850. ** WAL mode.
  38851. */
  38852. pPager->eState = PAGER_WRITER_LOCKED;
  38853. pPager->dbHintSize = pPager->dbSize;
  38854. pPager->dbFileSize = pPager->dbSize;
  38855. pPager->dbOrigSize = pPager->dbSize;
  38856. pPager->journalOff = 0;
  38857. }
  38858. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  38859. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  38860. assert( assert_pager_state(pPager) );
  38861. }
  38862. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  38863. return rc;
  38864. }
  38865. /*
  38866. ** Mark a single data page as writeable. The page is written into the
  38867. ** main journal or sub-journal as required. If the page is written into
  38868. ** one of the journals, the corresponding bit is set in the
  38869. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  38870. ** of any open savepoints as appropriate.
  38871. */
  38872. static int pager_write(PgHdr *pPg){
  38873. void *pData = pPg->pData;
  38874. Pager *pPager = pPg->pPager;
  38875. int rc = SQLITE_OK;
  38876. /* This routine is not called unless a write-transaction has already
  38877. ** been started. The journal file may or may not be open at this point.
  38878. ** It is never called in the ERROR state.
  38879. */
  38880. assert( pPager->eState==PAGER_WRITER_LOCKED
  38881. || pPager->eState==PAGER_WRITER_CACHEMOD
  38882. || pPager->eState==PAGER_WRITER_DBMOD
  38883. );
  38884. assert( assert_pager_state(pPager) );
  38885. /* If an error has been previously detected, report the same error
  38886. ** again. This should not happen, but the check provides robustness. */
  38887. if( NEVER(pPager->errCode) ) return pPager->errCode;
  38888. /* Higher-level routines never call this function if database is not
  38889. ** writable. But check anyway, just for robustness. */
  38890. if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
  38891. CHECK_PAGE(pPg);
  38892. /* The journal file needs to be opened. Higher level routines have already
  38893. ** obtained the necessary locks to begin the write-transaction, but the
  38894. ** rollback journal might not yet be open. Open it now if this is the case.
  38895. **
  38896. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  38897. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  38898. ** an error might occur and the pager would end up in WRITER_LOCKED state
  38899. ** with pages marked as dirty in the cache.
  38900. */
  38901. if( pPager->eState==PAGER_WRITER_LOCKED ){
  38902. rc = pager_open_journal(pPager);
  38903. if( rc!=SQLITE_OK ) return rc;
  38904. }
  38905. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  38906. assert( assert_pager_state(pPager) );
  38907. /* Mark the page as dirty. If the page has already been written
  38908. ** to the journal then we can return right away.
  38909. */
  38910. sqlite3PcacheMakeDirty(pPg);
  38911. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  38912. assert( !pagerUseWal(pPager) );
  38913. }else{
  38914. /* The transaction journal now exists and we have a RESERVED or an
  38915. ** EXCLUSIVE lock on the main database file. Write the current page to
  38916. ** the transaction journal if it is not there already.
  38917. */
  38918. if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
  38919. assert( pagerUseWal(pPager)==0 );
  38920. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  38921. u32 cksum;
  38922. char *pData2;
  38923. i64 iOff = pPager->journalOff;
  38924. /* We should never write to the journal file the page that
  38925. ** contains the database locks. The following assert verifies
  38926. ** that we do not. */
  38927. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  38928. assert( pPager->journalHdr<=pPager->journalOff );
  38929. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  38930. cksum = pager_cksum(pPager, (u8*)pData2);
  38931. /* Even if an IO or diskfull error occurs while journalling the
  38932. ** page in the block above, set the need-sync flag for the page.
  38933. ** Otherwise, when the transaction is rolled back, the logic in
  38934. ** playback_one_page() will think that the page needs to be restored
  38935. ** in the database file. And if an IO error occurs while doing so,
  38936. ** then corruption may follow.
  38937. */
  38938. pPg->flags |= PGHDR_NEED_SYNC;
  38939. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  38940. if( rc!=SQLITE_OK ) return rc;
  38941. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  38942. if( rc!=SQLITE_OK ) return rc;
  38943. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  38944. if( rc!=SQLITE_OK ) return rc;
  38945. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  38946. pPager->journalOff, pPager->pageSize));
  38947. PAGER_INCR(sqlite3_pager_writej_count);
  38948. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  38949. PAGERID(pPager), pPg->pgno,
  38950. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  38951. pPager->journalOff += 8 + pPager->pageSize;
  38952. pPager->nRec++;
  38953. assert( pPager->pInJournal!=0 );
  38954. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  38955. testcase( rc==SQLITE_NOMEM );
  38956. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  38957. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  38958. if( rc!=SQLITE_OK ){
  38959. assert( rc==SQLITE_NOMEM );
  38960. return rc;
  38961. }
  38962. }else{
  38963. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  38964. pPg->flags |= PGHDR_NEED_SYNC;
  38965. }
  38966. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  38967. PAGERID(pPager), pPg->pgno,
  38968. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  38969. }
  38970. }
  38971. /* If the statement journal is open and the page is not in it,
  38972. ** then write the current page to the statement journal. Note that
  38973. ** the statement journal format differs from the standard journal format
  38974. ** in that it omits the checksums and the header.
  38975. */
  38976. if( subjRequiresPage(pPg) ){
  38977. rc = subjournalPage(pPg);
  38978. }
  38979. }
  38980. /* Update the database size and return.
  38981. */
  38982. if( pPager->dbSize<pPg->pgno ){
  38983. pPager->dbSize = pPg->pgno;
  38984. }
  38985. return rc;
  38986. }
  38987. /*
  38988. ** Mark a data page as writeable. This routine must be called before
  38989. ** making changes to a page. The caller must check the return value
  38990. ** of this function and be careful not to change any page data unless
  38991. ** this routine returns SQLITE_OK.
  38992. **
  38993. ** The difference between this function and pager_write() is that this
  38994. ** function also deals with the special case where 2 or more pages
  38995. ** fit on a single disk sector. In this case all co-resident pages
  38996. ** must have been written to the journal file before returning.
  38997. **
  38998. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  38999. ** as appropriate. Otherwise, SQLITE_OK.
  39000. */
  39001. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  39002. int rc = SQLITE_OK;
  39003. PgHdr *pPg = pDbPage;
  39004. Pager *pPager = pPg->pPager;
  39005. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  39006. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  39007. assert( pPager->eState!=PAGER_ERROR );
  39008. assert( assert_pager_state(pPager) );
  39009. if( nPagePerSector>1 ){
  39010. Pgno nPageCount; /* Total number of pages in database file */
  39011. Pgno pg1; /* First page of the sector pPg is located on. */
  39012. int nPage = 0; /* Number of pages starting at pg1 to journal */
  39013. int ii; /* Loop counter */
  39014. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  39015. /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
  39016. ** a journal header to be written between the pages journaled by
  39017. ** this function.
  39018. */
  39019. assert( !MEMDB );
  39020. assert( pPager->doNotSyncSpill==0 );
  39021. pPager->doNotSyncSpill++;
  39022. /* This trick assumes that both the page-size and sector-size are
  39023. ** an integer power of 2. It sets variable pg1 to the identifier
  39024. ** of the first page of the sector pPg is located on.
  39025. */
  39026. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  39027. nPageCount = pPager->dbSize;
  39028. if( pPg->pgno>nPageCount ){
  39029. nPage = (pPg->pgno - pg1)+1;
  39030. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  39031. nPage = nPageCount+1-pg1;
  39032. }else{
  39033. nPage = nPagePerSector;
  39034. }
  39035. assert(nPage>0);
  39036. assert(pg1<=pPg->pgno);
  39037. assert((pg1+nPage)>pPg->pgno);
  39038. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  39039. Pgno pg = pg1+ii;
  39040. PgHdr *pPage;
  39041. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  39042. if( pg!=PAGER_MJ_PGNO(pPager) ){
  39043. rc = sqlite3PagerGet(pPager, pg, &pPage);
  39044. if( rc==SQLITE_OK ){
  39045. rc = pager_write(pPage);
  39046. if( pPage->flags&PGHDR_NEED_SYNC ){
  39047. needSync = 1;
  39048. }
  39049. sqlite3PagerUnref(pPage);
  39050. }
  39051. }
  39052. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  39053. if( pPage->flags&PGHDR_NEED_SYNC ){
  39054. needSync = 1;
  39055. }
  39056. sqlite3PagerUnref(pPage);
  39057. }
  39058. }
  39059. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  39060. ** starting at pg1, then it needs to be set for all of them. Because
  39061. ** writing to any of these nPage pages may damage the others, the
  39062. ** journal file must contain sync()ed copies of all of them
  39063. ** before any of them can be written out to the database file.
  39064. */
  39065. if( rc==SQLITE_OK && needSync ){
  39066. assert( !MEMDB );
  39067. for(ii=0; ii<nPage; ii++){
  39068. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  39069. if( pPage ){
  39070. pPage->flags |= PGHDR_NEED_SYNC;
  39071. sqlite3PagerUnref(pPage);
  39072. }
  39073. }
  39074. }
  39075. assert( pPager->doNotSyncSpill==1 );
  39076. pPager->doNotSyncSpill--;
  39077. }else{
  39078. rc = pager_write(pDbPage);
  39079. }
  39080. return rc;
  39081. }
  39082. /*
  39083. ** Return TRUE if the page given in the argument was previously passed
  39084. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  39085. ** to change the content of the page.
  39086. */
  39087. #ifndef NDEBUG
  39088. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  39089. return pPg->flags&PGHDR_DIRTY;
  39090. }
  39091. #endif
  39092. /*
  39093. ** A call to this routine tells the pager that it is not necessary to
  39094. ** write the information on page pPg back to the disk, even though
  39095. ** that page might be marked as dirty. This happens, for example, when
  39096. ** the page has been added as a leaf of the freelist and so its
  39097. ** content no longer matters.
  39098. **
  39099. ** The overlying software layer calls this routine when all of the data
  39100. ** on the given page is unused. The pager marks the page as clean so
  39101. ** that it does not get written to disk.
  39102. **
  39103. ** Tests show that this optimization can quadruple the speed of large
  39104. ** DELETE operations.
  39105. */
  39106. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  39107. Pager *pPager = pPg->pPager;
  39108. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  39109. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  39110. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  39111. pPg->flags |= PGHDR_DONT_WRITE;
  39112. pager_set_pagehash(pPg);
  39113. }
  39114. }
  39115. /*
  39116. ** This routine is called to increment the value of the database file
  39117. ** change-counter, stored as a 4-byte big-endian integer starting at
  39118. ** byte offset 24 of the pager file. The secondary change counter at
  39119. ** 92 is also updated, as is the SQLite version number at offset 96.
  39120. **
  39121. ** But this only happens if the pPager->changeCountDone flag is false.
  39122. ** To avoid excess churning of page 1, the update only happens once.
  39123. ** See also the pager_write_changecounter() routine that does an
  39124. ** unconditional update of the change counters.
  39125. **
  39126. ** If the isDirectMode flag is zero, then this is done by calling
  39127. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  39128. ** page data. In this case the file will be updated when the current
  39129. ** transaction is committed.
  39130. **
  39131. ** The isDirectMode flag may only be non-zero if the library was compiled
  39132. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  39133. ** if isDirect is non-zero, then the database file is updated directly
  39134. ** by writing an updated version of page 1 using a call to the
  39135. ** sqlite3OsWrite() function.
  39136. */
  39137. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  39138. int rc = SQLITE_OK;
  39139. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  39140. || pPager->eState==PAGER_WRITER_DBMOD
  39141. );
  39142. assert( assert_pager_state(pPager) );
  39143. /* Declare and initialize constant integer 'isDirect'. If the
  39144. ** atomic-write optimization is enabled in this build, then isDirect
  39145. ** is initialized to the value passed as the isDirectMode parameter
  39146. ** to this function. Otherwise, it is always set to zero.
  39147. **
  39148. ** The idea is that if the atomic-write optimization is not
  39149. ** enabled at compile time, the compiler can omit the tests of
  39150. ** 'isDirect' below, as well as the block enclosed in the
  39151. ** "if( isDirect )" condition.
  39152. */
  39153. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  39154. # define DIRECT_MODE 0
  39155. assert( isDirectMode==0 );
  39156. UNUSED_PARAMETER(isDirectMode);
  39157. #else
  39158. # define DIRECT_MODE isDirectMode
  39159. #endif
  39160. if( !pPager->changeCountDone && pPager->dbSize>0 ){
  39161. PgHdr *pPgHdr; /* Reference to page 1 */
  39162. assert( !pPager->tempFile && isOpen(pPager->fd) );
  39163. /* Open page 1 of the file for writing. */
  39164. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  39165. assert( pPgHdr==0 || rc==SQLITE_OK );
  39166. /* If page one was fetched successfully, and this function is not
  39167. ** operating in direct-mode, make page 1 writable. When not in
  39168. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  39169. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  39170. */
  39171. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  39172. rc = sqlite3PagerWrite(pPgHdr);
  39173. }
  39174. if( rc==SQLITE_OK ){
  39175. /* Actually do the update of the change counter */
  39176. pager_write_changecounter(pPgHdr);
  39177. /* If running in direct mode, write the contents of page 1 to the file. */
  39178. if( DIRECT_MODE ){
  39179. const void *zBuf;
  39180. assert( pPager->dbFileSize>0 );
  39181. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  39182. if( rc==SQLITE_OK ){
  39183. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  39184. }
  39185. if( rc==SQLITE_OK ){
  39186. pPager->changeCountDone = 1;
  39187. }
  39188. }else{
  39189. pPager->changeCountDone = 1;
  39190. }
  39191. }
  39192. /* Release the page reference. */
  39193. sqlite3PagerUnref(pPgHdr);
  39194. }
  39195. return rc;
  39196. }
  39197. /*
  39198. ** Sync the database file to disk. This is a no-op for in-memory databases
  39199. ** or pages with the Pager.noSync flag set.
  39200. **
  39201. ** If successful, or if called on a pager for which it is a no-op, this
  39202. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  39203. */
  39204. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  39205. int rc = SQLITE_OK;
  39206. if( !pPager->noSync ){
  39207. assert( !MEMDB );
  39208. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  39209. }else if( isOpen(pPager->fd) ){
  39210. assert( !MEMDB );
  39211. sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
  39212. }
  39213. return rc;
  39214. }
  39215. /*
  39216. ** This function may only be called while a write-transaction is active in
  39217. ** rollback. If the connection is in WAL mode, this call is a no-op.
  39218. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  39219. ** the database file, an attempt is made to obtain one.
  39220. **
  39221. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  39222. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  39223. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  39224. ** returned.
  39225. */
  39226. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  39227. int rc = SQLITE_OK;
  39228. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  39229. || pPager->eState==PAGER_WRITER_DBMOD
  39230. || pPager->eState==PAGER_WRITER_LOCKED
  39231. );
  39232. assert( assert_pager_state(pPager) );
  39233. if( 0==pagerUseWal(pPager) ){
  39234. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  39235. }
  39236. return rc;
  39237. }
  39238. /*
  39239. ** Sync the database file for the pager pPager. zMaster points to the name
  39240. ** of a master journal file that should be written into the individual
  39241. ** journal file. zMaster may be NULL, which is interpreted as no master
  39242. ** journal (a single database transaction).
  39243. **
  39244. ** This routine ensures that:
  39245. **
  39246. ** * The database file change-counter is updated,
  39247. ** * the journal is synced (unless the atomic-write optimization is used),
  39248. ** * all dirty pages are written to the database file,
  39249. ** * the database file is truncated (if required), and
  39250. ** * the database file synced.
  39251. **
  39252. ** The only thing that remains to commit the transaction is to finalize
  39253. ** (delete, truncate or zero the first part of) the journal file (or
  39254. ** delete the master journal file if specified).
  39255. **
  39256. ** Note that if zMaster==NULL, this does not overwrite a previous value
  39257. ** passed to an sqlite3PagerCommitPhaseOne() call.
  39258. **
  39259. ** If the final parameter - noSync - is true, then the database file itself
  39260. ** is not synced. The caller must call sqlite3PagerSync() directly to
  39261. ** sync the database file before calling CommitPhaseTwo() to delete the
  39262. ** journal file in this case.
  39263. */
  39264. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  39265. Pager *pPager, /* Pager object */
  39266. const char *zMaster, /* If not NULL, the master journal name */
  39267. int noSync /* True to omit the xSync on the db file */
  39268. ){
  39269. int rc = SQLITE_OK; /* Return code */
  39270. assert( pPager->eState==PAGER_WRITER_LOCKED
  39271. || pPager->eState==PAGER_WRITER_CACHEMOD
  39272. || pPager->eState==PAGER_WRITER_DBMOD
  39273. || pPager->eState==PAGER_ERROR
  39274. );
  39275. assert( assert_pager_state(pPager) );
  39276. /* If a prior error occurred, report that error again. */
  39277. if( NEVER(pPager->errCode) ) return pPager->errCode;
  39278. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  39279. pPager->zFilename, zMaster, pPager->dbSize));
  39280. /* If no database changes have been made, return early. */
  39281. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  39282. if( MEMDB ){
  39283. /* If this is an in-memory db, or no pages have been written to, or this
  39284. ** function has already been called, it is mostly a no-op. However, any
  39285. ** backup in progress needs to be restarted.
  39286. */
  39287. sqlite3BackupRestart(pPager->pBackup);
  39288. }else{
  39289. if( pagerUseWal(pPager) ){
  39290. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  39291. PgHdr *pPageOne = 0;
  39292. if( pList==0 ){
  39293. /* Must have at least one page for the WAL commit flag.
  39294. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  39295. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  39296. pList = pPageOne;
  39297. pList->pDirty = 0;
  39298. }
  39299. assert( pList!=0 || rc!=SQLITE_OK );
  39300. if( pList ){
  39301. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
  39302. (pPager->fullSync ? pPager->syncFlags : 0)
  39303. );
  39304. }
  39305. sqlite3PagerUnref(pPageOne);
  39306. if( rc==SQLITE_OK ){
  39307. sqlite3PcacheCleanAll(pPager->pPCache);
  39308. }
  39309. }else{
  39310. /* The following block updates the change-counter. Exactly how it
  39311. ** does this depends on whether or not the atomic-update optimization
  39312. ** was enabled at compile time, and if this transaction meets the
  39313. ** runtime criteria to use the operation:
  39314. **
  39315. ** * The file-system supports the atomic-write property for
  39316. ** blocks of size page-size, and
  39317. ** * This commit is not part of a multi-file transaction, and
  39318. ** * Exactly one page has been modified and store in the journal file.
  39319. **
  39320. ** If the optimization was not enabled at compile time, then the
  39321. ** pager_incr_changecounter() function is called to update the change
  39322. ** counter in 'indirect-mode'. If the optimization is compiled in but
  39323. ** is not applicable to this transaction, call sqlite3JournalCreate()
  39324. ** to make sure the journal file has actually been created, then call
  39325. ** pager_incr_changecounter() to update the change-counter in indirect
  39326. ** mode.
  39327. **
  39328. ** Otherwise, if the optimization is both enabled and applicable,
  39329. ** then call pager_incr_changecounter() to update the change-counter
  39330. ** in 'direct' mode. In this case the journal file will never be
  39331. ** created for this transaction.
  39332. */
  39333. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  39334. PgHdr *pPg;
  39335. assert( isOpen(pPager->jfd)
  39336. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  39337. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  39338. );
  39339. if( !zMaster && isOpen(pPager->jfd)
  39340. && pPager->journalOff==jrnlBufferSize(pPager)
  39341. && pPager->dbSize>=pPager->dbOrigSize
  39342. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  39343. ){
  39344. /* Update the db file change counter via the direct-write method. The
  39345. ** following call will modify the in-memory representation of page 1
  39346. ** to include the updated change counter and then write page 1
  39347. ** directly to the database file. Because of the atomic-write
  39348. ** property of the host file-system, this is safe.
  39349. */
  39350. rc = pager_incr_changecounter(pPager, 1);
  39351. }else{
  39352. rc = sqlite3JournalCreate(pPager->jfd);
  39353. if( rc==SQLITE_OK ){
  39354. rc = pager_incr_changecounter(pPager, 0);
  39355. }
  39356. }
  39357. #else
  39358. rc = pager_incr_changecounter(pPager, 0);
  39359. #endif
  39360. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  39361. /* If this transaction has made the database smaller, then all pages
  39362. ** being discarded by the truncation must be written to the journal
  39363. ** file. This can only happen in auto-vacuum mode.
  39364. **
  39365. ** Before reading the pages with page numbers larger than the
  39366. ** current value of Pager.dbSize, set dbSize back to the value
  39367. ** that it took at the start of the transaction. Otherwise, the
  39368. ** calls to sqlite3PagerGet() return zeroed pages instead of
  39369. ** reading data from the database file.
  39370. */
  39371. #ifndef SQLITE_OMIT_AUTOVACUUM
  39372. if( pPager->dbSize<pPager->dbOrigSize
  39373. && pPager->journalMode!=PAGER_JOURNALMODE_OFF
  39374. ){
  39375. Pgno i; /* Iterator variable */
  39376. const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
  39377. const Pgno dbSize = pPager->dbSize; /* Database image size */
  39378. pPager->dbSize = pPager->dbOrigSize;
  39379. for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
  39380. if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
  39381. PgHdr *pPage; /* Page to journal */
  39382. rc = sqlite3PagerGet(pPager, i, &pPage);
  39383. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  39384. rc = sqlite3PagerWrite(pPage);
  39385. sqlite3PagerUnref(pPage);
  39386. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  39387. }
  39388. }
  39389. pPager->dbSize = dbSize;
  39390. }
  39391. #endif
  39392. /* Write the master journal name into the journal file. If a master
  39393. ** journal file name has already been written to the journal file,
  39394. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  39395. */
  39396. rc = writeMasterJournal(pPager, zMaster);
  39397. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  39398. /* Sync the journal file and write all dirty pages to the database.
  39399. ** If the atomic-update optimization is being used, this sync will not
  39400. ** create the journal file or perform any real IO.
  39401. **
  39402. ** Because the change-counter page was just modified, unless the
  39403. ** atomic-update optimization is used it is almost certain that the
  39404. ** journal requires a sync here. However, in locking_mode=exclusive
  39405. ** on a system under memory pressure it is just possible that this is
  39406. ** not the case. In this case it is likely enough that the redundant
  39407. ** xSync() call will be changed to a no-op by the OS anyhow.
  39408. */
  39409. rc = syncJournal(pPager, 0);
  39410. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  39411. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  39412. if( rc!=SQLITE_OK ){
  39413. assert( rc!=SQLITE_IOERR_BLOCKED );
  39414. goto commit_phase_one_exit;
  39415. }
  39416. sqlite3PcacheCleanAll(pPager->pPCache);
  39417. /* If the file on disk is not the same size as the database image,
  39418. ** then use pager_truncate to grow or shrink the file here.
  39419. */
  39420. if( pPager->dbSize!=pPager->dbFileSize ){
  39421. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  39422. assert( pPager->eState==PAGER_WRITER_DBMOD );
  39423. rc = pager_truncate(pPager, nNew);
  39424. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  39425. }
  39426. /* Finally, sync the database file. */
  39427. if( !noSync ){
  39428. rc = sqlite3PagerSync(pPager);
  39429. }
  39430. IOTRACE(("DBSYNC %p\n", pPager))
  39431. }
  39432. }
  39433. commit_phase_one_exit:
  39434. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  39435. pPager->eState = PAGER_WRITER_FINISHED;
  39436. }
  39437. return rc;
  39438. }
  39439. /*
  39440. ** When this function is called, the database file has been completely
  39441. ** updated to reflect the changes made by the current transaction and
  39442. ** synced to disk. The journal file still exists in the file-system
  39443. ** though, and if a failure occurs at this point it will eventually
  39444. ** be used as a hot-journal and the current transaction rolled back.
  39445. **
  39446. ** This function finalizes the journal file, either by deleting,
  39447. ** truncating or partially zeroing it, so that it cannot be used
  39448. ** for hot-journal rollback. Once this is done the transaction is
  39449. ** irrevocably committed.
  39450. **
  39451. ** If an error occurs, an IO error code is returned and the pager
  39452. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  39453. */
  39454. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  39455. int rc = SQLITE_OK; /* Return code */
  39456. /* This routine should not be called if a prior error has occurred.
  39457. ** But if (due to a coding error elsewhere in the system) it does get
  39458. ** called, just return the same error code without doing anything. */
  39459. if( NEVER(pPager->errCode) ) return pPager->errCode;
  39460. assert( pPager->eState==PAGER_WRITER_LOCKED
  39461. || pPager->eState==PAGER_WRITER_FINISHED
  39462. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  39463. );
  39464. assert( assert_pager_state(pPager) );
  39465. /* An optimization. If the database was not actually modified during
  39466. ** this transaction, the pager is running in exclusive-mode and is
  39467. ** using persistent journals, then this function is a no-op.
  39468. **
  39469. ** The start of the journal file currently contains a single journal
  39470. ** header with the nRec field set to 0. If such a journal is used as
  39471. ** a hot-journal during hot-journal rollback, 0 changes will be made
  39472. ** to the database file. So there is no need to zero the journal
  39473. ** header. Since the pager is in exclusive mode, there is no need
  39474. ** to drop any locks either.
  39475. */
  39476. if( pPager->eState==PAGER_WRITER_LOCKED
  39477. && pPager->exclusiveMode
  39478. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  39479. ){
  39480. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  39481. pPager->eState = PAGER_READER;
  39482. return SQLITE_OK;
  39483. }
  39484. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  39485. rc = pager_end_transaction(pPager, pPager->setMaster);
  39486. return pager_error(pPager, rc);
  39487. }
  39488. /*
  39489. ** If a write transaction is open, then all changes made within the
  39490. ** transaction are reverted and the current write-transaction is closed.
  39491. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  39492. ** state if an error occurs.
  39493. **
  39494. ** If the pager is already in PAGER_ERROR state when this function is called,
  39495. ** it returns Pager.errCode immediately. No work is performed in this case.
  39496. **
  39497. ** Otherwise, in rollback mode, this function performs two functions:
  39498. **
  39499. ** 1) It rolls back the journal file, restoring all database file and
  39500. ** in-memory cache pages to the state they were in when the transaction
  39501. ** was opened, and
  39502. **
  39503. ** 2) It finalizes the journal file, so that it is not used for hot
  39504. ** rollback at any point in the future.
  39505. **
  39506. ** Finalization of the journal file (task 2) is only performed if the
  39507. ** rollback is successful.
  39508. **
  39509. ** In WAL mode, all cache-entries containing data modified within the
  39510. ** current transaction are either expelled from the cache or reverted to
  39511. ** their pre-transaction state by re-reading data from the database or
  39512. ** WAL files. The WAL transaction is then closed.
  39513. */
  39514. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  39515. int rc = SQLITE_OK; /* Return code */
  39516. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  39517. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  39518. ** the pager is already in the ERROR state, the rollback is not
  39519. ** attempted here. Instead, the error code is returned to the caller.
  39520. */
  39521. assert( assert_pager_state(pPager) );
  39522. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  39523. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  39524. if( pagerUseWal(pPager) ){
  39525. int rc2;
  39526. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  39527. rc2 = pager_end_transaction(pPager, pPager->setMaster);
  39528. if( rc==SQLITE_OK ) rc = rc2;
  39529. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  39530. int eState = pPager->eState;
  39531. rc = pager_end_transaction(pPager, 0);
  39532. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  39533. /* This can happen using journal_mode=off. Move the pager to the error
  39534. ** state to indicate that the contents of the cache may not be trusted.
  39535. ** Any active readers will get SQLITE_ABORT.
  39536. */
  39537. pPager->errCode = SQLITE_ABORT;
  39538. pPager->eState = PAGER_ERROR;
  39539. return rc;
  39540. }
  39541. }else{
  39542. rc = pager_playback(pPager, 0);
  39543. }
  39544. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  39545. assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
  39546. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  39547. ** cache. So call pager_error() on the way out to make any error persistent.
  39548. */
  39549. return pager_error(pPager, rc);
  39550. }
  39551. /*
  39552. ** Return TRUE if the database file is opened read-only. Return FALSE
  39553. ** if the database is (in theory) writable.
  39554. */
  39555. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  39556. return pPager->readOnly;
  39557. }
  39558. /*
  39559. ** Return the number of references to the pager.
  39560. */
  39561. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  39562. return sqlite3PcacheRefCount(pPager->pPCache);
  39563. }
  39564. /*
  39565. ** Return the approximate number of bytes of memory currently
  39566. ** used by the pager and its associated cache.
  39567. */
  39568. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  39569. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  39570. + 5*sizeof(void*);
  39571. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  39572. + sqlite3MallocSize(pPager)
  39573. + pPager->pageSize;
  39574. }
  39575. /*
  39576. ** Return the number of references to the specified page.
  39577. */
  39578. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  39579. return sqlite3PcachePageRefcount(pPage);
  39580. }
  39581. #ifdef SQLITE_TEST
  39582. /*
  39583. ** This routine is used for testing and analysis only.
  39584. */
  39585. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  39586. static int a[11];
  39587. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  39588. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  39589. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  39590. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  39591. a[4] = pPager->eState;
  39592. a[5] = pPager->errCode;
  39593. a[6] = pPager->nHit;
  39594. a[7] = pPager->nMiss;
  39595. a[8] = 0; /* Used to be pPager->nOvfl */
  39596. a[9] = pPager->nRead;
  39597. a[10] = pPager->nWrite;
  39598. return a;
  39599. }
  39600. #endif
  39601. /*
  39602. ** Return true if this is an in-memory pager.
  39603. */
  39604. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  39605. return MEMDB;
  39606. }
  39607. /*
  39608. ** Check that there are at least nSavepoint savepoints open. If there are
  39609. ** currently less than nSavepoints open, then open one or more savepoints
  39610. ** to make up the difference. If the number of savepoints is already
  39611. ** equal to nSavepoint, then this function is a no-op.
  39612. **
  39613. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  39614. ** occurs while opening the sub-journal file, then an IO error code is
  39615. ** returned. Otherwise, SQLITE_OK.
  39616. */
  39617. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  39618. int rc = SQLITE_OK; /* Return code */
  39619. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  39620. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  39621. assert( assert_pager_state(pPager) );
  39622. if( nSavepoint>nCurrent && pPager->useJournal ){
  39623. int ii; /* Iterator variable */
  39624. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  39625. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  39626. ** if the allocation fails. Otherwise, zero the new portion in case a
  39627. ** malloc failure occurs while populating it in the for(...) loop below.
  39628. */
  39629. aNew = (PagerSavepoint *)sqlite3Realloc(
  39630. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  39631. );
  39632. if( !aNew ){
  39633. return SQLITE_NOMEM;
  39634. }
  39635. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  39636. pPager->aSavepoint = aNew;
  39637. /* Populate the PagerSavepoint structures just allocated. */
  39638. for(ii=nCurrent; ii<nSavepoint; ii++){
  39639. aNew[ii].nOrig = pPager->dbSize;
  39640. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  39641. aNew[ii].iOffset = pPager->journalOff;
  39642. }else{
  39643. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  39644. }
  39645. aNew[ii].iSubRec = pPager->nSubRec;
  39646. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  39647. if( !aNew[ii].pInSavepoint ){
  39648. return SQLITE_NOMEM;
  39649. }
  39650. if( pagerUseWal(pPager) ){
  39651. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  39652. }
  39653. pPager->nSavepoint = ii+1;
  39654. }
  39655. assert( pPager->nSavepoint==nSavepoint );
  39656. assertTruncateConstraint(pPager);
  39657. }
  39658. return rc;
  39659. }
  39660. /*
  39661. ** This function is called to rollback or release (commit) a savepoint.
  39662. ** The savepoint to release or rollback need not be the most recently
  39663. ** created savepoint.
  39664. **
  39665. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  39666. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  39667. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  39668. ** that have occurred since the specified savepoint was created.
  39669. **
  39670. ** The savepoint to rollback or release is identified by parameter
  39671. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  39672. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  39673. ** on the most recently created savepoint. If iSavepoint is greater than
  39674. ** (Pager.nSavepoint-1), then this function is a no-op.
  39675. **
  39676. ** If a negative value is passed to this function, then the current
  39677. ** transaction is rolled back. This is different to calling
  39678. ** sqlite3PagerRollback() because this function does not terminate
  39679. ** the transaction or unlock the database, it just restores the
  39680. ** contents of the database to its original state.
  39681. **
  39682. ** In any case, all savepoints with an index greater than iSavepoint
  39683. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  39684. ** then savepoint iSavepoint is also destroyed.
  39685. **
  39686. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  39687. ** or an IO error code if an IO error occurs while rolling back a
  39688. ** savepoint. If no errors occur, SQLITE_OK is returned.
  39689. */
  39690. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  39691. int rc = pPager->errCode; /* Return code */
  39692. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  39693. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  39694. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  39695. int ii; /* Iterator variable */
  39696. int nNew; /* Number of remaining savepoints after this op. */
  39697. /* Figure out how many savepoints will still be active after this
  39698. ** operation. Store this value in nNew. Then free resources associated
  39699. ** with any savepoints that are destroyed by this operation.
  39700. */
  39701. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  39702. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  39703. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  39704. }
  39705. pPager->nSavepoint = nNew;
  39706. /* If this is a release of the outermost savepoint, truncate
  39707. ** the sub-journal to zero bytes in size. */
  39708. if( op==SAVEPOINT_RELEASE ){
  39709. if( nNew==0 && isOpen(pPager->sjfd) ){
  39710. /* Only truncate if it is an in-memory sub-journal. */
  39711. if( sqlite3IsMemJournal(pPager->sjfd) ){
  39712. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  39713. assert( rc==SQLITE_OK );
  39714. }
  39715. pPager->nSubRec = 0;
  39716. }
  39717. }
  39718. /* Else this is a rollback operation, playback the specified savepoint.
  39719. ** If this is a temp-file, it is possible that the journal file has
  39720. ** not yet been opened. In this case there have been no changes to
  39721. ** the database file, so the playback operation can be skipped.
  39722. */
  39723. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  39724. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  39725. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  39726. assert(rc!=SQLITE_DONE);
  39727. }
  39728. }
  39729. return rc;
  39730. }
  39731. /*
  39732. ** Return the full pathname of the database file.
  39733. */
  39734. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
  39735. return pPager->zFilename;
  39736. }
  39737. /*
  39738. ** Return the VFS structure for the pager.
  39739. */
  39740. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  39741. return pPager->pVfs;
  39742. }
  39743. /*
  39744. ** Return the file handle for the database file associated
  39745. ** with the pager. This might return NULL if the file has
  39746. ** not yet been opened.
  39747. */
  39748. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  39749. return pPager->fd;
  39750. }
  39751. /*
  39752. ** Return the full pathname of the journal file.
  39753. */
  39754. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  39755. return pPager->zJournal;
  39756. }
  39757. /*
  39758. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  39759. ** if fsync()s are executed normally.
  39760. */
  39761. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  39762. return pPager->noSync;
  39763. }
  39764. #ifdef SQLITE_HAS_CODEC
  39765. /*
  39766. ** Set or retrieve the codec for this pager
  39767. */
  39768. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  39769. Pager *pPager,
  39770. void *(*xCodec)(void*,void*,Pgno,int),
  39771. void (*xCodecSizeChng)(void*,int,int),
  39772. void (*xCodecFree)(void*),
  39773. void *pCodec
  39774. ){
  39775. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  39776. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  39777. pPager->xCodecSizeChng = xCodecSizeChng;
  39778. pPager->xCodecFree = xCodecFree;
  39779. pPager->pCodec = pCodec;
  39780. pagerReportSize(pPager);
  39781. }
  39782. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  39783. return pPager->pCodec;
  39784. }
  39785. #endif
  39786. #ifndef SQLITE_OMIT_AUTOVACUUM
  39787. /*
  39788. ** Move the page pPg to location pgno in the file.
  39789. **
  39790. ** There must be no references to the page previously located at
  39791. ** pgno (which we call pPgOld) though that page is allowed to be
  39792. ** in cache. If the page previously located at pgno is not already
  39793. ** in the rollback journal, it is not put there by by this routine.
  39794. **
  39795. ** References to the page pPg remain valid. Updating any
  39796. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  39797. ** allocated along with the page) is the responsibility of the caller.
  39798. **
  39799. ** A transaction must be active when this routine is called. It used to be
  39800. ** required that a statement transaction was not active, but this restriction
  39801. ** has been removed (CREATE INDEX needs to move a page when a statement
  39802. ** transaction is active).
  39803. **
  39804. ** If the fourth argument, isCommit, is non-zero, then this page is being
  39805. ** moved as part of a database reorganization just before the transaction
  39806. ** is being committed. In this case, it is guaranteed that the database page
  39807. ** pPg refers to will not be written to again within this transaction.
  39808. **
  39809. ** This function may return SQLITE_NOMEM or an IO error code if an error
  39810. ** occurs. Otherwise, it returns SQLITE_OK.
  39811. */
  39812. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  39813. PgHdr *pPgOld; /* The page being overwritten. */
  39814. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  39815. int rc; /* Return code */
  39816. Pgno origPgno; /* The original page number */
  39817. assert( pPg->nRef>0 );
  39818. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  39819. || pPager->eState==PAGER_WRITER_DBMOD
  39820. );
  39821. assert( assert_pager_state(pPager) );
  39822. /* In order to be able to rollback, an in-memory database must journal
  39823. ** the page we are moving from.
  39824. */
  39825. if( MEMDB ){
  39826. rc = sqlite3PagerWrite(pPg);
  39827. if( rc ) return rc;
  39828. }
  39829. /* If the page being moved is dirty and has not been saved by the latest
  39830. ** savepoint, then save the current contents of the page into the
  39831. ** sub-journal now. This is required to handle the following scenario:
  39832. **
  39833. ** BEGIN;
  39834. ** <journal page X, then modify it in memory>
  39835. ** SAVEPOINT one;
  39836. ** <Move page X to location Y>
  39837. ** ROLLBACK TO one;
  39838. **
  39839. ** If page X were not written to the sub-journal here, it would not
  39840. ** be possible to restore its contents when the "ROLLBACK TO one"
  39841. ** statement were is processed.
  39842. **
  39843. ** subjournalPage() may need to allocate space to store pPg->pgno into
  39844. ** one or more savepoint bitvecs. This is the reason this function
  39845. ** may return SQLITE_NOMEM.
  39846. */
  39847. if( pPg->flags&PGHDR_DIRTY
  39848. && subjRequiresPage(pPg)
  39849. && SQLITE_OK!=(rc = subjournalPage(pPg))
  39850. ){
  39851. return rc;
  39852. }
  39853. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  39854. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  39855. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  39856. /* If the journal needs to be sync()ed before page pPg->pgno can
  39857. ** be written to, store pPg->pgno in local variable needSyncPgno.
  39858. **
  39859. ** If the isCommit flag is set, there is no need to remember that
  39860. ** the journal needs to be sync()ed before database page pPg->pgno
  39861. ** can be written to. The caller has already promised not to write to it.
  39862. */
  39863. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  39864. needSyncPgno = pPg->pgno;
  39865. assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  39866. assert( pPg->flags&PGHDR_DIRTY );
  39867. }
  39868. /* If the cache contains a page with page-number pgno, remove it
  39869. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  39870. ** page pgno before the 'move' operation, it needs to be retained
  39871. ** for the page moved there.
  39872. */
  39873. pPg->flags &= ~PGHDR_NEED_SYNC;
  39874. pPgOld = pager_lookup(pPager, pgno);
  39875. assert( !pPgOld || pPgOld->nRef==1 );
  39876. if( pPgOld ){
  39877. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  39878. if( MEMDB ){
  39879. /* Do not discard pages from an in-memory database since we might
  39880. ** need to rollback later. Just move the page out of the way. */
  39881. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  39882. }else{
  39883. sqlite3PcacheDrop(pPgOld);
  39884. }
  39885. }
  39886. origPgno = pPg->pgno;
  39887. sqlite3PcacheMove(pPg, pgno);
  39888. sqlite3PcacheMakeDirty(pPg);
  39889. /* For an in-memory database, make sure the original page continues
  39890. ** to exist, in case the transaction needs to roll back. Use pPgOld
  39891. ** as the original page since it has already been allocated.
  39892. */
  39893. if( MEMDB ){
  39894. assert( pPgOld );
  39895. sqlite3PcacheMove(pPgOld, origPgno);
  39896. sqlite3PagerUnref(pPgOld);
  39897. }
  39898. if( needSyncPgno ){
  39899. /* If needSyncPgno is non-zero, then the journal file needs to be
  39900. ** sync()ed before any data is written to database file page needSyncPgno.
  39901. ** Currently, no such page exists in the page-cache and the
  39902. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  39903. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  39904. ** flag.
  39905. **
  39906. ** If the attempt to load the page into the page-cache fails, (due
  39907. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  39908. ** array. Otherwise, if the page is loaded and written again in
  39909. ** this transaction, it may be written to the database file before
  39910. ** it is synced into the journal file. This way, it may end up in
  39911. ** the journal file twice, but that is not a problem.
  39912. */
  39913. PgHdr *pPgHdr;
  39914. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  39915. if( rc!=SQLITE_OK ){
  39916. if( needSyncPgno<=pPager->dbOrigSize ){
  39917. assert( pPager->pTmpSpace!=0 );
  39918. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  39919. }
  39920. return rc;
  39921. }
  39922. pPgHdr->flags |= PGHDR_NEED_SYNC;
  39923. sqlite3PcacheMakeDirty(pPgHdr);
  39924. sqlite3PagerUnref(pPgHdr);
  39925. }
  39926. return SQLITE_OK;
  39927. }
  39928. #endif
  39929. /*
  39930. ** Return a pointer to the data for the specified page.
  39931. */
  39932. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  39933. assert( pPg->nRef>0 || pPg->pPager->memDb );
  39934. return pPg->pData;
  39935. }
  39936. /*
  39937. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  39938. ** allocated along with the specified page.
  39939. */
  39940. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  39941. return pPg->pExtra;
  39942. }
  39943. /*
  39944. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  39945. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  39946. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  39947. ** the locking-mode is set to the value specified.
  39948. **
  39949. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  39950. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  39951. ** locking-mode.
  39952. */
  39953. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  39954. assert( eMode==PAGER_LOCKINGMODE_QUERY
  39955. || eMode==PAGER_LOCKINGMODE_NORMAL
  39956. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  39957. assert( PAGER_LOCKINGMODE_QUERY<0 );
  39958. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  39959. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  39960. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  39961. pPager->exclusiveMode = (u8)eMode;
  39962. }
  39963. return (int)pPager->exclusiveMode;
  39964. }
  39965. /*
  39966. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  39967. **
  39968. ** PAGER_JOURNALMODE_DELETE
  39969. ** PAGER_JOURNALMODE_TRUNCATE
  39970. ** PAGER_JOURNALMODE_PERSIST
  39971. ** PAGER_JOURNALMODE_OFF
  39972. ** PAGER_JOURNALMODE_MEMORY
  39973. ** PAGER_JOURNALMODE_WAL
  39974. **
  39975. ** The journalmode is set to the value specified if the change is allowed.
  39976. ** The change may be disallowed for the following reasons:
  39977. **
  39978. ** * An in-memory database can only have its journal_mode set to _OFF
  39979. ** or _MEMORY.
  39980. **
  39981. ** * Temporary databases cannot have _WAL journalmode.
  39982. **
  39983. ** The returned indicate the current (possibly updated) journal-mode.
  39984. */
  39985. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  39986. u8 eOld = pPager->journalMode; /* Prior journalmode */
  39987. #ifdef SQLITE_DEBUG
  39988. /* The print_pager_state() routine is intended to be used by the debugger
  39989. ** only. We invoke it once here to suppress a compiler warning. */
  39990. print_pager_state(pPager);
  39991. #endif
  39992. /* The eMode parameter is always valid */
  39993. assert( eMode==PAGER_JOURNALMODE_DELETE
  39994. || eMode==PAGER_JOURNALMODE_TRUNCATE
  39995. || eMode==PAGER_JOURNALMODE_PERSIST
  39996. || eMode==PAGER_JOURNALMODE_OFF
  39997. || eMode==PAGER_JOURNALMODE_WAL
  39998. || eMode==PAGER_JOURNALMODE_MEMORY );
  39999. /* This routine is only called from the OP_JournalMode opcode, and
  40000. ** the logic there will never allow a temporary file to be changed
  40001. ** to WAL mode.
  40002. */
  40003. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  40004. /* Do allow the journalmode of an in-memory database to be set to
  40005. ** anything other than MEMORY or OFF
  40006. */
  40007. if( MEMDB ){
  40008. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  40009. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  40010. eMode = eOld;
  40011. }
  40012. }
  40013. if( eMode!=eOld ){
  40014. /* Change the journal mode. */
  40015. assert( pPager->eState!=PAGER_ERROR );
  40016. pPager->journalMode = (u8)eMode;
  40017. /* When transistioning from TRUNCATE or PERSIST to any other journal
  40018. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  40019. ** delete the journal file.
  40020. */
  40021. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  40022. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  40023. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  40024. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  40025. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  40026. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  40027. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  40028. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  40029. /* In this case we would like to delete the journal file. If it is
  40030. ** not possible, then that is not a problem. Deleting the journal file
  40031. ** here is an optimization only.
  40032. **
  40033. ** Before deleting the journal file, obtain a RESERVED lock on the
  40034. ** database file. This ensures that the journal file is not deleted
  40035. ** while it is in use by some other client.
  40036. */
  40037. sqlite3OsClose(pPager->jfd);
  40038. if( pPager->eLock>=RESERVED_LOCK ){
  40039. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  40040. }else{
  40041. int rc = SQLITE_OK;
  40042. int state = pPager->eState;
  40043. assert( state==PAGER_OPEN || state==PAGER_READER );
  40044. if( state==PAGER_OPEN ){
  40045. rc = sqlite3PagerSharedLock(pPager);
  40046. }
  40047. if( pPager->eState==PAGER_READER ){
  40048. assert( rc==SQLITE_OK );
  40049. rc = pagerLockDb(pPager, RESERVED_LOCK);
  40050. }
  40051. if( rc==SQLITE_OK ){
  40052. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  40053. }
  40054. if( rc==SQLITE_OK && state==PAGER_READER ){
  40055. pagerUnlockDb(pPager, SHARED_LOCK);
  40056. }else if( state==PAGER_OPEN ){
  40057. pager_unlock(pPager);
  40058. }
  40059. assert( state==pPager->eState );
  40060. }
  40061. }
  40062. }
  40063. /* Return the new journal mode */
  40064. return (int)pPager->journalMode;
  40065. }
  40066. /*
  40067. ** Return the current journal mode.
  40068. */
  40069. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  40070. return (int)pPager->journalMode;
  40071. }
  40072. /*
  40073. ** Return TRUE if the pager is in a state where it is OK to change the
  40074. ** journalmode. Journalmode changes can only happen when the database
  40075. ** is unmodified.
  40076. */
  40077. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  40078. assert( assert_pager_state(pPager) );
  40079. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  40080. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  40081. return 1;
  40082. }
  40083. /*
  40084. ** Get/set the size-limit used for persistent journal files.
  40085. **
  40086. ** Setting the size limit to -1 means no limit is enforced.
  40087. ** An attempt to set a limit smaller than -1 is a no-op.
  40088. */
  40089. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  40090. if( iLimit>=-1 ){
  40091. pPager->journalSizeLimit = iLimit;
  40092. }
  40093. return pPager->journalSizeLimit;
  40094. }
  40095. /*
  40096. ** Return a pointer to the pPager->pBackup variable. The backup module
  40097. ** in backup.c maintains the content of this variable. This module
  40098. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  40099. ** sqlite3BackupUpdate() only.
  40100. */
  40101. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  40102. return &pPager->pBackup;
  40103. }
  40104. #ifndef SQLITE_OMIT_WAL
  40105. /*
  40106. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  40107. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  40108. ** or wal_blocking_checkpoint() API functions.
  40109. **
  40110. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  40111. */
  40112. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  40113. int rc = SQLITE_OK;
  40114. if( pPager->pWal ){
  40115. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  40116. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  40117. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  40118. pnLog, pnCkpt
  40119. );
  40120. }
  40121. return rc;
  40122. }
  40123. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  40124. return sqlite3WalCallback(pPager->pWal);
  40125. }
  40126. /*
  40127. ** Return true if the underlying VFS for the given pager supports the
  40128. ** primitives necessary for write-ahead logging.
  40129. */
  40130. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  40131. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  40132. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  40133. }
  40134. /*
  40135. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  40136. ** is obtained instead, immediately release it.
  40137. */
  40138. static int pagerExclusiveLock(Pager *pPager){
  40139. int rc; /* Return code */
  40140. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  40141. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  40142. if( rc!=SQLITE_OK ){
  40143. /* If the attempt to grab the exclusive lock failed, release the
  40144. ** pending lock that may have been obtained instead. */
  40145. pagerUnlockDb(pPager, SHARED_LOCK);
  40146. }
  40147. return rc;
  40148. }
  40149. /*
  40150. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  40151. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  40152. ** lock on the database file and use heap-memory to store the wal-index
  40153. ** in. Otherwise, use the normal shared-memory.
  40154. */
  40155. static int pagerOpenWal(Pager *pPager){
  40156. int rc = SQLITE_OK;
  40157. assert( pPager->pWal==0 && pPager->tempFile==0 );
  40158. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
  40159. /* If the pager is already in exclusive-mode, the WAL module will use
  40160. ** heap-memory for the wal-index instead of the VFS shared-memory
  40161. ** implementation. Take the exclusive lock now, before opening the WAL
  40162. ** file, to make sure this is safe.
  40163. */
  40164. if( pPager->exclusiveMode ){
  40165. rc = pagerExclusiveLock(pPager);
  40166. }
  40167. /* Open the connection to the log file. If this operation fails,
  40168. ** (e.g. due to malloc() failure), return an error code.
  40169. */
  40170. if( rc==SQLITE_OK ){
  40171. rc = sqlite3WalOpen(pPager->pVfs,
  40172. pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
  40173. );
  40174. }
  40175. return rc;
  40176. }
  40177. /*
  40178. ** The caller must be holding a SHARED lock on the database file to call
  40179. ** this function.
  40180. **
  40181. ** If the pager passed as the first argument is open on a real database
  40182. ** file (not a temp file or an in-memory database), and the WAL file
  40183. ** is not already open, make an attempt to open it now. If successful,
  40184. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  40185. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  40186. ** not modified in either case.
  40187. **
  40188. ** If the pager is open on a temp-file (or in-memory database), or if
  40189. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  40190. ** without doing anything.
  40191. */
  40192. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  40193. Pager *pPager, /* Pager object */
  40194. int *pbOpen /* OUT: Set to true if call is a no-op */
  40195. ){
  40196. int rc = SQLITE_OK; /* Return code */
  40197. assert( assert_pager_state(pPager) );
  40198. assert( pPager->eState==PAGER_OPEN || pbOpen );
  40199. assert( pPager->eState==PAGER_READER || !pbOpen );
  40200. assert( pbOpen==0 || *pbOpen==0 );
  40201. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  40202. if( !pPager->tempFile && !pPager->pWal ){
  40203. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  40204. /* Close any rollback journal previously open */
  40205. sqlite3OsClose(pPager->jfd);
  40206. rc = pagerOpenWal(pPager);
  40207. if( rc==SQLITE_OK ){
  40208. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  40209. pPager->eState = PAGER_OPEN;
  40210. }
  40211. }else{
  40212. *pbOpen = 1;
  40213. }
  40214. return rc;
  40215. }
  40216. /*
  40217. ** This function is called to close the connection to the log file prior
  40218. ** to switching from WAL to rollback mode.
  40219. **
  40220. ** Before closing the log file, this function attempts to take an
  40221. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  40222. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  40223. ** If successful, the EXCLUSIVE lock is not released before returning.
  40224. */
  40225. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  40226. int rc = SQLITE_OK;
  40227. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  40228. /* If the log file is not already open, but does exist in the file-system,
  40229. ** it may need to be checkpointed before the connection can switch to
  40230. ** rollback mode. Open it now so this can happen.
  40231. */
  40232. if( !pPager->pWal ){
  40233. int logexists = 0;
  40234. rc = pagerLockDb(pPager, SHARED_LOCK);
  40235. if( rc==SQLITE_OK ){
  40236. rc = sqlite3OsAccess(
  40237. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  40238. );
  40239. }
  40240. if( rc==SQLITE_OK && logexists ){
  40241. rc = pagerOpenWal(pPager);
  40242. }
  40243. }
  40244. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  40245. ** the database file, the log and log-summary files will be deleted.
  40246. */
  40247. if( rc==SQLITE_OK && pPager->pWal ){
  40248. rc = pagerExclusiveLock(pPager);
  40249. if( rc==SQLITE_OK ){
  40250. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  40251. pPager->pageSize, (u8*)pPager->pTmpSpace);
  40252. pPager->pWal = 0;
  40253. }
  40254. }
  40255. return rc;
  40256. }
  40257. #ifdef SQLITE_HAS_CODEC
  40258. /*
  40259. ** This function is called by the wal module when writing page content
  40260. ** into the log file.
  40261. **
  40262. ** This function returns a pointer to a buffer containing the encrypted
  40263. ** page content. If a malloc fails, this function may return NULL.
  40264. */
  40265. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  40266. void *aData = 0;
  40267. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  40268. return aData;
  40269. }
  40270. #endif /* SQLITE_HAS_CODEC */
  40271. #endif /* !SQLITE_OMIT_WAL */
  40272. #endif /* SQLITE_OMIT_DISKIO */
  40273. /************** End of pager.c ***********************************************/
  40274. /************** Begin file wal.c *********************************************/
  40275. /*
  40276. ** 2010 February 1
  40277. **
  40278. ** The author disclaims copyright to this source code. In place of
  40279. ** a legal notice, here is a blessing:
  40280. **
  40281. ** May you do good and not evil.
  40282. ** May you find forgiveness for yourself and forgive others.
  40283. ** May you share freely, never taking more than you give.
  40284. **
  40285. *************************************************************************
  40286. **
  40287. ** This file contains the implementation of a write-ahead log (WAL) used in
  40288. ** "journal_mode=WAL" mode.
  40289. **
  40290. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  40291. **
  40292. ** A WAL file consists of a header followed by zero or more "frames".
  40293. ** Each frame records the revised content of a single page from the
  40294. ** database file. All changes to the database are recorded by writing
  40295. ** frames into the WAL. Transactions commit when a frame is written that
  40296. ** contains a commit marker. A single WAL can and usually does record
  40297. ** multiple transactions. Periodically, the content of the WAL is
  40298. ** transferred back into the database file in an operation called a
  40299. ** "checkpoint".
  40300. **
  40301. ** A single WAL file can be used multiple times. In other words, the
  40302. ** WAL can fill up with frames and then be checkpointed and then new
  40303. ** frames can overwrite the old ones. A WAL always grows from beginning
  40304. ** toward the end. Checksums and counters attached to each frame are
  40305. ** used to determine which frames within the WAL are valid and which
  40306. ** are leftovers from prior checkpoints.
  40307. **
  40308. ** The WAL header is 32 bytes in size and consists of the following eight
  40309. ** big-endian 32-bit unsigned integer values:
  40310. **
  40311. ** 0: Magic number. 0x377f0682 or 0x377f0683
  40312. ** 4: File format version. Currently 3007000
  40313. ** 8: Database page size. Example: 1024
  40314. ** 12: Checkpoint sequence number
  40315. ** 16: Salt-1, random integer incremented with each checkpoint
  40316. ** 20: Salt-2, a different random integer changing with each ckpt
  40317. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  40318. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  40319. **
  40320. ** Immediately following the wal-header are zero or more frames. Each
  40321. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  40322. ** of page data. The frame-header is six big-endian 32-bit unsigned
  40323. ** integer values, as follows:
  40324. **
  40325. ** 0: Page number.
  40326. ** 4: For commit records, the size of the database image in pages
  40327. ** after the commit. For all other records, zero.
  40328. ** 8: Salt-1 (copied from the header)
  40329. ** 12: Salt-2 (copied from the header)
  40330. ** 16: Checksum-1.
  40331. ** 20: Checksum-2.
  40332. **
  40333. ** A frame is considered valid if and only if the following conditions are
  40334. ** true:
  40335. **
  40336. ** (1) The salt-1 and salt-2 values in the frame-header match
  40337. ** salt values in the wal-header
  40338. **
  40339. ** (2) The checksum values in the final 8 bytes of the frame-header
  40340. ** exactly match the checksum computed consecutively on the
  40341. ** WAL header and the first 8 bytes and the content of all frames
  40342. ** up to and including the current frame.
  40343. **
  40344. ** The checksum is computed using 32-bit big-endian integers if the
  40345. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  40346. ** is computed using little-endian if the magic number is 0x377f0682.
  40347. ** The checksum values are always stored in the frame header in a
  40348. ** big-endian format regardless of which byte order is used to compute
  40349. ** the checksum. The checksum is computed by interpreting the input as
  40350. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  40351. ** algorithm used for the checksum is as follows:
  40352. **
  40353. ** for i from 0 to n-1 step 2:
  40354. ** s0 += x[i] + s1;
  40355. ** s1 += x[i+1] + s0;
  40356. ** endfor
  40357. **
  40358. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  40359. ** in reverse order (the largest fibonacci weight occurs on the first element
  40360. ** of the sequence being summed.) The s1 value spans all 32-bit
  40361. ** terms of the sequence whereas s0 omits the final term.
  40362. **
  40363. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  40364. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  40365. ** The VFS.xSync operations serve as write barriers - all writes launched
  40366. ** before the xSync must complete before any write that launches after the
  40367. ** xSync begins.
  40368. **
  40369. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  40370. ** value is randomized. This prevents old and new frames in the WAL from
  40371. ** being considered valid at the same time and being checkpointing together
  40372. ** following a crash.
  40373. **
  40374. ** READER ALGORITHM
  40375. **
  40376. ** To read a page from the database (call it page number P), a reader
  40377. ** first checks the WAL to see if it contains page P. If so, then the
  40378. ** last valid instance of page P that is a followed by a commit frame
  40379. ** or is a commit frame itself becomes the value read. If the WAL
  40380. ** contains no copies of page P that are valid and which are a commit
  40381. ** frame or are followed by a commit frame, then page P is read from
  40382. ** the database file.
  40383. **
  40384. ** To start a read transaction, the reader records the index of the last
  40385. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  40386. ** for all subsequent read operations. New transactions can be appended
  40387. ** to the WAL, but as long as the reader uses its original mxFrame value
  40388. ** and ignores the newly appended content, it will see a consistent snapshot
  40389. ** of the database from a single point in time. This technique allows
  40390. ** multiple concurrent readers to view different versions of the database
  40391. ** content simultaneously.
  40392. **
  40393. ** The reader algorithm in the previous paragraphs works correctly, but
  40394. ** because frames for page P can appear anywhere within the WAL, the
  40395. ** reader has to scan the entire WAL looking for page P frames. If the
  40396. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  40397. ** and read performance suffers. To overcome this problem, a separate
  40398. ** data structure called the wal-index is maintained to expedite the
  40399. ** search for frames of a particular page.
  40400. **
  40401. ** WAL-INDEX FORMAT
  40402. **
  40403. ** Conceptually, the wal-index is shared memory, though VFS implementations
  40404. ** might choose to implement the wal-index using a mmapped file. Because
  40405. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  40406. ** on a network filesystem. All users of the database must be able to
  40407. ** share memory.
  40408. **
  40409. ** The wal-index is transient. After a crash, the wal-index can (and should
  40410. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  40411. ** to either truncate or zero the header of the wal-index when the last
  40412. ** connection to it closes. Because the wal-index is transient, it can
  40413. ** use an architecture-specific format; it does not have to be cross-platform.
  40414. ** Hence, unlike the database and WAL file formats which store all values
  40415. ** as big endian, the wal-index can store multi-byte values in the native
  40416. ** byte order of the host computer.
  40417. **
  40418. ** The purpose of the wal-index is to answer this question quickly: Given
  40419. ** a page number P, return the index of the last frame for page P in the WAL,
  40420. ** or return NULL if there are no frames for page P in the WAL.
  40421. **
  40422. ** The wal-index consists of a header region, followed by an one or
  40423. ** more index blocks.
  40424. **
  40425. ** The wal-index header contains the total number of frames within the WAL
  40426. ** in the the mxFrame field.
  40427. **
  40428. ** Each index block except for the first contains information on
  40429. ** HASHTABLE_NPAGE frames. The first index block contains information on
  40430. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  40431. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  40432. ** first index block are the same size as all other index blocks in the
  40433. ** wal-index.
  40434. **
  40435. ** Each index block contains two sections, a page-mapping that contains the
  40436. ** database page number associated with each wal frame, and a hash-table
  40437. ** that allows readers to query an index block for a specific page number.
  40438. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  40439. ** for the first index block) 32-bit page numbers. The first entry in the
  40440. ** first index-block contains the database page number corresponding to the
  40441. ** first frame in the WAL file. The first entry in the second index block
  40442. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  40443. ** the log, and so on.
  40444. **
  40445. ** The last index block in a wal-index usually contains less than the full
  40446. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  40447. ** depending on the contents of the WAL file. This does not change the
  40448. ** allocated size of the page-mapping array - the page-mapping array merely
  40449. ** contains unused entries.
  40450. **
  40451. ** Even without using the hash table, the last frame for page P
  40452. ** can be found by scanning the page-mapping sections of each index block
  40453. ** starting with the last index block and moving toward the first, and
  40454. ** within each index block, starting at the end and moving toward the
  40455. ** beginning. The first entry that equals P corresponds to the frame
  40456. ** holding the content for that page.
  40457. **
  40458. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  40459. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  40460. ** hash table for each page number in the mapping section, so the hash
  40461. ** table is never more than half full. The expected number of collisions
  40462. ** prior to finding a match is 1. Each entry of the hash table is an
  40463. ** 1-based index of an entry in the mapping section of the same
  40464. ** index block. Let K be the 1-based index of the largest entry in
  40465. ** the mapping section. (For index blocks other than the last, K will
  40466. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  40467. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  40468. ** contain a value of 0.
  40469. **
  40470. ** To look for page P in the hash table, first compute a hash iKey on
  40471. ** P as follows:
  40472. **
  40473. ** iKey = (P * 383) % HASHTABLE_NSLOT
  40474. **
  40475. ** Then start scanning entries of the hash table, starting with iKey
  40476. ** (wrapping around to the beginning when the end of the hash table is
  40477. ** reached) until an unused hash slot is found. Let the first unused slot
  40478. ** be at index iUnused. (iUnused might be less than iKey if there was
  40479. ** wrap-around.) Because the hash table is never more than half full,
  40480. ** the search is guaranteed to eventually hit an unused entry. Let
  40481. ** iMax be the value between iKey and iUnused, closest to iUnused,
  40482. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  40483. ** no hash slot such that aHash[i]==p) then page P is not in the
  40484. ** current index block. Otherwise the iMax-th mapping entry of the
  40485. ** current index block corresponds to the last entry that references
  40486. ** page P.
  40487. **
  40488. ** A hash search begins with the last index block and moves toward the
  40489. ** first index block, looking for entries corresponding to page P. On
  40490. ** average, only two or three slots in each index block need to be
  40491. ** examined in order to either find the last entry for page P, or to
  40492. ** establish that no such entry exists in the block. Each index block
  40493. ** holds over 4000 entries. So two or three index blocks are sufficient
  40494. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  40495. ** comparisons (on average) suffice to either locate a frame in the
  40496. ** WAL or to establish that the frame does not exist in the WAL. This
  40497. ** is much faster than scanning the entire 10MB WAL.
  40498. **
  40499. ** Note that entries are added in order of increasing K. Hence, one
  40500. ** reader might be using some value K0 and a second reader that started
  40501. ** at a later time (after additional transactions were added to the WAL
  40502. ** and to the wal-index) might be using a different value K1, where K1>K0.
  40503. ** Both readers can use the same hash table and mapping section to get
  40504. ** the correct result. There may be entries in the hash table with
  40505. ** K>K0 but to the first reader, those entries will appear to be unused
  40506. ** slots in the hash table and so the first reader will get an answer as
  40507. ** if no values greater than K0 had ever been inserted into the hash table
  40508. ** in the first place - which is what reader one wants. Meanwhile, the
  40509. ** second reader using K1 will see additional values that were inserted
  40510. ** later, which is exactly what reader two wants.
  40511. **
  40512. ** When a rollback occurs, the value of K is decreased. Hash table entries
  40513. ** that correspond to frames greater than the new K value are removed
  40514. ** from the hash table at this point.
  40515. */
  40516. #ifndef SQLITE_OMIT_WAL
  40517. /*
  40518. ** Trace output macros
  40519. */
  40520. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  40521. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  40522. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  40523. #else
  40524. # define WALTRACE(X)
  40525. #endif
  40526. /*
  40527. ** The maximum (and only) versions of the wal and wal-index formats
  40528. ** that may be interpreted by this version of SQLite.
  40529. **
  40530. ** If a client begins recovering a WAL file and finds that (a) the checksum
  40531. ** values in the wal-header are correct and (b) the version field is not
  40532. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  40533. **
  40534. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  40535. ** checksum test is successful) and finds that the version field is not
  40536. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  40537. ** returns SQLITE_CANTOPEN.
  40538. */
  40539. #define WAL_MAX_VERSION 3007000
  40540. #define WALINDEX_MAX_VERSION 3007000
  40541. /*
  40542. ** Indices of various locking bytes. WAL_NREADER is the number
  40543. ** of available reader locks and should be at least 3.
  40544. */
  40545. #define WAL_WRITE_LOCK 0
  40546. #define WAL_ALL_BUT_WRITE 1
  40547. #define WAL_CKPT_LOCK 1
  40548. #define WAL_RECOVER_LOCK 2
  40549. #define WAL_READ_LOCK(I) (3+(I))
  40550. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  40551. /* Object declarations */
  40552. typedef struct WalIndexHdr WalIndexHdr;
  40553. typedef struct WalIterator WalIterator;
  40554. typedef struct WalCkptInfo WalCkptInfo;
  40555. /*
  40556. ** The following object holds a copy of the wal-index header content.
  40557. **
  40558. ** The actual header in the wal-index consists of two copies of this
  40559. ** object.
  40560. **
  40561. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  40562. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  40563. ** added in 3.7.1 when support for 64K pages was added.
  40564. */
  40565. struct WalIndexHdr {
  40566. u32 iVersion; /* Wal-index version */
  40567. u32 unused; /* Unused (padding) field */
  40568. u32 iChange; /* Counter incremented each transaction */
  40569. u8 isInit; /* 1 when initialized */
  40570. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  40571. u16 szPage; /* Database page size in bytes. 1==64K */
  40572. u32 mxFrame; /* Index of last valid frame in the WAL */
  40573. u32 nPage; /* Size of database in pages */
  40574. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  40575. u32 aSalt[2]; /* Two salt values copied from WAL header */
  40576. u32 aCksum[2]; /* Checksum over all prior fields */
  40577. };
  40578. /*
  40579. ** A copy of the following object occurs in the wal-index immediately
  40580. ** following the second copy of the WalIndexHdr. This object stores
  40581. ** information used by checkpoint.
  40582. **
  40583. ** nBackfill is the number of frames in the WAL that have been written
  40584. ** back into the database. (We call the act of moving content from WAL to
  40585. ** database "backfilling".) The nBackfill number is never greater than
  40586. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  40587. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  40588. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  40589. ** mxFrame back to zero when the WAL is reset.
  40590. **
  40591. ** There is one entry in aReadMark[] for each reader lock. If a reader
  40592. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  40593. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  40594. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  40595. ** a special case; its value is never used and it exists as a place-holder
  40596. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  40597. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  40598. ** directly from the database.
  40599. **
  40600. ** The value of aReadMark[K] may only be changed by a thread that
  40601. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  40602. ** aReadMark[K] cannot changed while there is a reader is using that mark
  40603. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  40604. **
  40605. ** The checkpointer may only transfer frames from WAL to database where
  40606. ** the frame numbers are less than or equal to every aReadMark[] that is
  40607. ** in use (that is, every aReadMark[j] for which there is a corresponding
  40608. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  40609. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  40610. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  40611. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  40612. ** in the WAL has been backfilled into the database) then new readers
  40613. ** will choose aReadMark[0] which has value 0 and hence such reader will
  40614. ** get all their all content directly from the database file and ignore
  40615. ** the WAL.
  40616. **
  40617. ** Writers normally append new frames to the end of the WAL. However,
  40618. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  40619. ** written back into the database) and if no readers are using the WAL
  40620. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  40621. ** the writer will first "reset" the WAL back to the beginning and start
  40622. ** writing new content beginning at frame 1.
  40623. **
  40624. ** We assume that 32-bit loads are atomic and so no locks are needed in
  40625. ** order to read from any aReadMark[] entries.
  40626. */
  40627. struct WalCkptInfo {
  40628. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  40629. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  40630. };
  40631. #define READMARK_NOT_USED 0xffffffff
  40632. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  40633. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  40634. ** only support mandatory file-locks, we do not read or write data
  40635. ** from the region of the file on which locks are applied.
  40636. */
  40637. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  40638. #define WALINDEX_LOCK_RESERVED 16
  40639. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  40640. /* Size of header before each frame in wal */
  40641. #define WAL_FRAME_HDRSIZE 24
  40642. /* Size of write ahead log header, including checksum. */
  40643. /* #define WAL_HDRSIZE 24 */
  40644. #define WAL_HDRSIZE 32
  40645. /* WAL magic value. Either this value, or the same value with the least
  40646. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  40647. ** big-endian format in the first 4 bytes of a WAL file.
  40648. **
  40649. ** If the LSB is set, then the checksums for each frame within the WAL
  40650. ** file are calculated by treating all data as an array of 32-bit
  40651. ** big-endian words. Otherwise, they are calculated by interpreting
  40652. ** all data as 32-bit little-endian words.
  40653. */
  40654. #define WAL_MAGIC 0x377f0682
  40655. /*
  40656. ** Return the offset of frame iFrame in the write-ahead log file,
  40657. ** assuming a database page size of szPage bytes. The offset returned
  40658. ** is to the start of the write-ahead log frame-header.
  40659. */
  40660. #define walFrameOffset(iFrame, szPage) ( \
  40661. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  40662. )
  40663. /*
  40664. ** An open write-ahead log file is represented by an instance of the
  40665. ** following object.
  40666. */
  40667. struct Wal {
  40668. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  40669. sqlite3_file *pDbFd; /* File handle for the database file */
  40670. sqlite3_file *pWalFd; /* File handle for WAL file */
  40671. u32 iCallback; /* Value to pass to log callback (or 0) */
  40672. int nWiData; /* Size of array apWiData */
  40673. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  40674. u32 szPage; /* Database page size */
  40675. i16 readLock; /* Which read lock is being held. -1 for none */
  40676. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  40677. u8 writeLock; /* True if in a write transaction */
  40678. u8 ckptLock; /* True if holding a checkpoint lock */
  40679. u8 readOnly; /* True if the WAL file is open read-only */
  40680. WalIndexHdr hdr; /* Wal-index header for current transaction */
  40681. const char *zWalName; /* Name of WAL file */
  40682. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  40683. #ifdef SQLITE_DEBUG
  40684. u8 lockError; /* True if a locking error has occurred */
  40685. #endif
  40686. };
  40687. /*
  40688. ** Candidate values for Wal.exclusiveMode.
  40689. */
  40690. #define WAL_NORMAL_MODE 0
  40691. #define WAL_EXCLUSIVE_MODE 1
  40692. #define WAL_HEAPMEMORY_MODE 2
  40693. /*
  40694. ** Each page of the wal-index mapping contains a hash-table made up of
  40695. ** an array of HASHTABLE_NSLOT elements of the following type.
  40696. */
  40697. typedef u16 ht_slot;
  40698. /*
  40699. ** This structure is used to implement an iterator that loops through
  40700. ** all frames in the WAL in database page order. Where two or more frames
  40701. ** correspond to the same database page, the iterator visits only the
  40702. ** frame most recently written to the WAL (in other words, the frame with
  40703. ** the largest index).
  40704. **
  40705. ** The internals of this structure are only accessed by:
  40706. **
  40707. ** walIteratorInit() - Create a new iterator,
  40708. ** walIteratorNext() - Step an iterator,
  40709. ** walIteratorFree() - Free an iterator.
  40710. **
  40711. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  40712. */
  40713. struct WalIterator {
  40714. int iPrior; /* Last result returned from the iterator */
  40715. int nSegment; /* Number of entries in aSegment[] */
  40716. struct WalSegment {
  40717. int iNext; /* Next slot in aIndex[] not yet returned */
  40718. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  40719. u32 *aPgno; /* Array of page numbers. */
  40720. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  40721. int iZero; /* Frame number associated with aPgno[0] */
  40722. } aSegment[1]; /* One for every 32KB page in the wal-index */
  40723. };
  40724. /*
  40725. ** Define the parameters of the hash tables in the wal-index file. There
  40726. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  40727. ** wal-index.
  40728. **
  40729. ** Changing any of these constants will alter the wal-index format and
  40730. ** create incompatibilities.
  40731. */
  40732. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  40733. #define HASHTABLE_HASH_1 383 /* Should be prime */
  40734. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  40735. /*
  40736. ** The block of page numbers associated with the first hash-table in a
  40737. ** wal-index is smaller than usual. This is so that there is a complete
  40738. ** hash-table on each aligned 32KB page of the wal-index.
  40739. */
  40740. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  40741. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  40742. #define WALINDEX_PGSZ ( \
  40743. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  40744. )
  40745. /*
  40746. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  40747. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  40748. ** numbered from zero.
  40749. **
  40750. ** If this call is successful, *ppPage is set to point to the wal-index
  40751. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  40752. ** then an SQLite error code is returned and *ppPage is set to 0.
  40753. */
  40754. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  40755. int rc = SQLITE_OK;
  40756. /* Enlarge the pWal->apWiData[] array if required */
  40757. if( pWal->nWiData<=iPage ){
  40758. int nByte = sizeof(u32*)*(iPage+1);
  40759. volatile u32 **apNew;
  40760. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  40761. if( !apNew ){
  40762. *ppPage = 0;
  40763. return SQLITE_NOMEM;
  40764. }
  40765. memset((void*)&apNew[pWal->nWiData], 0,
  40766. sizeof(u32*)*(iPage+1-pWal->nWiData));
  40767. pWal->apWiData = apNew;
  40768. pWal->nWiData = iPage+1;
  40769. }
  40770. /* Request a pointer to the required page from the VFS */
  40771. if( pWal->apWiData[iPage]==0 ){
  40772. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  40773. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  40774. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  40775. }else{
  40776. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  40777. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  40778. );
  40779. }
  40780. }
  40781. *ppPage = pWal->apWiData[iPage];
  40782. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  40783. return rc;
  40784. }
  40785. /*
  40786. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  40787. */
  40788. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  40789. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  40790. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  40791. }
  40792. /*
  40793. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  40794. */
  40795. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  40796. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  40797. return (volatile WalIndexHdr*)pWal->apWiData[0];
  40798. }
  40799. /*
  40800. ** The argument to this macro must be of type u32. On a little-endian
  40801. ** architecture, it returns the u32 value that results from interpreting
  40802. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  40803. ** returns the value that would be produced by intepreting the 4 bytes
  40804. ** of the input value as a little-endian integer.
  40805. */
  40806. #define BYTESWAP32(x) ( \
  40807. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  40808. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  40809. )
  40810. /*
  40811. ** Generate or extend an 8 byte checksum based on the data in
  40812. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  40813. ** initial values of 0 and 0 if aIn==NULL).
  40814. **
  40815. ** The checksum is written back into aOut[] before returning.
  40816. **
  40817. ** nByte must be a positive multiple of 8.
  40818. */
  40819. static void walChecksumBytes(
  40820. int nativeCksum, /* True for native byte-order, false for non-native */
  40821. u8 *a, /* Content to be checksummed */
  40822. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  40823. const u32 *aIn, /* Initial checksum value input */
  40824. u32 *aOut /* OUT: Final checksum value output */
  40825. ){
  40826. u32 s1, s2;
  40827. u32 *aData = (u32 *)a;
  40828. u32 *aEnd = (u32 *)&a[nByte];
  40829. if( aIn ){
  40830. s1 = aIn[0];
  40831. s2 = aIn[1];
  40832. }else{
  40833. s1 = s2 = 0;
  40834. }
  40835. assert( nByte>=8 );
  40836. assert( (nByte&0x00000007)==0 );
  40837. if( nativeCksum ){
  40838. do {
  40839. s1 += *aData++ + s2;
  40840. s2 += *aData++ + s1;
  40841. }while( aData<aEnd );
  40842. }else{
  40843. do {
  40844. s1 += BYTESWAP32(aData[0]) + s2;
  40845. s2 += BYTESWAP32(aData[1]) + s1;
  40846. aData += 2;
  40847. }while( aData<aEnd );
  40848. }
  40849. aOut[0] = s1;
  40850. aOut[1] = s2;
  40851. }
  40852. static void walShmBarrier(Wal *pWal){
  40853. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  40854. sqlite3OsShmBarrier(pWal->pDbFd);
  40855. }
  40856. }
  40857. /*
  40858. ** Write the header information in pWal->hdr into the wal-index.
  40859. **
  40860. ** The checksum on pWal->hdr is updated before it is written.
  40861. */
  40862. static void walIndexWriteHdr(Wal *pWal){
  40863. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  40864. const int nCksum = offsetof(WalIndexHdr, aCksum);
  40865. assert( pWal->writeLock );
  40866. pWal->hdr.isInit = 1;
  40867. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  40868. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  40869. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  40870. walShmBarrier(pWal);
  40871. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  40872. }
  40873. /*
  40874. ** This function encodes a single frame header and writes it to a buffer
  40875. ** supplied by the caller. A frame-header is made up of a series of
  40876. ** 4-byte big-endian integers, as follows:
  40877. **
  40878. ** 0: Page number.
  40879. ** 4: For commit records, the size of the database image in pages
  40880. ** after the commit. For all other records, zero.
  40881. ** 8: Salt-1 (copied from the wal-header)
  40882. ** 12: Salt-2 (copied from the wal-header)
  40883. ** 16: Checksum-1.
  40884. ** 20: Checksum-2.
  40885. */
  40886. static void walEncodeFrame(
  40887. Wal *pWal, /* The write-ahead log */
  40888. u32 iPage, /* Database page number for frame */
  40889. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  40890. u8 *aData, /* Pointer to page data */
  40891. u8 *aFrame /* OUT: Write encoded frame here */
  40892. ){
  40893. int nativeCksum; /* True for native byte-order checksums */
  40894. u32 *aCksum = pWal->hdr.aFrameCksum;
  40895. assert( WAL_FRAME_HDRSIZE==24 );
  40896. sqlite3Put4byte(&aFrame[0], iPage);
  40897. sqlite3Put4byte(&aFrame[4], nTruncate);
  40898. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  40899. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  40900. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  40901. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  40902. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  40903. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  40904. }
  40905. /*
  40906. ** Check to see if the frame with header in aFrame[] and content
  40907. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  40908. ** *pnTruncate and return true. Return if the frame is not valid.
  40909. */
  40910. static int walDecodeFrame(
  40911. Wal *pWal, /* The write-ahead log */
  40912. u32 *piPage, /* OUT: Database page number for frame */
  40913. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  40914. u8 *aData, /* Pointer to page data (for checksum) */
  40915. u8 *aFrame /* Frame data */
  40916. ){
  40917. int nativeCksum; /* True for native byte-order checksums */
  40918. u32 *aCksum = pWal->hdr.aFrameCksum;
  40919. u32 pgno; /* Page number of the frame */
  40920. assert( WAL_FRAME_HDRSIZE==24 );
  40921. /* A frame is only valid if the salt values in the frame-header
  40922. ** match the salt values in the wal-header.
  40923. */
  40924. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  40925. return 0;
  40926. }
  40927. /* A frame is only valid if the page number is creater than zero.
  40928. */
  40929. pgno = sqlite3Get4byte(&aFrame[0]);
  40930. if( pgno==0 ){
  40931. return 0;
  40932. }
  40933. /* A frame is only valid if a checksum of the WAL header,
  40934. ** all prior frams, the first 16 bytes of this frame-header,
  40935. ** and the frame-data matches the checksum in the last 8
  40936. ** bytes of this frame-header.
  40937. */
  40938. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  40939. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  40940. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  40941. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  40942. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  40943. ){
  40944. /* Checksum failed. */
  40945. return 0;
  40946. }
  40947. /* If we reach this point, the frame is valid. Return the page number
  40948. ** and the new database size.
  40949. */
  40950. *piPage = pgno;
  40951. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  40952. return 1;
  40953. }
  40954. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  40955. /*
  40956. ** Names of locks. This routine is used to provide debugging output and is not
  40957. ** a part of an ordinary build.
  40958. */
  40959. static const char *walLockName(int lockIdx){
  40960. if( lockIdx==WAL_WRITE_LOCK ){
  40961. return "WRITE-LOCK";
  40962. }else if( lockIdx==WAL_CKPT_LOCK ){
  40963. return "CKPT-LOCK";
  40964. }else if( lockIdx==WAL_RECOVER_LOCK ){
  40965. return "RECOVER-LOCK";
  40966. }else{
  40967. static char zName[15];
  40968. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  40969. lockIdx-WAL_READ_LOCK(0));
  40970. return zName;
  40971. }
  40972. }
  40973. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  40974. /*
  40975. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  40976. ** A lock cannot be moved directly between shared and exclusive - it must go
  40977. ** through the unlocked state first.
  40978. **
  40979. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  40980. */
  40981. static int walLockShared(Wal *pWal, int lockIdx){
  40982. int rc;
  40983. if( pWal->exclusiveMode ) return SQLITE_OK;
  40984. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  40985. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  40986. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  40987. walLockName(lockIdx), rc ? "failed" : "ok"));
  40988. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  40989. return rc;
  40990. }
  40991. static void walUnlockShared(Wal *pWal, int lockIdx){
  40992. if( pWal->exclusiveMode ) return;
  40993. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  40994. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  40995. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  40996. }
  40997. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  40998. int rc;
  40999. if( pWal->exclusiveMode ) return SQLITE_OK;
  41000. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  41001. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  41002. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  41003. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  41004. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  41005. return rc;
  41006. }
  41007. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  41008. if( pWal->exclusiveMode ) return;
  41009. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  41010. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  41011. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  41012. walLockName(lockIdx), n));
  41013. }
  41014. /*
  41015. ** Compute a hash on a page number. The resulting hash value must land
  41016. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  41017. ** the hash to the next value in the event of a collision.
  41018. */
  41019. static int walHash(u32 iPage){
  41020. assert( iPage>0 );
  41021. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  41022. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  41023. }
  41024. static int walNextHash(int iPriorHash){
  41025. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  41026. }
  41027. /*
  41028. ** Return pointers to the hash table and page number array stored on
  41029. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  41030. ** numbered starting from 0.
  41031. **
  41032. ** Set output variable *paHash to point to the start of the hash table
  41033. ** in the wal-index file. Set *piZero to one less than the frame
  41034. ** number of the first frame indexed by this hash table. If a
  41035. ** slot in the hash table is set to N, it refers to frame number
  41036. ** (*piZero+N) in the log.
  41037. **
  41038. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  41039. ** first frame indexed by the hash table, frame (*piZero+1).
  41040. */
  41041. static int walHashGet(
  41042. Wal *pWal, /* WAL handle */
  41043. int iHash, /* Find the iHash'th table */
  41044. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  41045. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  41046. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  41047. ){
  41048. int rc; /* Return code */
  41049. volatile u32 *aPgno;
  41050. rc = walIndexPage(pWal, iHash, &aPgno);
  41051. assert( rc==SQLITE_OK || iHash>0 );
  41052. if( rc==SQLITE_OK ){
  41053. u32 iZero;
  41054. volatile ht_slot *aHash;
  41055. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  41056. if( iHash==0 ){
  41057. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  41058. iZero = 0;
  41059. }else{
  41060. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  41061. }
  41062. *paPgno = &aPgno[-1];
  41063. *paHash = aHash;
  41064. *piZero = iZero;
  41065. }
  41066. return rc;
  41067. }
  41068. /*
  41069. ** Return the number of the wal-index page that contains the hash-table
  41070. ** and page-number array that contain entries corresponding to WAL frame
  41071. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  41072. ** are numbered starting from 0.
  41073. */
  41074. static int walFramePage(u32 iFrame){
  41075. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  41076. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  41077. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  41078. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  41079. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  41080. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  41081. );
  41082. return iHash;
  41083. }
  41084. /*
  41085. ** Return the page number associated with frame iFrame in this WAL.
  41086. */
  41087. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  41088. int iHash = walFramePage(iFrame);
  41089. if( iHash==0 ){
  41090. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  41091. }
  41092. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  41093. }
  41094. /*
  41095. ** Remove entries from the hash table that point to WAL slots greater
  41096. ** than pWal->hdr.mxFrame.
  41097. **
  41098. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  41099. ** to a rollback or savepoint.
  41100. **
  41101. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  41102. ** updated. Any later hash tables will be automatically cleared when
  41103. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  41104. ** actually needed.
  41105. */
  41106. static void walCleanupHash(Wal *pWal){
  41107. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  41108. volatile u32 *aPgno = 0; /* Page number array for hash table */
  41109. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  41110. int iLimit = 0; /* Zero values greater than this */
  41111. int nByte; /* Number of bytes to zero in aPgno[] */
  41112. int i; /* Used to iterate through aHash[] */
  41113. assert( pWal->writeLock );
  41114. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  41115. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  41116. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  41117. if( pWal->hdr.mxFrame==0 ) return;
  41118. /* Obtain pointers to the hash-table and page-number array containing
  41119. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  41120. ** that the page said hash-table and array reside on is already mapped.
  41121. */
  41122. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  41123. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  41124. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  41125. /* Zero all hash-table entries that correspond to frame numbers greater
  41126. ** than pWal->hdr.mxFrame.
  41127. */
  41128. iLimit = pWal->hdr.mxFrame - iZero;
  41129. assert( iLimit>0 );
  41130. for(i=0; i<HASHTABLE_NSLOT; i++){
  41131. if( aHash[i]>iLimit ){
  41132. aHash[i] = 0;
  41133. }
  41134. }
  41135. /* Zero the entries in the aPgno array that correspond to frames with
  41136. ** frame numbers greater than pWal->hdr.mxFrame.
  41137. */
  41138. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  41139. memset((void *)&aPgno[iLimit+1], 0, nByte);
  41140. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  41141. /* Verify that the every entry in the mapping region is still reachable
  41142. ** via the hash table even after the cleanup.
  41143. */
  41144. if( iLimit ){
  41145. int i; /* Loop counter */
  41146. int iKey; /* Hash key */
  41147. for(i=1; i<=iLimit; i++){
  41148. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  41149. if( aHash[iKey]==i ) break;
  41150. }
  41151. assert( aHash[iKey]==i );
  41152. }
  41153. }
  41154. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  41155. }
  41156. /*
  41157. ** Set an entry in the wal-index that will map database page number
  41158. ** pPage into WAL frame iFrame.
  41159. */
  41160. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  41161. int rc; /* Return code */
  41162. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  41163. volatile u32 *aPgno = 0; /* Page number array */
  41164. volatile ht_slot *aHash = 0; /* Hash table */
  41165. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  41166. /* Assuming the wal-index file was successfully mapped, populate the
  41167. ** page number array and hash table entry.
  41168. */
  41169. if( rc==SQLITE_OK ){
  41170. int iKey; /* Hash table key */
  41171. int idx; /* Value to write to hash-table slot */
  41172. int nCollide; /* Number of hash collisions */
  41173. idx = iFrame - iZero;
  41174. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  41175. /* If this is the first entry to be added to this hash-table, zero the
  41176. ** entire hash table and aPgno[] array before proceding.
  41177. */
  41178. if( idx==1 ){
  41179. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  41180. memset((void*)&aPgno[1], 0, nByte);
  41181. }
  41182. /* If the entry in aPgno[] is already set, then the previous writer
  41183. ** must have exited unexpectedly in the middle of a transaction (after
  41184. ** writing one or more dirty pages to the WAL to free up memory).
  41185. ** Remove the remnants of that writers uncommitted transaction from
  41186. ** the hash-table before writing any new entries.
  41187. */
  41188. if( aPgno[idx] ){
  41189. walCleanupHash(pWal);
  41190. assert( !aPgno[idx] );
  41191. }
  41192. /* Write the aPgno[] array entry and the hash-table slot. */
  41193. nCollide = idx;
  41194. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  41195. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  41196. }
  41197. aPgno[idx] = iPage;
  41198. aHash[iKey] = (ht_slot)idx;
  41199. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  41200. /* Verify that the number of entries in the hash table exactly equals
  41201. ** the number of entries in the mapping region.
  41202. */
  41203. {
  41204. int i; /* Loop counter */
  41205. int nEntry = 0; /* Number of entries in the hash table */
  41206. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  41207. assert( nEntry==idx );
  41208. }
  41209. /* Verify that the every entry in the mapping region is reachable
  41210. ** via the hash table. This turns out to be a really, really expensive
  41211. ** thing to check, so only do this occasionally - not on every
  41212. ** iteration.
  41213. */
  41214. if( (idx&0x3ff)==0 ){
  41215. int i; /* Loop counter */
  41216. for(i=1; i<=idx; i++){
  41217. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  41218. if( aHash[iKey]==i ) break;
  41219. }
  41220. assert( aHash[iKey]==i );
  41221. }
  41222. }
  41223. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  41224. }
  41225. return rc;
  41226. }
  41227. /*
  41228. ** Recover the wal-index by reading the write-ahead log file.
  41229. **
  41230. ** This routine first tries to establish an exclusive lock on the
  41231. ** wal-index to prevent other threads/processes from doing anything
  41232. ** with the WAL or wal-index while recovery is running. The
  41233. ** WAL_RECOVER_LOCK is also held so that other threads will know
  41234. ** that this thread is running recovery. If unable to establish
  41235. ** the necessary locks, this routine returns SQLITE_BUSY.
  41236. */
  41237. static int walIndexRecover(Wal *pWal){
  41238. int rc; /* Return Code */
  41239. i64 nSize; /* Size of log file */
  41240. u32 aFrameCksum[2] = {0, 0};
  41241. int iLock; /* Lock offset to lock for checkpoint */
  41242. int nLock; /* Number of locks to hold */
  41243. /* Obtain an exclusive lock on all byte in the locking range not already
  41244. ** locked by the caller. The caller is guaranteed to have locked the
  41245. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  41246. ** If successful, the same bytes that are locked here are unlocked before
  41247. ** this function returns.
  41248. */
  41249. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  41250. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  41251. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  41252. assert( pWal->writeLock );
  41253. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  41254. nLock = SQLITE_SHM_NLOCK - iLock;
  41255. rc = walLockExclusive(pWal, iLock, nLock);
  41256. if( rc ){
  41257. return rc;
  41258. }
  41259. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  41260. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  41261. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  41262. if( rc!=SQLITE_OK ){
  41263. goto recovery_error;
  41264. }
  41265. if( nSize>WAL_HDRSIZE ){
  41266. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  41267. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  41268. int szFrame; /* Number of bytes in buffer aFrame[] */
  41269. u8 *aData; /* Pointer to data part of aFrame buffer */
  41270. int iFrame; /* Index of last frame read */
  41271. i64 iOffset; /* Next offset to read from log file */
  41272. int szPage; /* Page size according to the log */
  41273. u32 magic; /* Magic value read from WAL header */
  41274. u32 version; /* Magic value read from WAL header */
  41275. /* Read in the WAL header. */
  41276. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  41277. if( rc!=SQLITE_OK ){
  41278. goto recovery_error;
  41279. }
  41280. /* If the database page size is not a power of two, or is greater than
  41281. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  41282. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  41283. ** WAL file.
  41284. */
  41285. magic = sqlite3Get4byte(&aBuf[0]);
  41286. szPage = sqlite3Get4byte(&aBuf[8]);
  41287. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  41288. || szPage&(szPage-1)
  41289. || szPage>SQLITE_MAX_PAGE_SIZE
  41290. || szPage<512
  41291. ){
  41292. goto finished;
  41293. }
  41294. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  41295. pWal->szPage = szPage;
  41296. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  41297. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  41298. /* Verify that the WAL header checksum is correct */
  41299. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  41300. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  41301. );
  41302. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  41303. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  41304. ){
  41305. goto finished;
  41306. }
  41307. /* Verify that the version number on the WAL format is one that
  41308. ** are able to understand */
  41309. version = sqlite3Get4byte(&aBuf[4]);
  41310. if( version!=WAL_MAX_VERSION ){
  41311. rc = SQLITE_CANTOPEN_BKPT;
  41312. goto finished;
  41313. }
  41314. /* Malloc a buffer to read frames into. */
  41315. szFrame = szPage + WAL_FRAME_HDRSIZE;
  41316. aFrame = (u8 *)sqlite3_malloc(szFrame);
  41317. if( !aFrame ){
  41318. rc = SQLITE_NOMEM;
  41319. goto recovery_error;
  41320. }
  41321. aData = &aFrame[WAL_FRAME_HDRSIZE];
  41322. /* Read all frames from the log file. */
  41323. iFrame = 0;
  41324. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  41325. u32 pgno; /* Database page number for frame */
  41326. u32 nTruncate; /* dbsize field from frame header */
  41327. int isValid; /* True if this frame is valid */
  41328. /* Read and decode the next log frame. */
  41329. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  41330. if( rc!=SQLITE_OK ) break;
  41331. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  41332. if( !isValid ) break;
  41333. rc = walIndexAppend(pWal, ++iFrame, pgno);
  41334. if( rc!=SQLITE_OK ) break;
  41335. /* If nTruncate is non-zero, this is a commit record. */
  41336. if( nTruncate ){
  41337. pWal->hdr.mxFrame = iFrame;
  41338. pWal->hdr.nPage = nTruncate;
  41339. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  41340. testcase( szPage<=32768 );
  41341. testcase( szPage>=65536 );
  41342. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  41343. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  41344. }
  41345. }
  41346. sqlite3_free(aFrame);
  41347. }
  41348. finished:
  41349. if( rc==SQLITE_OK ){
  41350. volatile WalCkptInfo *pInfo;
  41351. int i;
  41352. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  41353. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  41354. walIndexWriteHdr(pWal);
  41355. /* Reset the checkpoint-header. This is safe because this thread is
  41356. ** currently holding locks that exclude all other readers, writers and
  41357. ** checkpointers.
  41358. */
  41359. pInfo = walCkptInfo(pWal);
  41360. pInfo->nBackfill = 0;
  41361. pInfo->aReadMark[0] = 0;
  41362. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  41363. /* If more than one frame was recovered from the log file, report an
  41364. ** event via sqlite3_log(). This is to help with identifying performance
  41365. ** problems caused by applications routinely shutting down without
  41366. ** checkpointing the log file.
  41367. */
  41368. if( pWal->hdr.nPage ){
  41369. sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
  41370. pWal->hdr.nPage, pWal->zWalName
  41371. );
  41372. }
  41373. }
  41374. recovery_error:
  41375. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  41376. walUnlockExclusive(pWal, iLock, nLock);
  41377. return rc;
  41378. }
  41379. /*
  41380. ** Close an open wal-index.
  41381. */
  41382. static void walIndexClose(Wal *pWal, int isDelete){
  41383. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  41384. int i;
  41385. for(i=0; i<pWal->nWiData; i++){
  41386. sqlite3_free((void *)pWal->apWiData[i]);
  41387. pWal->apWiData[i] = 0;
  41388. }
  41389. }else{
  41390. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  41391. }
  41392. }
  41393. /*
  41394. ** Open a connection to the WAL file zWalName. The database file must
  41395. ** already be opened on connection pDbFd. The buffer that zWalName points
  41396. ** to must remain valid for the lifetime of the returned Wal* handle.
  41397. **
  41398. ** A SHARED lock should be held on the database file when this function
  41399. ** is called. The purpose of this SHARED lock is to prevent any other
  41400. ** client from unlinking the WAL or wal-index file. If another process
  41401. ** were to do this just after this client opened one of these files, the
  41402. ** system would be badly broken.
  41403. **
  41404. ** If the log file is successfully opened, SQLITE_OK is returned and
  41405. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  41406. ** an SQLite error code is returned and *ppWal is left unmodified.
  41407. */
  41408. SQLITE_PRIVATE int sqlite3WalOpen(
  41409. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  41410. sqlite3_file *pDbFd, /* The open database file */
  41411. const char *zWalName, /* Name of the WAL file */
  41412. int bNoShm, /* True to run in heap-memory mode */
  41413. Wal **ppWal /* OUT: Allocated Wal handle */
  41414. ){
  41415. int rc; /* Return Code */
  41416. Wal *pRet; /* Object to allocate and return */
  41417. int flags; /* Flags passed to OsOpen() */
  41418. assert( zWalName && zWalName[0] );
  41419. assert( pDbFd );
  41420. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  41421. ** this source file. Verify that the #defines of the locking byte offsets
  41422. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  41423. */
  41424. #ifdef WIN_SHM_BASE
  41425. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  41426. #endif
  41427. #ifdef UNIX_SHM_BASE
  41428. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  41429. #endif
  41430. /* Allocate an instance of struct Wal to return. */
  41431. *ppWal = 0;
  41432. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  41433. if( !pRet ){
  41434. return SQLITE_NOMEM;
  41435. }
  41436. pRet->pVfs = pVfs;
  41437. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  41438. pRet->pDbFd = pDbFd;
  41439. pRet->readLock = -1;
  41440. pRet->zWalName = zWalName;
  41441. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  41442. /* Open file handle on the write-ahead log file. */
  41443. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  41444. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  41445. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  41446. pRet->readOnly = 1;
  41447. }
  41448. if( rc!=SQLITE_OK ){
  41449. walIndexClose(pRet, 0);
  41450. sqlite3OsClose(pRet->pWalFd);
  41451. sqlite3_free(pRet);
  41452. }else{
  41453. *ppWal = pRet;
  41454. WALTRACE(("WAL%d: opened\n", pRet));
  41455. }
  41456. return rc;
  41457. }
  41458. /*
  41459. ** Find the smallest page number out of all pages held in the WAL that
  41460. ** has not been returned by any prior invocation of this method on the
  41461. ** same WalIterator object. Write into *piFrame the frame index where
  41462. ** that page was last written into the WAL. Write into *piPage the page
  41463. ** number.
  41464. **
  41465. ** Return 0 on success. If there are no pages in the WAL with a page
  41466. ** number larger than *piPage, then return 1.
  41467. */
  41468. static int walIteratorNext(
  41469. WalIterator *p, /* Iterator */
  41470. u32 *piPage, /* OUT: The page number of the next page */
  41471. u32 *piFrame /* OUT: Wal frame index of next page */
  41472. ){
  41473. u32 iMin; /* Result pgno must be greater than iMin */
  41474. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  41475. int i; /* For looping through segments */
  41476. iMin = p->iPrior;
  41477. assert( iMin<0xffffffff );
  41478. for(i=p->nSegment-1; i>=0; i--){
  41479. struct WalSegment *pSegment = &p->aSegment[i];
  41480. while( pSegment->iNext<pSegment->nEntry ){
  41481. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  41482. if( iPg>iMin ){
  41483. if( iPg<iRet ){
  41484. iRet = iPg;
  41485. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  41486. }
  41487. break;
  41488. }
  41489. pSegment->iNext++;
  41490. }
  41491. }
  41492. *piPage = p->iPrior = iRet;
  41493. return (iRet==0xFFFFFFFF);
  41494. }
  41495. /*
  41496. ** This function merges two sorted lists into a single sorted list.
  41497. **
  41498. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  41499. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  41500. ** is guaranteed for all J<K:
  41501. **
  41502. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  41503. ** aContent[aRight[J]] < aContent[aRight[K]]
  41504. **
  41505. ** This routine overwrites aRight[] with a new (probably longer) sequence
  41506. ** of indices such that the aRight[] contains every index that appears in
  41507. ** either aLeft[] or the old aRight[] and such that the second condition
  41508. ** above is still met.
  41509. **
  41510. ** The aContent[aLeft[X]] values will be unique for all X. And the
  41511. ** aContent[aRight[X]] values will be unique too. But there might be
  41512. ** one or more combinations of X and Y such that
  41513. **
  41514. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  41515. **
  41516. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  41517. */
  41518. static void walMerge(
  41519. const u32 *aContent, /* Pages in wal - keys for the sort */
  41520. ht_slot *aLeft, /* IN: Left hand input list */
  41521. int nLeft, /* IN: Elements in array *paLeft */
  41522. ht_slot **paRight, /* IN/OUT: Right hand input list */
  41523. int *pnRight, /* IN/OUT: Elements in *paRight */
  41524. ht_slot *aTmp /* Temporary buffer */
  41525. ){
  41526. int iLeft = 0; /* Current index in aLeft */
  41527. int iRight = 0; /* Current index in aRight */
  41528. int iOut = 0; /* Current index in output buffer */
  41529. int nRight = *pnRight;
  41530. ht_slot *aRight = *paRight;
  41531. assert( nLeft>0 && nRight>0 );
  41532. while( iRight<nRight || iLeft<nLeft ){
  41533. ht_slot logpage;
  41534. Pgno dbpage;
  41535. if( (iLeft<nLeft)
  41536. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  41537. ){
  41538. logpage = aLeft[iLeft++];
  41539. }else{
  41540. logpage = aRight[iRight++];
  41541. }
  41542. dbpage = aContent[logpage];
  41543. aTmp[iOut++] = logpage;
  41544. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  41545. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  41546. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  41547. }
  41548. *paRight = aLeft;
  41549. *pnRight = iOut;
  41550. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  41551. }
  41552. /*
  41553. ** Sort the elements in list aList using aContent[] as the sort key.
  41554. ** Remove elements with duplicate keys, preferring to keep the
  41555. ** larger aList[] values.
  41556. **
  41557. ** The aList[] entries are indices into aContent[]. The values in
  41558. ** aList[] are to be sorted so that for all J<K:
  41559. **
  41560. ** aContent[aList[J]] < aContent[aList[K]]
  41561. **
  41562. ** For any X and Y such that
  41563. **
  41564. ** aContent[aList[X]] == aContent[aList[Y]]
  41565. **
  41566. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  41567. ** the smaller.
  41568. */
  41569. static void walMergesort(
  41570. const u32 *aContent, /* Pages in wal */
  41571. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  41572. ht_slot *aList, /* IN/OUT: List to sort */
  41573. int *pnList /* IN/OUT: Number of elements in aList[] */
  41574. ){
  41575. struct Sublist {
  41576. int nList; /* Number of elements in aList */
  41577. ht_slot *aList; /* Pointer to sub-list content */
  41578. };
  41579. const int nList = *pnList; /* Size of input list */
  41580. int nMerge = 0; /* Number of elements in list aMerge */
  41581. ht_slot *aMerge = 0; /* List to be merged */
  41582. int iList; /* Index into input list */
  41583. int iSub = 0; /* Index into aSub array */
  41584. struct Sublist aSub[13]; /* Array of sub-lists */
  41585. memset(aSub, 0, sizeof(aSub));
  41586. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  41587. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  41588. for(iList=0; iList<nList; iList++){
  41589. nMerge = 1;
  41590. aMerge = &aList[iList];
  41591. for(iSub=0; iList & (1<<iSub); iSub++){
  41592. struct Sublist *p = &aSub[iSub];
  41593. assert( p->aList && p->nList<=(1<<iSub) );
  41594. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  41595. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  41596. }
  41597. aSub[iSub].aList = aMerge;
  41598. aSub[iSub].nList = nMerge;
  41599. }
  41600. for(iSub++; iSub<ArraySize(aSub); iSub++){
  41601. if( nList & (1<<iSub) ){
  41602. struct Sublist *p = &aSub[iSub];
  41603. assert( p->nList<=(1<<iSub) );
  41604. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  41605. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  41606. }
  41607. }
  41608. assert( aMerge==aList );
  41609. *pnList = nMerge;
  41610. #ifdef SQLITE_DEBUG
  41611. {
  41612. int i;
  41613. for(i=1; i<*pnList; i++){
  41614. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  41615. }
  41616. }
  41617. #endif
  41618. }
  41619. /*
  41620. ** Free an iterator allocated by walIteratorInit().
  41621. */
  41622. static void walIteratorFree(WalIterator *p){
  41623. sqlite3ScratchFree(p);
  41624. }
  41625. /*
  41626. ** Construct a WalInterator object that can be used to loop over all
  41627. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  41628. ** lock.
  41629. **
  41630. ** On success, make *pp point to the newly allocated WalInterator object
  41631. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  41632. ** returns an error, the value of *pp is undefined.
  41633. **
  41634. ** The calling routine should invoke walIteratorFree() to destroy the
  41635. ** WalIterator object when it has finished with it.
  41636. */
  41637. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  41638. WalIterator *p; /* Return value */
  41639. int nSegment; /* Number of segments to merge */
  41640. u32 iLast; /* Last frame in log */
  41641. int nByte; /* Number of bytes to allocate */
  41642. int i; /* Iterator variable */
  41643. ht_slot *aTmp; /* Temp space used by merge-sort */
  41644. int rc = SQLITE_OK; /* Return Code */
  41645. /* This routine only runs while holding the checkpoint lock. And
  41646. ** it only runs if there is actually content in the log (mxFrame>0).
  41647. */
  41648. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  41649. iLast = pWal->hdr.mxFrame;
  41650. /* Allocate space for the WalIterator object. */
  41651. nSegment = walFramePage(iLast) + 1;
  41652. nByte = sizeof(WalIterator)
  41653. + (nSegment-1)*sizeof(struct WalSegment)
  41654. + iLast*sizeof(ht_slot);
  41655. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  41656. if( !p ){
  41657. return SQLITE_NOMEM;
  41658. }
  41659. memset(p, 0, nByte);
  41660. p->nSegment = nSegment;
  41661. /* Allocate temporary space used by the merge-sort routine. This block
  41662. ** of memory will be freed before this function returns.
  41663. */
  41664. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  41665. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  41666. );
  41667. if( !aTmp ){
  41668. rc = SQLITE_NOMEM;
  41669. }
  41670. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  41671. volatile ht_slot *aHash;
  41672. u32 iZero;
  41673. volatile u32 *aPgno;
  41674. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  41675. if( rc==SQLITE_OK ){
  41676. int j; /* Counter variable */
  41677. int nEntry; /* Number of entries in this segment */
  41678. ht_slot *aIndex; /* Sorted index for this segment */
  41679. aPgno++;
  41680. if( (i+1)==nSegment ){
  41681. nEntry = (int)(iLast - iZero);
  41682. }else{
  41683. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  41684. }
  41685. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  41686. iZero++;
  41687. for(j=0; j<nEntry; j++){
  41688. aIndex[j] = (ht_slot)j;
  41689. }
  41690. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  41691. p->aSegment[i].iZero = iZero;
  41692. p->aSegment[i].nEntry = nEntry;
  41693. p->aSegment[i].aIndex = aIndex;
  41694. p->aSegment[i].aPgno = (u32 *)aPgno;
  41695. }
  41696. }
  41697. sqlite3ScratchFree(aTmp);
  41698. if( rc!=SQLITE_OK ){
  41699. walIteratorFree(p);
  41700. }
  41701. *pp = p;
  41702. return rc;
  41703. }
  41704. /*
  41705. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  41706. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  41707. ** busy-handler function. Invoke it and retry the lock until either the
  41708. ** lock is successfully obtained or the busy-handler returns 0.
  41709. */
  41710. static int walBusyLock(
  41711. Wal *pWal, /* WAL connection */
  41712. int (*xBusy)(void*), /* Function to call when busy */
  41713. void *pBusyArg, /* Context argument for xBusyHandler */
  41714. int lockIdx, /* Offset of first byte to lock */
  41715. int n /* Number of bytes to lock */
  41716. ){
  41717. int rc;
  41718. do {
  41719. rc = walLockExclusive(pWal, lockIdx, n);
  41720. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  41721. return rc;
  41722. }
  41723. /*
  41724. ** The cache of the wal-index header must be valid to call this function.
  41725. ** Return the page-size in bytes used by the database.
  41726. */
  41727. static int walPagesize(Wal *pWal){
  41728. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  41729. }
  41730. /*
  41731. ** Copy as much content as we can from the WAL back into the database file
  41732. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  41733. **
  41734. ** The amount of information copies from WAL to database might be limited
  41735. ** by active readers. This routine will never overwrite a database page
  41736. ** that a concurrent reader might be using.
  41737. **
  41738. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  41739. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  41740. ** checkpoints are always run by a background thread or background
  41741. ** process, foreground threads will never block on a lengthy fsync call.
  41742. **
  41743. ** Fsync is called on the WAL before writing content out of the WAL and
  41744. ** into the database. This ensures that if the new content is persistent
  41745. ** in the WAL and can be recovered following a power-loss or hard reset.
  41746. **
  41747. ** Fsync is also called on the database file if (and only if) the entire
  41748. ** WAL content is copied into the database file. This second fsync makes
  41749. ** it safe to delete the WAL since the new content will persist in the
  41750. ** database file.
  41751. **
  41752. ** This routine uses and updates the nBackfill field of the wal-index header.
  41753. ** This is the only routine tha will increase the value of nBackfill.
  41754. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  41755. ** its value.)
  41756. **
  41757. ** The caller must be holding sufficient locks to ensure that no other
  41758. ** checkpoint is running (in any other thread or process) at the same
  41759. ** time.
  41760. */
  41761. static int walCheckpoint(
  41762. Wal *pWal, /* Wal connection */
  41763. int eMode, /* One of PASSIVE, FULL or RESTART */
  41764. int (*xBusyCall)(void*), /* Function to call when busy */
  41765. void *pBusyArg, /* Context argument for xBusyHandler */
  41766. int sync_flags, /* Flags for OsSync() (or 0) */
  41767. u8 *zBuf /* Temporary buffer to use */
  41768. ){
  41769. int rc; /* Return code */
  41770. int szPage; /* Database page-size */
  41771. WalIterator *pIter = 0; /* Wal iterator context */
  41772. u32 iDbpage = 0; /* Next database page to write */
  41773. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  41774. u32 mxSafeFrame; /* Max frame that can be backfilled */
  41775. u32 mxPage; /* Max database page to write */
  41776. int i; /* Loop counter */
  41777. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  41778. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  41779. szPage = walPagesize(pWal);
  41780. testcase( szPage<=32768 );
  41781. testcase( szPage>=65536 );
  41782. pInfo = walCkptInfo(pWal);
  41783. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  41784. /* Allocate the iterator */
  41785. rc = walIteratorInit(pWal, &pIter);
  41786. if( rc!=SQLITE_OK ){
  41787. return rc;
  41788. }
  41789. assert( pIter );
  41790. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  41791. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  41792. ** safe to write into the database. Frames beyond mxSafeFrame might
  41793. ** overwrite database pages that are in use by active readers and thus
  41794. ** cannot be backfilled from the WAL.
  41795. */
  41796. mxSafeFrame = pWal->hdr.mxFrame;
  41797. mxPage = pWal->hdr.nPage;
  41798. for(i=1; i<WAL_NREADER; i++){
  41799. u32 y = pInfo->aReadMark[i];
  41800. if( mxSafeFrame>y ){
  41801. assert( y<=pWal->hdr.mxFrame );
  41802. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  41803. if( rc==SQLITE_OK ){
  41804. pInfo->aReadMark[i] = READMARK_NOT_USED;
  41805. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  41806. }else if( rc==SQLITE_BUSY ){
  41807. mxSafeFrame = y;
  41808. xBusy = 0;
  41809. }else{
  41810. goto walcheckpoint_out;
  41811. }
  41812. }
  41813. }
  41814. if( pInfo->nBackfill<mxSafeFrame
  41815. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  41816. ){
  41817. i64 nSize; /* Current size of database file */
  41818. u32 nBackfill = pInfo->nBackfill;
  41819. /* Sync the WAL to disk */
  41820. if( sync_flags ){
  41821. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  41822. }
  41823. /* If the database file may grow as a result of this checkpoint, hint
  41824. ** about the eventual size of the db file to the VFS layer.
  41825. */
  41826. if( rc==SQLITE_OK ){
  41827. i64 nReq = ((i64)mxPage * szPage);
  41828. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  41829. if( rc==SQLITE_OK && nSize<nReq ){
  41830. sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  41831. }
  41832. }
  41833. /* Iterate through the contents of the WAL, copying data to the db file. */
  41834. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  41835. i64 iOffset;
  41836. assert( walFramePgno(pWal, iFrame)==iDbpage );
  41837. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  41838. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  41839. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  41840. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  41841. if( rc!=SQLITE_OK ) break;
  41842. iOffset = (iDbpage-1)*(i64)szPage;
  41843. testcase( IS_BIG_INT(iOffset) );
  41844. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  41845. if( rc!=SQLITE_OK ) break;
  41846. }
  41847. /* If work was actually accomplished... */
  41848. if( rc==SQLITE_OK ){
  41849. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  41850. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  41851. testcase( IS_BIG_INT(szDb) );
  41852. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  41853. if( rc==SQLITE_OK && sync_flags ){
  41854. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  41855. }
  41856. }
  41857. if( rc==SQLITE_OK ){
  41858. pInfo->nBackfill = mxSafeFrame;
  41859. }
  41860. }
  41861. /* Release the reader lock held while backfilling */
  41862. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  41863. }
  41864. if( rc==SQLITE_BUSY ){
  41865. /* Reset the return code so as not to report a checkpoint failure
  41866. ** just because there are active readers. */
  41867. rc = SQLITE_OK;
  41868. }
  41869. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  41870. ** file has been copied into the database file, then block until all
  41871. ** readers have finished using the wal file. This ensures that the next
  41872. ** process to write to the database restarts the wal file.
  41873. */
  41874. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  41875. assert( pWal->writeLock );
  41876. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  41877. rc = SQLITE_BUSY;
  41878. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  41879. assert( mxSafeFrame==pWal->hdr.mxFrame );
  41880. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  41881. if( rc==SQLITE_OK ){
  41882. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  41883. }
  41884. }
  41885. }
  41886. walcheckpoint_out:
  41887. walIteratorFree(pIter);
  41888. return rc;
  41889. }
  41890. /*
  41891. ** Close a connection to a log file.
  41892. */
  41893. SQLITE_PRIVATE int sqlite3WalClose(
  41894. Wal *pWal, /* Wal to close */
  41895. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  41896. int nBuf,
  41897. u8 *zBuf /* Buffer of at least nBuf bytes */
  41898. ){
  41899. int rc = SQLITE_OK;
  41900. if( pWal ){
  41901. int isDelete = 0; /* True to unlink wal and wal-index files */
  41902. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  41903. ** ordinary, rollback-mode locking methods, this guarantees that the
  41904. ** connection associated with this log file is the only connection to
  41905. ** the database. In this case checkpoint the database and unlink both
  41906. ** the wal and wal-index files.
  41907. **
  41908. ** The EXCLUSIVE lock is not released before returning.
  41909. */
  41910. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  41911. if( rc==SQLITE_OK ){
  41912. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  41913. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  41914. }
  41915. rc = sqlite3WalCheckpoint(
  41916. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  41917. );
  41918. if( rc==SQLITE_OK ){
  41919. isDelete = 1;
  41920. }
  41921. }
  41922. walIndexClose(pWal, isDelete);
  41923. sqlite3OsClose(pWal->pWalFd);
  41924. if( isDelete ){
  41925. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  41926. }
  41927. WALTRACE(("WAL%p: closed\n", pWal));
  41928. sqlite3_free((void *)pWal->apWiData);
  41929. sqlite3_free(pWal);
  41930. }
  41931. return rc;
  41932. }
  41933. /*
  41934. ** Try to read the wal-index header. Return 0 on success and 1 if
  41935. ** there is a problem.
  41936. **
  41937. ** The wal-index is in shared memory. Another thread or process might
  41938. ** be writing the header at the same time this procedure is trying to
  41939. ** read it, which might result in inconsistency. A dirty read is detected
  41940. ** by verifying that both copies of the header are the same and also by
  41941. ** a checksum on the header.
  41942. **
  41943. ** If and only if the read is consistent and the header is different from
  41944. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  41945. ** and *pChanged is set to 1.
  41946. **
  41947. ** If the checksum cannot be verified return non-zero. If the header
  41948. ** is read successfully and the checksum verified, return zero.
  41949. */
  41950. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  41951. u32 aCksum[2]; /* Checksum on the header content */
  41952. WalIndexHdr h1, h2; /* Two copies of the header content */
  41953. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  41954. /* The first page of the wal-index must be mapped at this point. */
  41955. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  41956. /* Read the header. This might happen concurrently with a write to the
  41957. ** same area of shared memory on a different CPU in a SMP,
  41958. ** meaning it is possible that an inconsistent snapshot is read
  41959. ** from the file. If this happens, return non-zero.
  41960. **
  41961. ** There are two copies of the header at the beginning of the wal-index.
  41962. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  41963. ** Memory barriers are used to prevent the compiler or the hardware from
  41964. ** reordering the reads and writes.
  41965. */
  41966. aHdr = walIndexHdr(pWal);
  41967. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  41968. walShmBarrier(pWal);
  41969. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  41970. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  41971. return 1; /* Dirty read */
  41972. }
  41973. if( h1.isInit==0 ){
  41974. return 1; /* Malformed header - probably all zeros */
  41975. }
  41976. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  41977. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  41978. return 1; /* Checksum does not match */
  41979. }
  41980. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  41981. *pChanged = 1;
  41982. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  41983. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  41984. testcase( pWal->szPage<=32768 );
  41985. testcase( pWal->szPage>=65536 );
  41986. }
  41987. /* The header was successfully read. Return zero. */
  41988. return 0;
  41989. }
  41990. /*
  41991. ** Read the wal-index header from the wal-index and into pWal->hdr.
  41992. ** If the wal-header appears to be corrupt, try to reconstruct the
  41993. ** wal-index from the WAL before returning.
  41994. **
  41995. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  41996. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  41997. ** to 0.
  41998. **
  41999. ** If the wal-index header is successfully read, return SQLITE_OK.
  42000. ** Otherwise an SQLite error code.
  42001. */
  42002. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  42003. int rc; /* Return code */
  42004. int badHdr; /* True if a header read failed */
  42005. volatile u32 *page0; /* Chunk of wal-index containing header */
  42006. /* Ensure that page 0 of the wal-index (the page that contains the
  42007. ** wal-index header) is mapped. Return early if an error occurs here.
  42008. */
  42009. assert( pChanged );
  42010. rc = walIndexPage(pWal, 0, &page0);
  42011. if( rc!=SQLITE_OK ){
  42012. return rc;
  42013. };
  42014. assert( page0 || pWal->writeLock==0 );
  42015. /* If the first page of the wal-index has been mapped, try to read the
  42016. ** wal-index header immediately, without holding any lock. This usually
  42017. ** works, but may fail if the wal-index header is corrupt or currently
  42018. ** being modified by another thread or process.
  42019. */
  42020. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  42021. /* If the first attempt failed, it might have been due to a race
  42022. ** with a writer. So get a WRITE lock and try again.
  42023. */
  42024. assert( badHdr==0 || pWal->writeLock==0 );
  42025. if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  42026. pWal->writeLock = 1;
  42027. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  42028. badHdr = walIndexTryHdr(pWal, pChanged);
  42029. if( badHdr ){
  42030. /* If the wal-index header is still malformed even while holding
  42031. ** a WRITE lock, it can only mean that the header is corrupted and
  42032. ** needs to be reconstructed. So run recovery to do exactly that.
  42033. */
  42034. rc = walIndexRecover(pWal);
  42035. *pChanged = 1;
  42036. }
  42037. }
  42038. pWal->writeLock = 0;
  42039. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  42040. }
  42041. /* If the header is read successfully, check the version number to make
  42042. ** sure the wal-index was not constructed with some future format that
  42043. ** this version of SQLite cannot understand.
  42044. */
  42045. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  42046. rc = SQLITE_CANTOPEN_BKPT;
  42047. }
  42048. return rc;
  42049. }
  42050. /*
  42051. ** This is the value that walTryBeginRead returns when it needs to
  42052. ** be retried.
  42053. */
  42054. #define WAL_RETRY (-1)
  42055. /*
  42056. ** Attempt to start a read transaction. This might fail due to a race or
  42057. ** other transient condition. When that happens, it returns WAL_RETRY to
  42058. ** indicate to the caller that it is safe to retry immediately.
  42059. **
  42060. ** On success return SQLITE_OK. On a permanent failure (such an
  42061. ** I/O error or an SQLITE_BUSY because another process is running
  42062. ** recovery) return a positive error code.
  42063. **
  42064. ** The useWal parameter is true to force the use of the WAL and disable
  42065. ** the case where the WAL is bypassed because it has been completely
  42066. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  42067. ** to make a copy of the wal-index header into pWal->hdr. If the
  42068. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  42069. ** to the caller that the local paget cache is obsolete and needs to be
  42070. ** flushed.) When useWal==1, the wal-index header is assumed to already
  42071. ** be loaded and the pChanged parameter is unused.
  42072. **
  42073. ** The caller must set the cnt parameter to the number of prior calls to
  42074. ** this routine during the current read attempt that returned WAL_RETRY.
  42075. ** This routine will start taking more aggressive measures to clear the
  42076. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  42077. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  42078. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  42079. ** and is not honoring the locking protocol. There is a vanishingly small
  42080. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  42081. ** bad luck when there is lots of contention for the wal-index, but that
  42082. ** possibility is so small that it can be safely neglected, we believe.
  42083. **
  42084. ** On success, this routine obtains a read lock on
  42085. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  42086. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  42087. ** that means the Wal does not hold any read lock. The reader must not
  42088. ** access any database page that is modified by a WAL frame up to and
  42089. ** including frame number aReadMark[pWal->readLock]. The reader will
  42090. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  42091. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  42092. ** completely and get all content directly from the database file.
  42093. ** If the useWal parameter is 1 then the WAL will never be ignored and
  42094. ** this routine will always set pWal->readLock>0 on success.
  42095. ** When the read transaction is completed, the caller must release the
  42096. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  42097. **
  42098. ** This routine uses the nBackfill and aReadMark[] fields of the header
  42099. ** to select a particular WAL_READ_LOCK() that strives to let the
  42100. ** checkpoint process do as much work as possible. This routine might
  42101. ** update values of the aReadMark[] array in the header, but if it does
  42102. ** so it takes care to hold an exclusive lock on the corresponding
  42103. ** WAL_READ_LOCK() while changing values.
  42104. */
  42105. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  42106. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  42107. u32 mxReadMark; /* Largest aReadMark[] value */
  42108. int mxI; /* Index of largest aReadMark[] value */
  42109. int i; /* Loop counter */
  42110. int rc = SQLITE_OK; /* Return code */
  42111. assert( pWal->readLock<0 ); /* Not currently locked */
  42112. /* Take steps to avoid spinning forever if there is a protocol error.
  42113. **
  42114. ** Circumstances that cause a RETRY should only last for the briefest
  42115. ** instances of time. No I/O or other system calls are done while the
  42116. ** locks are held, so the locks should not be held for very long. But
  42117. ** if we are unlucky, another process that is holding a lock might get
  42118. ** paged out or take a page-fault that is time-consuming to resolve,
  42119. ** during the few nanoseconds that it is holding the lock. In that case,
  42120. ** it might take longer than normal for the lock to free.
  42121. **
  42122. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  42123. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  42124. ** is more of a scheduler yield than an actual delay. But on the 10th
  42125. ** an subsequent retries, the delays start becoming longer and longer,
  42126. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  42127. ** The total delay time before giving up is less than 1 second.
  42128. */
  42129. if( cnt>5 ){
  42130. int nDelay = 1; /* Pause time in microseconds */
  42131. if( cnt>100 ){
  42132. VVA_ONLY( pWal->lockError = 1; )
  42133. return SQLITE_PROTOCOL;
  42134. }
  42135. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  42136. sqlite3OsSleep(pWal->pVfs, nDelay);
  42137. }
  42138. if( !useWal ){
  42139. rc = walIndexReadHdr(pWal, pChanged);
  42140. if( rc==SQLITE_BUSY ){
  42141. /* If there is not a recovery running in another thread or process
  42142. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  42143. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  42144. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  42145. ** would be technically correct. But the race is benign since with
  42146. ** WAL_RETRY this routine will be called again and will probably be
  42147. ** right on the second iteration.
  42148. */
  42149. if( pWal->apWiData[0]==0 ){
  42150. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  42151. ** We assume this is a transient condition, so return WAL_RETRY. The
  42152. ** xShmMap() implementation used by the default unix and win32 VFS
  42153. ** modules may return SQLITE_BUSY due to a race condition in the
  42154. ** code that determines whether or not the shared-memory region
  42155. ** must be zeroed before the requested page is returned.
  42156. */
  42157. rc = WAL_RETRY;
  42158. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  42159. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  42160. rc = WAL_RETRY;
  42161. }else if( rc==SQLITE_BUSY ){
  42162. rc = SQLITE_BUSY_RECOVERY;
  42163. }
  42164. }
  42165. if( rc!=SQLITE_OK ){
  42166. return rc;
  42167. }
  42168. }
  42169. pInfo = walCkptInfo(pWal);
  42170. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  42171. /* The WAL has been completely backfilled (or it is empty).
  42172. ** and can be safely ignored.
  42173. */
  42174. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  42175. walShmBarrier(pWal);
  42176. if( rc==SQLITE_OK ){
  42177. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  42178. /* It is not safe to allow the reader to continue here if frames
  42179. ** may have been appended to the log before READ_LOCK(0) was obtained.
  42180. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  42181. ** which implies that the database file contains a trustworthy
  42182. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  42183. ** happening, this is usually correct.
  42184. **
  42185. ** However, if frames have been appended to the log (or if the log
  42186. ** is wrapped and written for that matter) before the READ_LOCK(0)
  42187. ** is obtained, that is not necessarily true. A checkpointer may
  42188. ** have started to backfill the appended frames but crashed before
  42189. ** it finished. Leaving a corrupt image in the database file.
  42190. */
  42191. walUnlockShared(pWal, WAL_READ_LOCK(0));
  42192. return WAL_RETRY;
  42193. }
  42194. pWal->readLock = 0;
  42195. return SQLITE_OK;
  42196. }else if( rc!=SQLITE_BUSY ){
  42197. return rc;
  42198. }
  42199. }
  42200. /* If we get this far, it means that the reader will want to use
  42201. ** the WAL to get at content from recent commits. The job now is
  42202. ** to select one of the aReadMark[] entries that is closest to
  42203. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  42204. */
  42205. mxReadMark = 0;
  42206. mxI = 0;
  42207. for(i=1; i<WAL_NREADER; i++){
  42208. u32 thisMark = pInfo->aReadMark[i];
  42209. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  42210. assert( thisMark!=READMARK_NOT_USED );
  42211. mxReadMark = thisMark;
  42212. mxI = i;
  42213. }
  42214. }
  42215. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  42216. {
  42217. if( mxReadMark < pWal->hdr.mxFrame || mxI==0 ){
  42218. for(i=1; i<WAL_NREADER; i++){
  42219. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  42220. if( rc==SQLITE_OK ){
  42221. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  42222. mxI = i;
  42223. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  42224. break;
  42225. }else if( rc!=SQLITE_BUSY ){
  42226. return rc;
  42227. }
  42228. }
  42229. }
  42230. if( mxI==0 ){
  42231. assert( rc==SQLITE_BUSY );
  42232. return WAL_RETRY;
  42233. }
  42234. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  42235. if( rc ){
  42236. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  42237. }
  42238. /* Now that the read-lock has been obtained, check that neither the
  42239. ** value in the aReadMark[] array or the contents of the wal-index
  42240. ** header have changed.
  42241. **
  42242. ** It is necessary to check that the wal-index header did not change
  42243. ** between the time it was read and when the shared-lock was obtained
  42244. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  42245. ** that the log file may have been wrapped by a writer, or that frames
  42246. ** that occur later in the log than pWal->hdr.mxFrame may have been
  42247. ** copied into the database by a checkpointer. If either of these things
  42248. ** happened, then reading the database with the current value of
  42249. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  42250. ** instead.
  42251. **
  42252. ** This does not guarantee that the copy of the wal-index header is up to
  42253. ** date before proceeding. That would not be possible without somehow
  42254. ** blocking writers. It only guarantees that a dangerous checkpoint or
  42255. ** log-wrap (either of which would require an exclusive lock on
  42256. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  42257. */
  42258. walShmBarrier(pWal);
  42259. if( pInfo->aReadMark[mxI]!=mxReadMark
  42260. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  42261. ){
  42262. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  42263. return WAL_RETRY;
  42264. }else{
  42265. assert( mxReadMark<=pWal->hdr.mxFrame );
  42266. pWal->readLock = (i16)mxI;
  42267. }
  42268. }
  42269. return rc;
  42270. }
  42271. /*
  42272. ** Begin a read transaction on the database.
  42273. **
  42274. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  42275. ** it takes a snapshot of the state of the WAL and wal-index for the current
  42276. ** instant in time. The current thread will continue to use this snapshot.
  42277. ** Other threads might append new content to the WAL and wal-index but
  42278. ** that extra content is ignored by the current thread.
  42279. **
  42280. ** If the database contents have changes since the previous read
  42281. ** transaction, then *pChanged is set to 1 before returning. The
  42282. ** Pager layer will use this to know that is cache is stale and
  42283. ** needs to be flushed.
  42284. */
  42285. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  42286. int rc; /* Return code */
  42287. int cnt = 0; /* Number of TryBeginRead attempts */
  42288. do{
  42289. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  42290. }while( rc==WAL_RETRY );
  42291. testcase( (rc&0xff)==SQLITE_BUSY );
  42292. testcase( (rc&0xff)==SQLITE_IOERR );
  42293. testcase( rc==SQLITE_PROTOCOL );
  42294. testcase( rc==SQLITE_OK );
  42295. return rc;
  42296. }
  42297. /*
  42298. ** Finish with a read transaction. All this does is release the
  42299. ** read-lock.
  42300. */
  42301. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  42302. sqlite3WalEndWriteTransaction(pWal);
  42303. if( pWal->readLock>=0 ){
  42304. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  42305. pWal->readLock = -1;
  42306. }
  42307. }
  42308. /*
  42309. ** Read a page from the WAL, if it is present in the WAL and if the
  42310. ** current read transaction is configured to use the WAL.
  42311. **
  42312. ** The *pInWal is set to 1 if the requested page is in the WAL and
  42313. ** has been loaded. Or *pInWal is set to 0 if the page was not in
  42314. ** the WAL and needs to be read out of the database.
  42315. */
  42316. SQLITE_PRIVATE int sqlite3WalRead(
  42317. Wal *pWal, /* WAL handle */
  42318. Pgno pgno, /* Database page number to read data for */
  42319. int *pInWal, /* OUT: True if data is read from WAL */
  42320. int nOut, /* Size of buffer pOut in bytes */
  42321. u8 *pOut /* Buffer to write page data to */
  42322. ){
  42323. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  42324. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  42325. int iHash; /* Used to loop through N hash tables */
  42326. /* This routine is only be called from within a read transaction. */
  42327. assert( pWal->readLock>=0 || pWal->lockError );
  42328. /* If the "last page" field of the wal-index header snapshot is 0, then
  42329. ** no data will be read from the wal under any circumstances. Return early
  42330. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  42331. ** then the WAL is ignored by the reader so return early, as if the
  42332. ** WAL were empty.
  42333. */
  42334. if( iLast==0 || pWal->readLock==0 ){
  42335. *pInWal = 0;
  42336. return SQLITE_OK;
  42337. }
  42338. /* Search the hash table or tables for an entry matching page number
  42339. ** pgno. Each iteration of the following for() loop searches one
  42340. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  42341. **
  42342. ** This code might run concurrently to the code in walIndexAppend()
  42343. ** that adds entries to the wal-index (and possibly to this hash
  42344. ** table). This means the value just read from the hash
  42345. ** slot (aHash[iKey]) may have been added before or after the
  42346. ** current read transaction was opened. Values added after the
  42347. ** read transaction was opened may have been written incorrectly -
  42348. ** i.e. these slots may contain garbage data. However, we assume
  42349. ** that any slots written before the current read transaction was
  42350. ** opened remain unmodified.
  42351. **
  42352. ** For the reasons above, the if(...) condition featured in the inner
  42353. ** loop of the following block is more stringent that would be required
  42354. ** if we had exclusive access to the hash-table:
  42355. **
  42356. ** (aPgno[iFrame]==pgno):
  42357. ** This condition filters out normal hash-table collisions.
  42358. **
  42359. ** (iFrame<=iLast):
  42360. ** This condition filters out entries that were added to the hash
  42361. ** table after the current read-transaction had started.
  42362. */
  42363. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  42364. volatile ht_slot *aHash; /* Pointer to hash table */
  42365. volatile u32 *aPgno; /* Pointer to array of page numbers */
  42366. u32 iZero; /* Frame number corresponding to aPgno[0] */
  42367. int iKey; /* Hash slot index */
  42368. int nCollide; /* Number of hash collisions remaining */
  42369. int rc; /* Error code */
  42370. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  42371. if( rc!=SQLITE_OK ){
  42372. return rc;
  42373. }
  42374. nCollide = HASHTABLE_NSLOT;
  42375. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  42376. u32 iFrame = aHash[iKey] + iZero;
  42377. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  42378. assert( iFrame>iRead );
  42379. iRead = iFrame;
  42380. }
  42381. if( (nCollide--)==0 ){
  42382. return SQLITE_CORRUPT_BKPT;
  42383. }
  42384. }
  42385. }
  42386. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  42387. /* If expensive assert() statements are available, do a linear search
  42388. ** of the wal-index file content. Make sure the results agree with the
  42389. ** result obtained using the hash indexes above. */
  42390. {
  42391. u32 iRead2 = 0;
  42392. u32 iTest;
  42393. for(iTest=iLast; iTest>0; iTest--){
  42394. if( walFramePgno(pWal, iTest)==pgno ){
  42395. iRead2 = iTest;
  42396. break;
  42397. }
  42398. }
  42399. assert( iRead==iRead2 );
  42400. }
  42401. #endif
  42402. /* If iRead is non-zero, then it is the log frame number that contains the
  42403. ** required page. Read and return data from the log file.
  42404. */
  42405. if( iRead ){
  42406. int sz;
  42407. i64 iOffset;
  42408. sz = pWal->hdr.szPage;
  42409. sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  42410. testcase( sz<=32768 );
  42411. testcase( sz>=65536 );
  42412. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  42413. *pInWal = 1;
  42414. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  42415. return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
  42416. }
  42417. *pInWal = 0;
  42418. return SQLITE_OK;
  42419. }
  42420. /*
  42421. ** Return the size of the database in pages (or zero, if unknown).
  42422. */
  42423. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  42424. if( pWal && ALWAYS(pWal->readLock>=0) ){
  42425. return pWal->hdr.nPage;
  42426. }
  42427. return 0;
  42428. }
  42429. /*
  42430. ** This function starts a write transaction on the WAL.
  42431. **
  42432. ** A read transaction must have already been started by a prior call
  42433. ** to sqlite3WalBeginReadTransaction().
  42434. **
  42435. ** If another thread or process has written into the database since
  42436. ** the read transaction was started, then it is not possible for this
  42437. ** thread to write as doing so would cause a fork. So this routine
  42438. ** returns SQLITE_BUSY in that case and no write transaction is started.
  42439. **
  42440. ** There can only be a single writer active at a time.
  42441. */
  42442. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  42443. int rc;
  42444. /* Cannot start a write transaction without first holding a read
  42445. ** transaction. */
  42446. assert( pWal->readLock>=0 );
  42447. if( pWal->readOnly ){
  42448. return SQLITE_READONLY;
  42449. }
  42450. /* Only one writer allowed at a time. Get the write lock. Return
  42451. ** SQLITE_BUSY if unable.
  42452. */
  42453. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  42454. if( rc ){
  42455. return rc;
  42456. }
  42457. pWal->writeLock = 1;
  42458. /* If another connection has written to the database file since the
  42459. ** time the read transaction on this connection was started, then
  42460. ** the write is disallowed.
  42461. */
  42462. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  42463. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  42464. pWal->writeLock = 0;
  42465. rc = SQLITE_BUSY;
  42466. }
  42467. return rc;
  42468. }
  42469. /*
  42470. ** End a write transaction. The commit has already been done. This
  42471. ** routine merely releases the lock.
  42472. */
  42473. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  42474. if( pWal->writeLock ){
  42475. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  42476. pWal->writeLock = 0;
  42477. }
  42478. return SQLITE_OK;
  42479. }
  42480. /*
  42481. ** If any data has been written (but not committed) to the log file, this
  42482. ** function moves the write-pointer back to the start of the transaction.
  42483. **
  42484. ** Additionally, the callback function is invoked for each frame written
  42485. ** to the WAL since the start of the transaction. If the callback returns
  42486. ** other than SQLITE_OK, it is not invoked again and the error code is
  42487. ** returned to the caller.
  42488. **
  42489. ** Otherwise, if the callback function does not return an error, this
  42490. ** function returns SQLITE_OK.
  42491. */
  42492. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  42493. int rc = SQLITE_OK;
  42494. if( ALWAYS(pWal->writeLock) ){
  42495. Pgno iMax = pWal->hdr.mxFrame;
  42496. Pgno iFrame;
  42497. /* Restore the clients cache of the wal-index header to the state it
  42498. ** was in before the client began writing to the database.
  42499. */
  42500. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  42501. for(iFrame=pWal->hdr.mxFrame+1;
  42502. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  42503. iFrame++
  42504. ){
  42505. /* This call cannot fail. Unless the page for which the page number
  42506. ** is passed as the second argument is (a) in the cache and
  42507. ** (b) has an outstanding reference, then xUndo is either a no-op
  42508. ** (if (a) is false) or simply expels the page from the cache (if (b)
  42509. ** is false).
  42510. **
  42511. ** If the upper layer is doing a rollback, it is guaranteed that there
  42512. ** are no outstanding references to any page other than page 1. And
  42513. ** page 1 is never written to the log until the transaction is
  42514. ** committed. As a result, the call to xUndo may not fail.
  42515. */
  42516. assert( walFramePgno(pWal, iFrame)!=1 );
  42517. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  42518. }
  42519. walCleanupHash(pWal);
  42520. }
  42521. assert( rc==SQLITE_OK );
  42522. return rc;
  42523. }
  42524. /*
  42525. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  42526. ** values. This function populates the array with values required to
  42527. ** "rollback" the write position of the WAL handle back to the current
  42528. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  42529. */
  42530. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  42531. assert( pWal->writeLock );
  42532. aWalData[0] = pWal->hdr.mxFrame;
  42533. aWalData[1] = pWal->hdr.aFrameCksum[0];
  42534. aWalData[2] = pWal->hdr.aFrameCksum[1];
  42535. aWalData[3] = pWal->nCkpt;
  42536. }
  42537. /*
  42538. ** Move the write position of the WAL back to the point identified by
  42539. ** the values in the aWalData[] array. aWalData must point to an array
  42540. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  42541. ** by a call to WalSavepoint().
  42542. */
  42543. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  42544. int rc = SQLITE_OK;
  42545. assert( pWal->writeLock );
  42546. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  42547. if( aWalData[3]!=pWal->nCkpt ){
  42548. /* This savepoint was opened immediately after the write-transaction
  42549. ** was started. Right after that, the writer decided to wrap around
  42550. ** to the start of the log. Update the savepoint values to match.
  42551. */
  42552. aWalData[0] = 0;
  42553. aWalData[3] = pWal->nCkpt;
  42554. }
  42555. if( aWalData[0]<pWal->hdr.mxFrame ){
  42556. pWal->hdr.mxFrame = aWalData[0];
  42557. pWal->hdr.aFrameCksum[0] = aWalData[1];
  42558. pWal->hdr.aFrameCksum[1] = aWalData[2];
  42559. walCleanupHash(pWal);
  42560. }
  42561. return rc;
  42562. }
  42563. /*
  42564. ** This function is called just before writing a set of frames to the log
  42565. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  42566. ** to the current log file, it is possible to overwrite the start of the
  42567. ** existing log file with the new frames (i.e. "reset" the log). If so,
  42568. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  42569. ** unchanged.
  42570. **
  42571. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  42572. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  42573. ** if an error occurs.
  42574. */
  42575. static int walRestartLog(Wal *pWal){
  42576. int rc = SQLITE_OK;
  42577. int cnt;
  42578. if( pWal->readLock==0 ){
  42579. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  42580. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  42581. if( pInfo->nBackfill>0 ){
  42582. u32 salt1;
  42583. sqlite3_randomness(4, &salt1);
  42584. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  42585. if( rc==SQLITE_OK ){
  42586. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  42587. ** readers are currently using the WAL), then the transactions
  42588. ** frames will overwrite the start of the existing log. Update the
  42589. ** wal-index header to reflect this.
  42590. **
  42591. ** In theory it would be Ok to update the cache of the header only
  42592. ** at this point. But updating the actual wal-index header is also
  42593. ** safe and means there is no special case for sqlite3WalUndo()
  42594. ** to handle if this transaction is rolled back.
  42595. */
  42596. int i; /* Loop counter */
  42597. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  42598. pWal->nCkpt++;
  42599. pWal->hdr.mxFrame = 0;
  42600. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  42601. aSalt[1] = salt1;
  42602. walIndexWriteHdr(pWal);
  42603. pInfo->nBackfill = 0;
  42604. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  42605. assert( pInfo->aReadMark[0]==0 );
  42606. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  42607. }else if( rc!=SQLITE_BUSY ){
  42608. return rc;
  42609. }
  42610. }
  42611. walUnlockShared(pWal, WAL_READ_LOCK(0));
  42612. pWal->readLock = -1;
  42613. cnt = 0;
  42614. do{
  42615. int notUsed;
  42616. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  42617. }while( rc==WAL_RETRY );
  42618. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  42619. testcase( (rc&0xff)==SQLITE_IOERR );
  42620. testcase( rc==SQLITE_PROTOCOL );
  42621. testcase( rc==SQLITE_OK );
  42622. }
  42623. return rc;
  42624. }
  42625. /*
  42626. ** Write a set of frames to the log. The caller must hold the write-lock
  42627. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  42628. */
  42629. SQLITE_PRIVATE int sqlite3WalFrames(
  42630. Wal *pWal, /* Wal handle to write to */
  42631. int szPage, /* Database page-size in bytes */
  42632. PgHdr *pList, /* List of dirty pages to write */
  42633. Pgno nTruncate, /* Database size after this commit */
  42634. int isCommit, /* True if this is a commit */
  42635. int sync_flags /* Flags to pass to OsSync() (or 0) */
  42636. ){
  42637. int rc; /* Used to catch return codes */
  42638. u32 iFrame; /* Next frame address */
  42639. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  42640. PgHdr *p; /* Iterator to run through pList with. */
  42641. PgHdr *pLast = 0; /* Last frame in list */
  42642. int nLast = 0; /* Number of extra copies of last page */
  42643. assert( pList );
  42644. assert( pWal->writeLock );
  42645. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  42646. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  42647. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  42648. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  42649. }
  42650. #endif
  42651. /* See if it is possible to write these frames into the start of the
  42652. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  42653. */
  42654. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  42655. return rc;
  42656. }
  42657. /* If this is the first frame written into the log, write the WAL
  42658. ** header to the start of the WAL file. See comments at the top of
  42659. ** this source file for a description of the WAL header format.
  42660. */
  42661. iFrame = pWal->hdr.mxFrame;
  42662. if( iFrame==0 ){
  42663. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  42664. u32 aCksum[2]; /* Checksum for wal-header */
  42665. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  42666. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  42667. sqlite3Put4byte(&aWalHdr[8], szPage);
  42668. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  42669. sqlite3_randomness(8, pWal->hdr.aSalt);
  42670. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  42671. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  42672. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  42673. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  42674. pWal->szPage = szPage;
  42675. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  42676. pWal->hdr.aFrameCksum[0] = aCksum[0];
  42677. pWal->hdr.aFrameCksum[1] = aCksum[1];
  42678. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  42679. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  42680. if( rc!=SQLITE_OK ){
  42681. return rc;
  42682. }
  42683. }
  42684. assert( (int)pWal->szPage==szPage );
  42685. /* Write the log file. */
  42686. for(p=pList; p; p=p->pDirty){
  42687. u32 nDbsize; /* Db-size field for frame header */
  42688. i64 iOffset; /* Write offset in log file */
  42689. void *pData;
  42690. iOffset = walFrameOffset(++iFrame, szPage);
  42691. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  42692. /* Populate and write the frame header */
  42693. nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  42694. #if defined(SQLITE_HAS_CODEC)
  42695. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  42696. #else
  42697. pData = p->pData;
  42698. #endif
  42699. walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
  42700. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
  42701. if( rc!=SQLITE_OK ){
  42702. return rc;
  42703. }
  42704. /* Write the page data */
  42705. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
  42706. if( rc!=SQLITE_OK ){
  42707. return rc;
  42708. }
  42709. pLast = p;
  42710. }
  42711. /* Sync the log file if the 'isSync' flag was specified. */
  42712. if( sync_flags ){
  42713. i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
  42714. i64 iOffset = walFrameOffset(iFrame+1, szPage);
  42715. assert( isCommit );
  42716. assert( iSegment>0 );
  42717. iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
  42718. while( iOffset<iSegment ){
  42719. void *pData;
  42720. #if defined(SQLITE_HAS_CODEC)
  42721. if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
  42722. #else
  42723. pData = pLast->pData;
  42724. #endif
  42725. walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
  42726. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  42727. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
  42728. if( rc!=SQLITE_OK ){
  42729. return rc;
  42730. }
  42731. iOffset += WAL_FRAME_HDRSIZE;
  42732. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
  42733. if( rc!=SQLITE_OK ){
  42734. return rc;
  42735. }
  42736. nLast++;
  42737. iOffset += szPage;
  42738. }
  42739. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  42740. }
  42741. /* Append data to the wal-index. It is not necessary to lock the
  42742. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  42743. ** guarantees that there are no other writers, and no data that may
  42744. ** be in use by existing readers is being overwritten.
  42745. */
  42746. iFrame = pWal->hdr.mxFrame;
  42747. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  42748. iFrame++;
  42749. rc = walIndexAppend(pWal, iFrame, p->pgno);
  42750. }
  42751. while( nLast>0 && rc==SQLITE_OK ){
  42752. iFrame++;
  42753. nLast--;
  42754. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  42755. }
  42756. if( rc==SQLITE_OK ){
  42757. /* Update the private copy of the header. */
  42758. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  42759. testcase( szPage<=32768 );
  42760. testcase( szPage>=65536 );
  42761. pWal->hdr.mxFrame = iFrame;
  42762. if( isCommit ){
  42763. pWal->hdr.iChange++;
  42764. pWal->hdr.nPage = nTruncate;
  42765. }
  42766. /* If this is a commit, update the wal-index header too. */
  42767. if( isCommit ){
  42768. walIndexWriteHdr(pWal);
  42769. pWal->iCallback = iFrame;
  42770. }
  42771. }
  42772. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  42773. return rc;
  42774. }
  42775. /*
  42776. ** This routine is called to implement sqlite3_wal_checkpoint() and
  42777. ** related interfaces.
  42778. **
  42779. ** Obtain a CHECKPOINT lock and then backfill as much information as
  42780. ** we can from WAL into the database.
  42781. **
  42782. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  42783. ** callback. In this case this function runs a blocking checkpoint.
  42784. */
  42785. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  42786. Wal *pWal, /* Wal connection */
  42787. int eMode, /* PASSIVE, FULL or RESTART */
  42788. int (*xBusy)(void*), /* Function to call when busy */
  42789. void *pBusyArg, /* Context argument for xBusyHandler */
  42790. int sync_flags, /* Flags to sync db file with (or 0) */
  42791. int nBuf, /* Size of temporary buffer */
  42792. u8 *zBuf, /* Temporary buffer to use */
  42793. int *pnLog, /* OUT: Number of frames in WAL */
  42794. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  42795. ){
  42796. int rc; /* Return code */
  42797. int isChanged = 0; /* True if a new wal-index header is loaded */
  42798. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  42799. assert( pWal->ckptLock==0 );
  42800. assert( pWal->writeLock==0 );
  42801. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  42802. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  42803. if( rc ){
  42804. /* Usually this is SQLITE_BUSY meaning that another thread or process
  42805. ** is already running a checkpoint, or maybe a recovery. But it might
  42806. ** also be SQLITE_IOERR. */
  42807. return rc;
  42808. }
  42809. pWal->ckptLock = 1;
  42810. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  42811. ** to prevent any writers from running while the checkpoint is underway.
  42812. ** This has to be done before the call to walIndexReadHdr() below.
  42813. **
  42814. ** If the writer lock cannot be obtained, then a passive checkpoint is
  42815. ** run instead. Since the checkpointer is not holding the writer lock,
  42816. ** there is no point in blocking waiting for any readers. Assuming no
  42817. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  42818. */
  42819. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  42820. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  42821. if( rc==SQLITE_OK ){
  42822. pWal->writeLock = 1;
  42823. }else if( rc==SQLITE_BUSY ){
  42824. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  42825. rc = SQLITE_OK;
  42826. }
  42827. }
  42828. /* Read the wal-index header. */
  42829. if( rc==SQLITE_OK ){
  42830. rc = walIndexReadHdr(pWal, &isChanged);
  42831. }
  42832. /* Copy data from the log to the database file. */
  42833. if( rc==SQLITE_OK ){
  42834. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  42835. rc = SQLITE_CORRUPT_BKPT;
  42836. }else{
  42837. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  42838. }
  42839. /* If no error occurred, set the output variables. */
  42840. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  42841. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  42842. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  42843. }
  42844. }
  42845. if( isChanged ){
  42846. /* If a new wal-index header was loaded before the checkpoint was
  42847. ** performed, then the pager-cache associated with pWal is now
  42848. ** out of date. So zero the cached wal-index header to ensure that
  42849. ** next time the pager opens a snapshot on this database it knows that
  42850. ** the cache needs to be reset.
  42851. */
  42852. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  42853. }
  42854. /* Release the locks. */
  42855. sqlite3WalEndWriteTransaction(pWal);
  42856. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  42857. pWal->ckptLock = 0;
  42858. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  42859. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  42860. }
  42861. /* Return the value to pass to a sqlite3_wal_hook callback, the
  42862. ** number of frames in the WAL at the point of the last commit since
  42863. ** sqlite3WalCallback() was called. If no commits have occurred since
  42864. ** the last call, then return 0.
  42865. */
  42866. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  42867. u32 ret = 0;
  42868. if( pWal ){
  42869. ret = pWal->iCallback;
  42870. pWal->iCallback = 0;
  42871. }
  42872. return (int)ret;
  42873. }
  42874. /*
  42875. ** This function is called to change the WAL subsystem into or out
  42876. ** of locking_mode=EXCLUSIVE.
  42877. **
  42878. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  42879. ** into locking_mode=NORMAL. This means that we must acquire a lock
  42880. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  42881. ** or if the acquisition of the lock fails, then return 0. If the
  42882. ** transition out of exclusive-mode is successful, return 1. This
  42883. ** operation must occur while the pager is still holding the exclusive
  42884. ** lock on the main database file.
  42885. **
  42886. ** If op is one, then change from locking_mode=NORMAL into
  42887. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  42888. ** be released. Return 1 if the transition is made and 0 if the
  42889. ** WAL is already in exclusive-locking mode - meaning that this
  42890. ** routine is a no-op. The pager must already hold the exclusive lock
  42891. ** on the main database file before invoking this operation.
  42892. **
  42893. ** If op is negative, then do a dry-run of the op==1 case but do
  42894. ** not actually change anything. The pager uses this to see if it
  42895. ** should acquire the database exclusive lock prior to invoking
  42896. ** the op==1 case.
  42897. */
  42898. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  42899. int rc;
  42900. assert( pWal->writeLock==0 );
  42901. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  42902. /* pWal->readLock is usually set, but might be -1 if there was a
  42903. ** prior error while attempting to acquire are read-lock. This cannot
  42904. ** happen if the connection is actually in exclusive mode (as no xShmLock
  42905. ** locks are taken in this case). Nor should the pager attempt to
  42906. ** upgrade to exclusive-mode following such an error.
  42907. */
  42908. assert( pWal->readLock>=0 || pWal->lockError );
  42909. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  42910. if( op==0 ){
  42911. if( pWal->exclusiveMode ){
  42912. pWal->exclusiveMode = 0;
  42913. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  42914. pWal->exclusiveMode = 1;
  42915. }
  42916. rc = pWal->exclusiveMode==0;
  42917. }else{
  42918. /* Already in locking_mode=NORMAL */
  42919. rc = 0;
  42920. }
  42921. }else if( op>0 ){
  42922. assert( pWal->exclusiveMode==0 );
  42923. assert( pWal->readLock>=0 );
  42924. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  42925. pWal->exclusiveMode = 1;
  42926. rc = 1;
  42927. }else{
  42928. rc = pWal->exclusiveMode==0;
  42929. }
  42930. return rc;
  42931. }
  42932. /*
  42933. ** Return true if the argument is non-NULL and the WAL module is using
  42934. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  42935. ** WAL module is using shared-memory, return false.
  42936. */
  42937. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  42938. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  42939. }
  42940. #endif /* #ifndef SQLITE_OMIT_WAL */
  42941. /************** End of wal.c *************************************************/
  42942. /************** Begin file btmutex.c *****************************************/
  42943. /*
  42944. ** 2007 August 27
  42945. **
  42946. ** The author disclaims copyright to this source code. In place of
  42947. ** a legal notice, here is a blessing:
  42948. **
  42949. ** May you do good and not evil.
  42950. ** May you find forgiveness for yourself and forgive others.
  42951. ** May you share freely, never taking more than you give.
  42952. **
  42953. *************************************************************************
  42954. **
  42955. ** This file contains code used to implement mutexes on Btree objects.
  42956. ** This code really belongs in btree.c. But btree.c is getting too
  42957. ** big and we want to break it down some. This packaged seemed like
  42958. ** a good breakout.
  42959. */
  42960. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  42961. /************** Begin file btreeInt.h ****************************************/
  42962. /*
  42963. ** 2004 April 6
  42964. **
  42965. ** The author disclaims copyright to this source code. In place of
  42966. ** a legal notice, here is a blessing:
  42967. **
  42968. ** May you do good and not evil.
  42969. ** May you find forgiveness for yourself and forgive others.
  42970. ** May you share freely, never taking more than you give.
  42971. **
  42972. *************************************************************************
  42973. ** This file implements a external (disk-based) database using BTrees.
  42974. ** For a detailed discussion of BTrees, refer to
  42975. **
  42976. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  42977. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  42978. ** Publishing Company, Reading, Massachusetts.
  42979. **
  42980. ** The basic idea is that each page of the file contains N database
  42981. ** entries and N+1 pointers to subpages.
  42982. **
  42983. ** ----------------------------------------------------------------
  42984. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  42985. ** ----------------------------------------------------------------
  42986. **
  42987. ** All of the keys on the page that Ptr(0) points to have values less
  42988. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  42989. ** values greater than Key(0) and less than Key(1). All of the keys
  42990. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  42991. ** so forth.
  42992. **
  42993. ** Finding a particular key requires reading O(log(M)) pages from the
  42994. ** disk where M is the number of entries in the tree.
  42995. **
  42996. ** In this implementation, a single file can hold one or more separate
  42997. ** BTrees. Each BTree is identified by the index of its root page. The
  42998. ** key and data for any entry are combined to form the "payload". A
  42999. ** fixed amount of payload can be carried directly on the database
  43000. ** page. If the payload is larger than the preset amount then surplus
  43001. ** bytes are stored on overflow pages. The payload for an entry
  43002. ** and the preceding pointer are combined to form a "Cell". Each
  43003. ** page has a small header which contains the Ptr(N) pointer and other
  43004. ** information such as the size of key and data.
  43005. **
  43006. ** FORMAT DETAILS
  43007. **
  43008. ** The file is divided into pages. The first page is called page 1,
  43009. ** the second is page 2, and so forth. A page number of zero indicates
  43010. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  43011. ** Each page can be either a btree page, a freelist page, an overflow
  43012. ** page, or a pointer-map page.
  43013. **
  43014. ** The first page is always a btree page. The first 100 bytes of the first
  43015. ** page contain a special header (the "file header") that describes the file.
  43016. ** The format of the file header is as follows:
  43017. **
  43018. ** OFFSET SIZE DESCRIPTION
  43019. ** 0 16 Header string: "SQLite format 3\000"
  43020. ** 16 2 Page size in bytes.
  43021. ** 18 1 File format write version
  43022. ** 19 1 File format read version
  43023. ** 20 1 Bytes of unused space at the end of each page
  43024. ** 21 1 Max embedded payload fraction
  43025. ** 22 1 Min embedded payload fraction
  43026. ** 23 1 Min leaf payload fraction
  43027. ** 24 4 File change counter
  43028. ** 28 4 Reserved for future use
  43029. ** 32 4 First freelist page
  43030. ** 36 4 Number of freelist pages in the file
  43031. ** 40 60 15 4-byte meta values passed to higher layers
  43032. **
  43033. ** 40 4 Schema cookie
  43034. ** 44 4 File format of schema layer
  43035. ** 48 4 Size of page cache
  43036. ** 52 4 Largest root-page (auto/incr_vacuum)
  43037. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  43038. ** 60 4 User version
  43039. ** 64 4 Incremental vacuum mode
  43040. ** 68 4 unused
  43041. ** 72 4 unused
  43042. ** 76 4 unused
  43043. **
  43044. ** All of the integer values are big-endian (most significant byte first).
  43045. **
  43046. ** The file change counter is incremented when the database is changed
  43047. ** This counter allows other processes to know when the file has changed
  43048. ** and thus when they need to flush their cache.
  43049. **
  43050. ** The max embedded payload fraction is the amount of the total usable
  43051. ** space in a page that can be consumed by a single cell for standard
  43052. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  43053. ** is to limit the maximum cell size so that at least 4 cells will fit
  43054. ** on one page. Thus the default max embedded payload fraction is 64.
  43055. **
  43056. ** If the payload for a cell is larger than the max payload, then extra
  43057. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  43058. ** as many bytes as possible are moved into the overflow pages without letting
  43059. ** the cell size drop below the min embedded payload fraction.
  43060. **
  43061. ** The min leaf payload fraction is like the min embedded payload fraction
  43062. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  43063. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  43064. ** not specified in the header.
  43065. **
  43066. ** Each btree pages is divided into three sections: The header, the
  43067. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  43068. ** file header that occurs before the page header.
  43069. **
  43070. ** |----------------|
  43071. ** | file header | 100 bytes. Page 1 only.
  43072. ** |----------------|
  43073. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  43074. ** |----------------|
  43075. ** | cell pointer | | 2 bytes per cell. Sorted order.
  43076. ** | array | | Grows downward
  43077. ** | | v
  43078. ** |----------------|
  43079. ** | unallocated |
  43080. ** | space |
  43081. ** |----------------| ^ Grows upwards
  43082. ** | cell content | | Arbitrary order interspersed with freeblocks.
  43083. ** | area | | and free space fragments.
  43084. ** |----------------|
  43085. **
  43086. ** The page headers looks like this:
  43087. **
  43088. ** OFFSET SIZE DESCRIPTION
  43089. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  43090. ** 1 2 byte offset to the first freeblock
  43091. ** 3 2 number of cells on this page
  43092. ** 5 2 first byte of the cell content area
  43093. ** 7 1 number of fragmented free bytes
  43094. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  43095. **
  43096. ** The flags define the format of this btree page. The leaf flag means that
  43097. ** this page has no children. The zerodata flag means that this page carries
  43098. ** only keys and no data. The intkey flag means that the key is a integer
  43099. ** which is stored in the key size entry of the cell header rather than in
  43100. ** the payload area.
  43101. **
  43102. ** The cell pointer array begins on the first byte after the page header.
  43103. ** The cell pointer array contains zero or more 2-byte numbers which are
  43104. ** offsets from the beginning of the page to the cell content in the cell
  43105. ** content area. The cell pointers occur in sorted order. The system strives
  43106. ** to keep free space after the last cell pointer so that new cells can
  43107. ** be easily added without having to defragment the page.
  43108. **
  43109. ** Cell content is stored at the very end of the page and grows toward the
  43110. ** beginning of the page.
  43111. **
  43112. ** Unused space within the cell content area is collected into a linked list of
  43113. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  43114. ** to the first freeblock is given in the header. Freeblocks occur in
  43115. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  43116. ** any group of 3 or fewer unused bytes in the cell content area cannot
  43117. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  43118. ** a fragment. The total number of bytes in all fragments is recorded.
  43119. ** in the page header at offset 7.
  43120. **
  43121. ** SIZE DESCRIPTION
  43122. ** 2 Byte offset of the next freeblock
  43123. ** 2 Bytes in this freeblock
  43124. **
  43125. ** Cells are of variable length. Cells are stored in the cell content area at
  43126. ** the end of the page. Pointers to the cells are in the cell pointer array
  43127. ** that immediately follows the page header. Cells is not necessarily
  43128. ** contiguous or in order, but cell pointers are contiguous and in order.
  43129. **
  43130. ** Cell content makes use of variable length integers. A variable
  43131. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  43132. ** byte are used. The integer consists of all bytes that have bit 8 set and
  43133. ** the first byte with bit 8 clear. The most significant byte of the integer
  43134. ** appears first. A variable-length integer may not be more than 9 bytes long.
  43135. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  43136. ** allows a 64-bit integer to be encoded in 9 bytes.
  43137. **
  43138. ** 0x00 becomes 0x00000000
  43139. ** 0x7f becomes 0x0000007f
  43140. ** 0x81 0x00 becomes 0x00000080
  43141. ** 0x82 0x00 becomes 0x00000100
  43142. ** 0x80 0x7f becomes 0x0000007f
  43143. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  43144. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  43145. **
  43146. ** Variable length integers are used for rowids and to hold the number of
  43147. ** bytes of key and data in a btree cell.
  43148. **
  43149. ** The content of a cell looks like this:
  43150. **
  43151. ** SIZE DESCRIPTION
  43152. ** 4 Page number of the left child. Omitted if leaf flag is set.
  43153. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  43154. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  43155. ** * Payload
  43156. ** 4 First page of the overflow chain. Omitted if no overflow
  43157. **
  43158. ** Overflow pages form a linked list. Each page except the last is completely
  43159. ** filled with data (pagesize - 4 bytes). The last page can have as little
  43160. ** as 1 byte of data.
  43161. **
  43162. ** SIZE DESCRIPTION
  43163. ** 4 Page number of next overflow page
  43164. ** * Data
  43165. **
  43166. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  43167. ** file header points to the first in a linked list of trunk page. Each trunk
  43168. ** page points to multiple leaf pages. The content of a leaf page is
  43169. ** unspecified. A trunk page looks like this:
  43170. **
  43171. ** SIZE DESCRIPTION
  43172. ** 4 Page number of next trunk page
  43173. ** 4 Number of leaf pointers on this page
  43174. ** * zero or more pages numbers of leaves
  43175. */
  43176. /* The following value is the maximum cell size assuming a maximum page
  43177. ** size give above.
  43178. */
  43179. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  43180. /* The maximum number of cells on a single page of the database. This
  43181. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  43182. ** plus 2 bytes for the index to the cell in the page header). Such
  43183. ** small cells will be rare, but they are possible.
  43184. */
  43185. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  43186. /* Forward declarations */
  43187. typedef struct MemPage MemPage;
  43188. typedef struct BtLock BtLock;
  43189. /*
  43190. ** This is a magic string that appears at the beginning of every
  43191. ** SQLite database in order to identify the file as a real database.
  43192. **
  43193. ** You can change this value at compile-time by specifying a
  43194. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  43195. ** header must be exactly 16 bytes including the zero-terminator so
  43196. ** the string itself should be 15 characters long. If you change
  43197. ** the header, then your custom library will not be able to read
  43198. ** databases generated by the standard tools and the standard tools
  43199. ** will not be able to read databases created by your custom library.
  43200. */
  43201. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  43202. # define SQLITE_FILE_HEADER "SQLite format 3"
  43203. #endif
  43204. /*
  43205. ** Page type flags. An ORed combination of these flags appear as the
  43206. ** first byte of on-disk image of every BTree page.
  43207. */
  43208. #define PTF_INTKEY 0x01
  43209. #define PTF_ZERODATA 0x02
  43210. #define PTF_LEAFDATA 0x04
  43211. #define PTF_LEAF 0x08
  43212. /*
  43213. ** As each page of the file is loaded into memory, an instance of the following
  43214. ** structure is appended and initialized to zero. This structure stores
  43215. ** information about the page that is decoded from the raw file page.
  43216. **
  43217. ** The pParent field points back to the parent page. This allows us to
  43218. ** walk up the BTree from any leaf to the root. Care must be taken to
  43219. ** unref() the parent page pointer when this page is no longer referenced.
  43220. ** The pageDestructor() routine handles that chore.
  43221. **
  43222. ** Access to all fields of this structure is controlled by the mutex
  43223. ** stored in MemPage.pBt->mutex.
  43224. */
  43225. struct MemPage {
  43226. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  43227. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  43228. u8 intKey; /* True if intkey flag is set */
  43229. u8 leaf; /* True if leaf flag is set */
  43230. u8 hasData; /* True if this page stores data */
  43231. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  43232. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  43233. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  43234. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  43235. u16 cellOffset; /* Index in aData of first cell pointer */
  43236. u16 nFree; /* Number of free bytes on the page */
  43237. u16 nCell; /* Number of cells on this page, local and ovfl */
  43238. u16 maskPage; /* Mask for page offset */
  43239. struct _OvflCell { /* Cells that will not fit on aData[] */
  43240. u8 *pCell; /* Pointers to the body of the overflow cell */
  43241. u16 idx; /* Insert this cell before idx-th non-overflow cell */
  43242. } aOvfl[5];
  43243. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  43244. u8 *aData; /* Pointer to disk image of the page data */
  43245. DbPage *pDbPage; /* Pager page handle */
  43246. Pgno pgno; /* Page number for this page */
  43247. };
  43248. /*
  43249. ** The in-memory image of a disk page has the auxiliary information appended
  43250. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  43251. ** that extra information.
  43252. */
  43253. #define EXTRA_SIZE sizeof(MemPage)
  43254. /*
  43255. ** A linked list of the following structures is stored at BtShared.pLock.
  43256. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  43257. ** is opened on the table with root page BtShared.iTable. Locks are removed
  43258. ** from this list when a transaction is committed or rolled back, or when
  43259. ** a btree handle is closed.
  43260. */
  43261. struct BtLock {
  43262. Btree *pBtree; /* Btree handle holding this lock */
  43263. Pgno iTable; /* Root page of table */
  43264. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  43265. BtLock *pNext; /* Next in BtShared.pLock list */
  43266. };
  43267. /* Candidate values for BtLock.eLock */
  43268. #define READ_LOCK 1
  43269. #define WRITE_LOCK 2
  43270. /* A Btree handle
  43271. **
  43272. ** A database connection contains a pointer to an instance of
  43273. ** this object for every database file that it has open. This structure
  43274. ** is opaque to the database connection. The database connection cannot
  43275. ** see the internals of this structure and only deals with pointers to
  43276. ** this structure.
  43277. **
  43278. ** For some database files, the same underlying database cache might be
  43279. ** shared between multiple connections. In that case, each connection
  43280. ** has it own instance of this object. But each instance of this object
  43281. ** points to the same BtShared object. The database cache and the
  43282. ** schema associated with the database file are all contained within
  43283. ** the BtShared object.
  43284. **
  43285. ** All fields in this structure are accessed under sqlite3.mutex.
  43286. ** The pBt pointer itself may not be changed while there exists cursors
  43287. ** in the referenced BtShared that point back to this Btree since those
  43288. ** cursors have to go through this Btree to find their BtShared and
  43289. ** they often do so without holding sqlite3.mutex.
  43290. */
  43291. struct Btree {
  43292. sqlite3 *db; /* The database connection holding this btree */
  43293. BtShared *pBt; /* Sharable content of this btree */
  43294. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  43295. u8 sharable; /* True if we can share pBt with another db */
  43296. u8 locked; /* True if db currently has pBt locked */
  43297. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  43298. int nBackup; /* Number of backup operations reading this btree */
  43299. Btree *pNext; /* List of other sharable Btrees from the same db */
  43300. Btree *pPrev; /* Back pointer of the same list */
  43301. #ifndef SQLITE_OMIT_SHARED_CACHE
  43302. BtLock lock; /* Object used to lock page 1 */
  43303. #endif
  43304. };
  43305. /*
  43306. ** Btree.inTrans may take one of the following values.
  43307. **
  43308. ** If the shared-data extension is enabled, there may be multiple users
  43309. ** of the Btree structure. At most one of these may open a write transaction,
  43310. ** but any number may have active read transactions.
  43311. */
  43312. #define TRANS_NONE 0
  43313. #define TRANS_READ 1
  43314. #define TRANS_WRITE 2
  43315. /*
  43316. ** An instance of this object represents a single database file.
  43317. **
  43318. ** A single database file can be in use as the same time by two
  43319. ** or more database connections. When two or more connections are
  43320. ** sharing the same database file, each connection has it own
  43321. ** private Btree object for the file and each of those Btrees points
  43322. ** to this one BtShared object. BtShared.nRef is the number of
  43323. ** connections currently sharing this database file.
  43324. **
  43325. ** Fields in this structure are accessed under the BtShared.mutex
  43326. ** mutex, except for nRef and pNext which are accessed under the
  43327. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  43328. ** may not be modified once it is initially set as long as nRef>0.
  43329. ** The pSchema field may be set once under BtShared.mutex and
  43330. ** thereafter is unchanged as long as nRef>0.
  43331. **
  43332. ** isPending:
  43333. **
  43334. ** If a BtShared client fails to obtain a write-lock on a database
  43335. ** table (because there exists one or more read-locks on the table),
  43336. ** the shared-cache enters 'pending-lock' state and isPending is
  43337. ** set to true.
  43338. **
  43339. ** The shared-cache leaves the 'pending lock' state when either of
  43340. ** the following occur:
  43341. **
  43342. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  43343. ** 2) The number of locks held by other connections drops to zero.
  43344. **
  43345. ** while in the 'pending-lock' state, no connection may start a new
  43346. ** transaction.
  43347. **
  43348. ** This feature is included to help prevent writer-starvation.
  43349. */
  43350. struct BtShared {
  43351. Pager *pPager; /* The page cache */
  43352. sqlite3 *db; /* Database connection currently using this Btree */
  43353. BtCursor *pCursor; /* A list of all open cursors */
  43354. MemPage *pPage1; /* First page of the database */
  43355. u8 readOnly; /* True if the underlying file is readonly */
  43356. u8 pageSizeFixed; /* True if the page size can no longer be changed */
  43357. u8 secureDelete; /* True if secure_delete is enabled */
  43358. u8 initiallyEmpty; /* Database is empty at start of transaction */
  43359. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  43360. #ifndef SQLITE_OMIT_AUTOVACUUM
  43361. u8 autoVacuum; /* True if auto-vacuum is enabled */
  43362. u8 incrVacuum; /* True if incr-vacuum is enabled */
  43363. #endif
  43364. u8 inTransaction; /* Transaction state */
  43365. u8 doNotUseWAL; /* If true, do not open write-ahead-log file */
  43366. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  43367. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  43368. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  43369. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  43370. u32 pageSize; /* Total number of bytes on a page */
  43371. u32 usableSize; /* Number of usable bytes on each page */
  43372. int nTransaction; /* Number of open transactions (read + write) */
  43373. u32 nPage; /* Number of pages in the database */
  43374. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  43375. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  43376. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  43377. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  43378. #ifndef SQLITE_OMIT_SHARED_CACHE
  43379. int nRef; /* Number of references to this structure */
  43380. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  43381. BtLock *pLock; /* List of locks held on this shared-btree struct */
  43382. Btree *pWriter; /* Btree with currently open write transaction */
  43383. u8 isExclusive; /* True if pWriter has an EXCLUSIVE lock on the db */
  43384. u8 isPending; /* If waiting for read-locks to clear */
  43385. #endif
  43386. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  43387. };
  43388. /*
  43389. ** An instance of the following structure is used to hold information
  43390. ** about a cell. The parseCellPtr() function fills in this structure
  43391. ** based on information extract from the raw disk page.
  43392. */
  43393. typedef struct CellInfo CellInfo;
  43394. struct CellInfo {
  43395. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  43396. u8 *pCell; /* Pointer to the start of cell content */
  43397. u32 nData; /* Number of bytes of data */
  43398. u32 nPayload; /* Total amount of payload */
  43399. u16 nHeader; /* Size of the cell content header in bytes */
  43400. u16 nLocal; /* Amount of payload held locally */
  43401. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  43402. u16 nSize; /* Size of the cell content on the main b-tree page */
  43403. };
  43404. /*
  43405. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  43406. ** this will be declared corrupt. This value is calculated based on a
  43407. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  43408. ** root-node and 3 for all other internal nodes.
  43409. **
  43410. ** If a tree that appears to be taller than this is encountered, it is
  43411. ** assumed that the database is corrupt.
  43412. */
  43413. #define BTCURSOR_MAX_DEPTH 20
  43414. /*
  43415. ** A cursor is a pointer to a particular entry within a particular
  43416. ** b-tree within a database file.
  43417. **
  43418. ** The entry is identified by its MemPage and the index in
  43419. ** MemPage.aCell[] of the entry.
  43420. **
  43421. ** A single database file can shared by two more database connections,
  43422. ** but cursors cannot be shared. Each cursor is associated with a
  43423. ** particular database connection identified BtCursor.pBtree.db.
  43424. **
  43425. ** Fields in this structure are accessed under the BtShared.mutex
  43426. ** found at self->pBt->mutex.
  43427. */
  43428. struct BtCursor {
  43429. Btree *pBtree; /* The Btree to which this cursor belongs */
  43430. BtShared *pBt; /* The BtShared this cursor points to */
  43431. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  43432. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  43433. Pgno pgnoRoot; /* The root page of this tree */
  43434. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  43435. CellInfo info; /* A parse of the cell we are pointing at */
  43436. i64 nKey; /* Size of pKey, or last integer key */
  43437. void *pKey; /* Saved key that was cursor's last known position */
  43438. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  43439. u8 wrFlag; /* True if writable */
  43440. u8 atLast; /* Cursor pointing to the last entry */
  43441. u8 validNKey; /* True if info.nKey is valid */
  43442. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  43443. #ifndef SQLITE_OMIT_INCRBLOB
  43444. Pgno *aOverflow; /* Cache of overflow page locations */
  43445. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  43446. #endif
  43447. i16 iPage; /* Index of current page in apPage */
  43448. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  43449. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  43450. };
  43451. /*
  43452. ** Potential values for BtCursor.eState.
  43453. **
  43454. ** CURSOR_VALID:
  43455. ** Cursor points to a valid entry. getPayload() etc. may be called.
  43456. **
  43457. ** CURSOR_INVALID:
  43458. ** Cursor does not point to a valid entry. This can happen (for example)
  43459. ** because the table is empty or because BtreeCursorFirst() has not been
  43460. ** called.
  43461. **
  43462. ** CURSOR_REQUIRESEEK:
  43463. ** The table that this cursor was opened on still exists, but has been
  43464. ** modified since the cursor was last used. The cursor position is saved
  43465. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  43466. ** this state, restoreCursorPosition() can be called to attempt to
  43467. ** seek the cursor to the saved position.
  43468. **
  43469. ** CURSOR_FAULT:
  43470. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  43471. ** on a different connection that shares the BtShared cache with this
  43472. ** cursor. The error has left the cache in an inconsistent state.
  43473. ** Do nothing else with this cursor. Any attempt to use the cursor
  43474. ** should return the error code stored in BtCursor.skip
  43475. */
  43476. #define CURSOR_INVALID 0
  43477. #define CURSOR_VALID 1
  43478. #define CURSOR_REQUIRESEEK 2
  43479. #define CURSOR_FAULT 3
  43480. /*
  43481. ** The database page the PENDING_BYTE occupies. This page is never used.
  43482. */
  43483. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  43484. /*
  43485. ** These macros define the location of the pointer-map entry for a
  43486. ** database page. The first argument to each is the number of usable
  43487. ** bytes on each page of the database (often 1024). The second is the
  43488. ** page number to look up in the pointer map.
  43489. **
  43490. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  43491. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  43492. ** the offset of the requested map entry.
  43493. **
  43494. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  43495. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  43496. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  43497. ** this test.
  43498. */
  43499. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  43500. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  43501. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  43502. /*
  43503. ** The pointer map is a lookup table that identifies the parent page for
  43504. ** each child page in the database file. The parent page is the page that
  43505. ** contains a pointer to the child. Every page in the database contains
  43506. ** 0 or 1 parent pages. (In this context 'database page' refers
  43507. ** to any page that is not part of the pointer map itself.) Each pointer map
  43508. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  43509. ** The PTRMAP_XXX identifiers below are the valid types.
  43510. **
  43511. ** The purpose of the pointer map is to facility moving pages from one
  43512. ** position in the file to another as part of autovacuum. When a page
  43513. ** is moved, the pointer in its parent must be updated to point to the
  43514. ** new location. The pointer map is used to locate the parent page quickly.
  43515. **
  43516. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  43517. ** used in this case.
  43518. **
  43519. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  43520. ** is not used in this case.
  43521. **
  43522. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  43523. ** overflow pages. The page number identifies the page that
  43524. ** contains the cell with a pointer to this overflow page.
  43525. **
  43526. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  43527. ** overflow pages. The page-number identifies the previous
  43528. ** page in the overflow page list.
  43529. **
  43530. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  43531. ** identifies the parent page in the btree.
  43532. */
  43533. #define PTRMAP_ROOTPAGE 1
  43534. #define PTRMAP_FREEPAGE 2
  43535. #define PTRMAP_OVERFLOW1 3
  43536. #define PTRMAP_OVERFLOW2 4
  43537. #define PTRMAP_BTREE 5
  43538. /* A bunch of assert() statements to check the transaction state variables
  43539. ** of handle p (type Btree*) are internally consistent.
  43540. */
  43541. #define btreeIntegrity(p) \
  43542. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  43543. assert( p->pBt->inTransaction>=p->inTrans );
  43544. /*
  43545. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  43546. ** if the database supports auto-vacuum or not. Because it is used
  43547. ** within an expression that is an argument to another macro
  43548. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  43549. ** So, this macro is defined instead.
  43550. */
  43551. #ifndef SQLITE_OMIT_AUTOVACUUM
  43552. #define ISAUTOVACUUM (pBt->autoVacuum)
  43553. #else
  43554. #define ISAUTOVACUUM 0
  43555. #endif
  43556. /*
  43557. ** This structure is passed around through all the sanity checking routines
  43558. ** in order to keep track of some global state information.
  43559. */
  43560. typedef struct IntegrityCk IntegrityCk;
  43561. struct IntegrityCk {
  43562. BtShared *pBt; /* The tree being checked out */
  43563. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  43564. Pgno nPage; /* Number of pages in the database */
  43565. int *anRef; /* Number of times each page is referenced */
  43566. int mxErr; /* Stop accumulating errors when this reaches zero */
  43567. int nErr; /* Number of messages written to zErrMsg so far */
  43568. int mallocFailed; /* A memory allocation error has occurred */
  43569. StrAccum errMsg; /* Accumulate the error message text here */
  43570. };
  43571. /*
  43572. ** Read or write a two- and four-byte big-endian integer values.
  43573. */
  43574. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  43575. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  43576. #define get4byte sqlite3Get4byte
  43577. #define put4byte sqlite3Put4byte
  43578. /************** End of btreeInt.h ********************************************/
  43579. /************** Continuing where we left off in btmutex.c ********************/
  43580. #ifndef SQLITE_OMIT_SHARED_CACHE
  43581. #if SQLITE_THREADSAFE
  43582. /*
  43583. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  43584. ** set BtShared.db to the database handle associated with p and the
  43585. ** p->locked boolean to true.
  43586. */
  43587. static void lockBtreeMutex(Btree *p){
  43588. assert( p->locked==0 );
  43589. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  43590. assert( sqlite3_mutex_held(p->db->mutex) );
  43591. sqlite3_mutex_enter(p->pBt->mutex);
  43592. p->pBt->db = p->db;
  43593. p->locked = 1;
  43594. }
  43595. /*
  43596. ** Release the BtShared mutex associated with B-Tree handle p and
  43597. ** clear the p->locked boolean.
  43598. */
  43599. static void unlockBtreeMutex(Btree *p){
  43600. BtShared *pBt = p->pBt;
  43601. assert( p->locked==1 );
  43602. assert( sqlite3_mutex_held(pBt->mutex) );
  43603. assert( sqlite3_mutex_held(p->db->mutex) );
  43604. assert( p->db==pBt->db );
  43605. sqlite3_mutex_leave(pBt->mutex);
  43606. p->locked = 0;
  43607. }
  43608. /*
  43609. ** Enter a mutex on the given BTree object.
  43610. **
  43611. ** If the object is not sharable, then no mutex is ever required
  43612. ** and this routine is a no-op. The underlying mutex is non-recursive.
  43613. ** But we keep a reference count in Btree.wantToLock so the behavior
  43614. ** of this interface is recursive.
  43615. **
  43616. ** To avoid deadlocks, multiple Btrees are locked in the same order
  43617. ** by all database connections. The p->pNext is a list of other
  43618. ** Btrees belonging to the same database connection as the p Btree
  43619. ** which need to be locked after p. If we cannot get a lock on
  43620. ** p, then first unlock all of the others on p->pNext, then wait
  43621. ** for the lock to become available on p, then relock all of the
  43622. ** subsequent Btrees that desire a lock.
  43623. */
  43624. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  43625. Btree *pLater;
  43626. /* Some basic sanity checking on the Btree. The list of Btrees
  43627. ** connected by pNext and pPrev should be in sorted order by
  43628. ** Btree.pBt value. All elements of the list should belong to
  43629. ** the same connection. Only shared Btrees are on the list. */
  43630. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  43631. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  43632. assert( p->pNext==0 || p->pNext->db==p->db );
  43633. assert( p->pPrev==0 || p->pPrev->db==p->db );
  43634. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  43635. /* Check for locking consistency */
  43636. assert( !p->locked || p->wantToLock>0 );
  43637. assert( p->sharable || p->wantToLock==0 );
  43638. /* We should already hold a lock on the database connection */
  43639. assert( sqlite3_mutex_held(p->db->mutex) );
  43640. /* Unless the database is sharable and unlocked, then BtShared.db
  43641. ** should already be set correctly. */
  43642. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  43643. if( !p->sharable ) return;
  43644. p->wantToLock++;
  43645. if( p->locked ) return;
  43646. /* In most cases, we should be able to acquire the lock we
  43647. ** want without having to go throught the ascending lock
  43648. ** procedure that follows. Just be sure not to block.
  43649. */
  43650. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  43651. p->pBt->db = p->db;
  43652. p->locked = 1;
  43653. return;
  43654. }
  43655. /* To avoid deadlock, first release all locks with a larger
  43656. ** BtShared address. Then acquire our lock. Then reacquire
  43657. ** the other BtShared locks that we used to hold in ascending
  43658. ** order.
  43659. */
  43660. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  43661. assert( pLater->sharable );
  43662. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  43663. assert( !pLater->locked || pLater->wantToLock>0 );
  43664. if( pLater->locked ){
  43665. unlockBtreeMutex(pLater);
  43666. }
  43667. }
  43668. lockBtreeMutex(p);
  43669. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  43670. if( pLater->wantToLock ){
  43671. lockBtreeMutex(pLater);
  43672. }
  43673. }
  43674. }
  43675. /*
  43676. ** Exit the recursive mutex on a Btree.
  43677. */
  43678. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  43679. if( p->sharable ){
  43680. assert( p->wantToLock>0 );
  43681. p->wantToLock--;
  43682. if( p->wantToLock==0 ){
  43683. unlockBtreeMutex(p);
  43684. }
  43685. }
  43686. }
  43687. #ifndef NDEBUG
  43688. /*
  43689. ** Return true if the BtShared mutex is held on the btree, or if the
  43690. ** B-Tree is not marked as sharable.
  43691. **
  43692. ** This routine is used only from within assert() statements.
  43693. */
  43694. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  43695. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  43696. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  43697. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  43698. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  43699. return (p->sharable==0 || p->locked);
  43700. }
  43701. #endif
  43702. #ifndef SQLITE_OMIT_INCRBLOB
  43703. /*
  43704. ** Enter and leave a mutex on a Btree given a cursor owned by that
  43705. ** Btree. These entry points are used by incremental I/O and can be
  43706. ** omitted if that module is not used.
  43707. */
  43708. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  43709. sqlite3BtreeEnter(pCur->pBtree);
  43710. }
  43711. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  43712. sqlite3BtreeLeave(pCur->pBtree);
  43713. }
  43714. #endif /* SQLITE_OMIT_INCRBLOB */
  43715. /*
  43716. ** Enter the mutex on every Btree associated with a database
  43717. ** connection. This is needed (for example) prior to parsing
  43718. ** a statement since we will be comparing table and column names
  43719. ** against all schemas and we do not want those schemas being
  43720. ** reset out from under us.
  43721. **
  43722. ** There is a corresponding leave-all procedures.
  43723. **
  43724. ** Enter the mutexes in accending order by BtShared pointer address
  43725. ** to avoid the possibility of deadlock when two threads with
  43726. ** two or more btrees in common both try to lock all their btrees
  43727. ** at the same instant.
  43728. */
  43729. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  43730. int i;
  43731. Btree *p;
  43732. assert( sqlite3_mutex_held(db->mutex) );
  43733. for(i=0; i<db->nDb; i++){
  43734. p = db->aDb[i].pBt;
  43735. if( p ) sqlite3BtreeEnter(p);
  43736. }
  43737. }
  43738. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  43739. int i;
  43740. Btree *p;
  43741. assert( sqlite3_mutex_held(db->mutex) );
  43742. for(i=0; i<db->nDb; i++){
  43743. p = db->aDb[i].pBt;
  43744. if( p ) sqlite3BtreeLeave(p);
  43745. }
  43746. }
  43747. /*
  43748. ** Return true if a particular Btree requires a lock. Return FALSE if
  43749. ** no lock is ever required since it is not sharable.
  43750. */
  43751. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  43752. return p->sharable;
  43753. }
  43754. #ifndef NDEBUG
  43755. /*
  43756. ** Return true if the current thread holds the database connection
  43757. ** mutex and all required BtShared mutexes.
  43758. **
  43759. ** This routine is used inside assert() statements only.
  43760. */
  43761. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  43762. int i;
  43763. if( !sqlite3_mutex_held(db->mutex) ){
  43764. return 0;
  43765. }
  43766. for(i=0; i<db->nDb; i++){
  43767. Btree *p;
  43768. p = db->aDb[i].pBt;
  43769. if( p && p->sharable &&
  43770. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  43771. return 0;
  43772. }
  43773. }
  43774. return 1;
  43775. }
  43776. #endif /* NDEBUG */
  43777. #ifndef NDEBUG
  43778. /*
  43779. ** Return true if the correct mutexes are held for accessing the
  43780. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  43781. ** access are:
  43782. **
  43783. ** (1) The mutex on db
  43784. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  43785. **
  43786. ** If pSchema is not NULL, then iDb is computed from pSchema and
  43787. ** db using sqlite3SchemaToIndex().
  43788. */
  43789. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  43790. Btree *p;
  43791. assert( db!=0 );
  43792. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  43793. assert( iDb>=0 && iDb<db->nDb );
  43794. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  43795. if( iDb==1 ) return 1;
  43796. p = db->aDb[iDb].pBt;
  43797. assert( p!=0 );
  43798. return p->sharable==0 || p->locked==1;
  43799. }
  43800. #endif /* NDEBUG */
  43801. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  43802. /*
  43803. ** The following are special cases for mutex enter routines for use
  43804. ** in single threaded applications that use shared cache. Except for
  43805. ** these two routines, all mutex operations are no-ops in that case and
  43806. ** are null #defines in btree.h.
  43807. **
  43808. ** If shared cache is disabled, then all btree mutex routines, including
  43809. ** the ones below, are no-ops and are null #defines in btree.h.
  43810. */
  43811. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  43812. p->pBt->db = p->db;
  43813. }
  43814. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  43815. int i;
  43816. for(i=0; i<db->nDb; i++){
  43817. Btree *p = db->aDb[i].pBt;
  43818. if( p ){
  43819. p->pBt->db = p->db;
  43820. }
  43821. }
  43822. }
  43823. #endif /* if SQLITE_THREADSAFE */
  43824. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  43825. /************** End of btmutex.c *********************************************/
  43826. /************** Begin file btree.c *******************************************/
  43827. /*
  43828. ** 2004 April 6
  43829. **
  43830. ** The author disclaims copyright to this source code. In place of
  43831. ** a legal notice, here is a blessing:
  43832. **
  43833. ** May you do good and not evil.
  43834. ** May you find forgiveness for yourself and forgive others.
  43835. ** May you share freely, never taking more than you give.
  43836. **
  43837. *************************************************************************
  43838. ** This file implements a external (disk-based) database using BTrees.
  43839. ** See the header comment on "btreeInt.h" for additional information.
  43840. ** Including a description of file format and an overview of operation.
  43841. */
  43842. /*
  43843. ** The header string that appears at the beginning of every
  43844. ** SQLite database.
  43845. */
  43846. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  43847. /*
  43848. ** Set this global variable to 1 to enable tracing using the TRACE
  43849. ** macro.
  43850. */
  43851. #if 0
  43852. int sqlite3BtreeTrace=1; /* True to enable tracing */
  43853. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  43854. #else
  43855. # define TRACE(X)
  43856. #endif
  43857. /*
  43858. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  43859. ** But if the value is zero, make it 65536.
  43860. **
  43861. ** This routine is used to extract the "offset to cell content area" value
  43862. ** from the header of a btree page. If the page size is 65536 and the page
  43863. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  43864. ** This routine makes the necessary adjustment to 65536.
  43865. */
  43866. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  43867. #ifndef SQLITE_OMIT_SHARED_CACHE
  43868. /*
  43869. ** A list of BtShared objects that are eligible for participation
  43870. ** in shared cache. This variable has file scope during normal builds,
  43871. ** but the test harness needs to access it so we make it global for
  43872. ** test builds.
  43873. **
  43874. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  43875. */
  43876. #ifdef SQLITE_TEST
  43877. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  43878. #else
  43879. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  43880. #endif
  43881. #endif /* SQLITE_OMIT_SHARED_CACHE */
  43882. #ifndef SQLITE_OMIT_SHARED_CACHE
  43883. /*
  43884. ** Enable or disable the shared pager and schema features.
  43885. **
  43886. ** This routine has no effect on existing database connections.
  43887. ** The shared cache setting effects only future calls to
  43888. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  43889. */
  43890. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  43891. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  43892. return SQLITE_OK;
  43893. }
  43894. #endif
  43895. #ifdef SQLITE_OMIT_SHARED_CACHE
  43896. /*
  43897. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  43898. ** and clearAllSharedCacheTableLocks()
  43899. ** manipulate entries in the BtShared.pLock linked list used to store
  43900. ** shared-cache table level locks. If the library is compiled with the
  43901. ** shared-cache feature disabled, then there is only ever one user
  43902. ** of each BtShared structure and so this locking is not necessary.
  43903. ** So define the lock related functions as no-ops.
  43904. */
  43905. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  43906. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  43907. #define clearAllSharedCacheTableLocks(a)
  43908. #define downgradeAllSharedCacheTableLocks(a)
  43909. #define hasSharedCacheTableLock(a,b,c,d) 1
  43910. #define hasReadConflicts(a, b) 0
  43911. #endif
  43912. #ifndef SQLITE_OMIT_SHARED_CACHE
  43913. #ifdef SQLITE_DEBUG
  43914. /*
  43915. **** This function is only used as part of an assert() statement. ***
  43916. **
  43917. ** Check to see if pBtree holds the required locks to read or write to the
  43918. ** table with root page iRoot. Return 1 if it does and 0 if not.
  43919. **
  43920. ** For example, when writing to a table with root-page iRoot via
  43921. ** Btree connection pBtree:
  43922. **
  43923. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  43924. **
  43925. ** When writing to an index that resides in a sharable database, the
  43926. ** caller should have first obtained a lock specifying the root page of
  43927. ** the corresponding table. This makes things a bit more complicated,
  43928. ** as this module treats each table as a separate structure. To determine
  43929. ** the table corresponding to the index being written, this
  43930. ** function has to search through the database schema.
  43931. **
  43932. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  43933. ** hold a write-lock on the schema table (root page 1). This is also
  43934. ** acceptable.
  43935. */
  43936. static int hasSharedCacheTableLock(
  43937. Btree *pBtree, /* Handle that must hold lock */
  43938. Pgno iRoot, /* Root page of b-tree */
  43939. int isIndex, /* True if iRoot is the root of an index b-tree */
  43940. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  43941. ){
  43942. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  43943. Pgno iTab = 0;
  43944. BtLock *pLock;
  43945. /* If this database is not shareable, or if the client is reading
  43946. ** and has the read-uncommitted flag set, then no lock is required.
  43947. ** Return true immediately.
  43948. */
  43949. if( (pBtree->sharable==0)
  43950. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  43951. ){
  43952. return 1;
  43953. }
  43954. /* If the client is reading or writing an index and the schema is
  43955. ** not loaded, then it is too difficult to actually check to see if
  43956. ** the correct locks are held. So do not bother - just return true.
  43957. ** This case does not come up very often anyhow.
  43958. */
  43959. if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
  43960. return 1;
  43961. }
  43962. /* Figure out the root-page that the lock should be held on. For table
  43963. ** b-trees, this is just the root page of the b-tree being read or
  43964. ** written. For index b-trees, it is the root page of the associated
  43965. ** table. */
  43966. if( isIndex ){
  43967. HashElem *p;
  43968. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  43969. Index *pIdx = (Index *)sqliteHashData(p);
  43970. if( pIdx->tnum==(int)iRoot ){
  43971. iTab = pIdx->pTable->tnum;
  43972. }
  43973. }
  43974. }else{
  43975. iTab = iRoot;
  43976. }
  43977. /* Search for the required lock. Either a write-lock on root-page iTab, a
  43978. ** write-lock on the schema table, or (if the client is reading) a
  43979. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  43980. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  43981. if( pLock->pBtree==pBtree
  43982. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  43983. && pLock->eLock>=eLockType
  43984. ){
  43985. return 1;
  43986. }
  43987. }
  43988. /* Failed to find the required lock. */
  43989. return 0;
  43990. }
  43991. #endif /* SQLITE_DEBUG */
  43992. #ifdef SQLITE_DEBUG
  43993. /*
  43994. **** This function may be used as part of assert() statements only. ****
  43995. **
  43996. ** Return true if it would be illegal for pBtree to write into the
  43997. ** table or index rooted at iRoot because other shared connections are
  43998. ** simultaneously reading that same table or index.
  43999. **
  44000. ** It is illegal for pBtree to write if some other Btree object that
  44001. ** shares the same BtShared object is currently reading or writing
  44002. ** the iRoot table. Except, if the other Btree object has the
  44003. ** read-uncommitted flag set, then it is OK for the other object to
  44004. ** have a read cursor.
  44005. **
  44006. ** For example, before writing to any part of the table or index
  44007. ** rooted at page iRoot, one should call:
  44008. **
  44009. ** assert( !hasReadConflicts(pBtree, iRoot) );
  44010. */
  44011. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  44012. BtCursor *p;
  44013. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  44014. if( p->pgnoRoot==iRoot
  44015. && p->pBtree!=pBtree
  44016. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  44017. ){
  44018. return 1;
  44019. }
  44020. }
  44021. return 0;
  44022. }
  44023. #endif /* #ifdef SQLITE_DEBUG */
  44024. /*
  44025. ** Query to see if Btree handle p may obtain a lock of type eLock
  44026. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  44027. ** SQLITE_OK if the lock may be obtained (by calling
  44028. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  44029. */
  44030. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  44031. BtShared *pBt = p->pBt;
  44032. BtLock *pIter;
  44033. assert( sqlite3BtreeHoldsMutex(p) );
  44034. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  44035. assert( p->db!=0 );
  44036. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  44037. /* If requesting a write-lock, then the Btree must have an open write
  44038. ** transaction on this file. And, obviously, for this to be so there
  44039. ** must be an open write transaction on the file itself.
  44040. */
  44041. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  44042. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  44043. /* This routine is a no-op if the shared-cache is not enabled */
  44044. if( !p->sharable ){
  44045. return SQLITE_OK;
  44046. }
  44047. /* If some other connection is holding an exclusive lock, the
  44048. ** requested lock may not be obtained.
  44049. */
  44050. if( pBt->pWriter!=p && pBt->isExclusive ){
  44051. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  44052. return SQLITE_LOCKED_SHAREDCACHE;
  44053. }
  44054. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  44055. /* The condition (pIter->eLock!=eLock) in the following if(...)
  44056. ** statement is a simplification of:
  44057. **
  44058. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  44059. **
  44060. ** since we know that if eLock==WRITE_LOCK, then no other connection
  44061. ** may hold a WRITE_LOCK on any table in this file (since there can
  44062. ** only be a single writer).
  44063. */
  44064. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  44065. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  44066. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  44067. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  44068. if( eLock==WRITE_LOCK ){
  44069. assert( p==pBt->pWriter );
  44070. pBt->isPending = 1;
  44071. }
  44072. return SQLITE_LOCKED_SHAREDCACHE;
  44073. }
  44074. }
  44075. return SQLITE_OK;
  44076. }
  44077. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  44078. #ifndef SQLITE_OMIT_SHARED_CACHE
  44079. /*
  44080. ** Add a lock on the table with root-page iTable to the shared-btree used
  44081. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  44082. ** WRITE_LOCK.
  44083. **
  44084. ** This function assumes the following:
  44085. **
  44086. ** (a) The specified Btree object p is connected to a sharable
  44087. ** database (one with the BtShared.sharable flag set), and
  44088. **
  44089. ** (b) No other Btree objects hold a lock that conflicts
  44090. ** with the requested lock (i.e. querySharedCacheTableLock() has
  44091. ** already been called and returned SQLITE_OK).
  44092. **
  44093. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  44094. ** is returned if a malloc attempt fails.
  44095. */
  44096. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  44097. BtShared *pBt = p->pBt;
  44098. BtLock *pLock = 0;
  44099. BtLock *pIter;
  44100. assert( sqlite3BtreeHoldsMutex(p) );
  44101. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  44102. assert( p->db!=0 );
  44103. /* A connection with the read-uncommitted flag set will never try to
  44104. ** obtain a read-lock using this function. The only read-lock obtained
  44105. ** by a connection in read-uncommitted mode is on the sqlite_master
  44106. ** table, and that lock is obtained in BtreeBeginTrans(). */
  44107. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  44108. /* This function should only be called on a sharable b-tree after it
  44109. ** has been determined that no other b-tree holds a conflicting lock. */
  44110. assert( p->sharable );
  44111. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  44112. /* First search the list for an existing lock on this table. */
  44113. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  44114. if( pIter->iTable==iTable && pIter->pBtree==p ){
  44115. pLock = pIter;
  44116. break;
  44117. }
  44118. }
  44119. /* If the above search did not find a BtLock struct associating Btree p
  44120. ** with table iTable, allocate one and link it into the list.
  44121. */
  44122. if( !pLock ){
  44123. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  44124. if( !pLock ){
  44125. return SQLITE_NOMEM;
  44126. }
  44127. pLock->iTable = iTable;
  44128. pLock->pBtree = p;
  44129. pLock->pNext = pBt->pLock;
  44130. pBt->pLock = pLock;
  44131. }
  44132. /* Set the BtLock.eLock variable to the maximum of the current lock
  44133. ** and the requested lock. This means if a write-lock was already held
  44134. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  44135. */
  44136. assert( WRITE_LOCK>READ_LOCK );
  44137. if( eLock>pLock->eLock ){
  44138. pLock->eLock = eLock;
  44139. }
  44140. return SQLITE_OK;
  44141. }
  44142. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  44143. #ifndef SQLITE_OMIT_SHARED_CACHE
  44144. /*
  44145. ** Release all the table locks (locks obtained via calls to
  44146. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  44147. **
  44148. ** This function assumes that Btree p has an open read or write
  44149. ** transaction. If it does not, then the BtShared.isPending variable
  44150. ** may be incorrectly cleared.
  44151. */
  44152. static void clearAllSharedCacheTableLocks(Btree *p){
  44153. BtShared *pBt = p->pBt;
  44154. BtLock **ppIter = &pBt->pLock;
  44155. assert( sqlite3BtreeHoldsMutex(p) );
  44156. assert( p->sharable || 0==*ppIter );
  44157. assert( p->inTrans>0 );
  44158. while( *ppIter ){
  44159. BtLock *pLock = *ppIter;
  44160. assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
  44161. assert( pLock->pBtree->inTrans>=pLock->eLock );
  44162. if( pLock->pBtree==p ){
  44163. *ppIter = pLock->pNext;
  44164. assert( pLock->iTable!=1 || pLock==&p->lock );
  44165. if( pLock->iTable!=1 ){
  44166. sqlite3_free(pLock);
  44167. }
  44168. }else{
  44169. ppIter = &pLock->pNext;
  44170. }
  44171. }
  44172. assert( pBt->isPending==0 || pBt->pWriter );
  44173. if( pBt->pWriter==p ){
  44174. pBt->pWriter = 0;
  44175. pBt->isExclusive = 0;
  44176. pBt->isPending = 0;
  44177. }else if( pBt->nTransaction==2 ){
  44178. /* This function is called when Btree p is concluding its
  44179. ** transaction. If there currently exists a writer, and p is not
  44180. ** that writer, then the number of locks held by connections other
  44181. ** than the writer must be about to drop to zero. In this case
  44182. ** set the isPending flag to 0.
  44183. **
  44184. ** If there is not currently a writer, then BtShared.isPending must
  44185. ** be zero already. So this next line is harmless in that case.
  44186. */
  44187. pBt->isPending = 0;
  44188. }
  44189. }
  44190. /*
  44191. ** This function changes all write-locks held by Btree p into read-locks.
  44192. */
  44193. static void downgradeAllSharedCacheTableLocks(Btree *p){
  44194. BtShared *pBt = p->pBt;
  44195. if( pBt->pWriter==p ){
  44196. BtLock *pLock;
  44197. pBt->pWriter = 0;
  44198. pBt->isExclusive = 0;
  44199. pBt->isPending = 0;
  44200. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  44201. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  44202. pLock->eLock = READ_LOCK;
  44203. }
  44204. }
  44205. }
  44206. #endif /* SQLITE_OMIT_SHARED_CACHE */
  44207. static void releasePage(MemPage *pPage); /* Forward reference */
  44208. /*
  44209. ***** This routine is used inside of assert() only ****
  44210. **
  44211. ** Verify that the cursor holds the mutex on its BtShared
  44212. */
  44213. #ifdef SQLITE_DEBUG
  44214. static int cursorHoldsMutex(BtCursor *p){
  44215. return sqlite3_mutex_held(p->pBt->mutex);
  44216. }
  44217. #endif
  44218. #ifndef SQLITE_OMIT_INCRBLOB
  44219. /*
  44220. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  44221. */
  44222. static void invalidateOverflowCache(BtCursor *pCur){
  44223. assert( cursorHoldsMutex(pCur) );
  44224. sqlite3_free(pCur->aOverflow);
  44225. pCur->aOverflow = 0;
  44226. }
  44227. /*
  44228. ** Invalidate the overflow page-list cache for all cursors opened
  44229. ** on the shared btree structure pBt.
  44230. */
  44231. static void invalidateAllOverflowCache(BtShared *pBt){
  44232. BtCursor *p;
  44233. assert( sqlite3_mutex_held(pBt->mutex) );
  44234. for(p=pBt->pCursor; p; p=p->pNext){
  44235. invalidateOverflowCache(p);
  44236. }
  44237. }
  44238. /*
  44239. ** This function is called before modifying the contents of a table
  44240. ** to invalidate any incrblob cursors that are open on the
  44241. ** row or one of the rows being modified.
  44242. **
  44243. ** If argument isClearTable is true, then the entire contents of the
  44244. ** table is about to be deleted. In this case invalidate all incrblob
  44245. ** cursors open on any row within the table with root-page pgnoRoot.
  44246. **
  44247. ** Otherwise, if argument isClearTable is false, then the row with
  44248. ** rowid iRow is being replaced or deleted. In this case invalidate
  44249. ** only those incrblob cursors open on that specific row.
  44250. */
  44251. static void invalidateIncrblobCursors(
  44252. Btree *pBtree, /* The database file to check */
  44253. i64 iRow, /* The rowid that might be changing */
  44254. int isClearTable /* True if all rows are being deleted */
  44255. ){
  44256. BtCursor *p;
  44257. BtShared *pBt = pBtree->pBt;
  44258. assert( sqlite3BtreeHoldsMutex(pBtree) );
  44259. for(p=pBt->pCursor; p; p=p->pNext){
  44260. if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
  44261. p->eState = CURSOR_INVALID;
  44262. }
  44263. }
  44264. }
  44265. #else
  44266. /* Stub functions when INCRBLOB is omitted */
  44267. #define invalidateOverflowCache(x)
  44268. #define invalidateAllOverflowCache(x)
  44269. #define invalidateIncrblobCursors(x,y,z)
  44270. #endif /* SQLITE_OMIT_INCRBLOB */
  44271. /*
  44272. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  44273. ** when a page that previously contained data becomes a free-list leaf
  44274. ** page.
  44275. **
  44276. ** The BtShared.pHasContent bitvec exists to work around an obscure
  44277. ** bug caused by the interaction of two useful IO optimizations surrounding
  44278. ** free-list leaf pages:
  44279. **
  44280. ** 1) When all data is deleted from a page and the page becomes
  44281. ** a free-list leaf page, the page is not written to the database
  44282. ** (as free-list leaf pages contain no meaningful data). Sometimes
  44283. ** such a page is not even journalled (as it will not be modified,
  44284. ** why bother journalling it?).
  44285. **
  44286. ** 2) When a free-list leaf page is reused, its content is not read
  44287. ** from the database or written to the journal file (why should it
  44288. ** be, if it is not at all meaningful?).
  44289. **
  44290. ** By themselves, these optimizations work fine and provide a handy
  44291. ** performance boost to bulk delete or insert operations. However, if
  44292. ** a page is moved to the free-list and then reused within the same
  44293. ** transaction, a problem comes up. If the page is not journalled when
  44294. ** it is moved to the free-list and it is also not journalled when it
  44295. ** is extracted from the free-list and reused, then the original data
  44296. ** may be lost. In the event of a rollback, it may not be possible
  44297. ** to restore the database to its original configuration.
  44298. **
  44299. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  44300. ** moved to become a free-list leaf page, the corresponding bit is
  44301. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  44302. ** optimization 2 above is omitted if the corresponding bit is already
  44303. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  44304. ** at the end of every transaction.
  44305. */
  44306. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  44307. int rc = SQLITE_OK;
  44308. if( !pBt->pHasContent ){
  44309. assert( pgno<=pBt->nPage );
  44310. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  44311. if( !pBt->pHasContent ){
  44312. rc = SQLITE_NOMEM;
  44313. }
  44314. }
  44315. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  44316. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  44317. }
  44318. return rc;
  44319. }
  44320. /*
  44321. ** Query the BtShared.pHasContent vector.
  44322. **
  44323. ** This function is called when a free-list leaf page is removed from the
  44324. ** free-list for reuse. It returns false if it is safe to retrieve the
  44325. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  44326. */
  44327. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  44328. Bitvec *p = pBt->pHasContent;
  44329. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  44330. }
  44331. /*
  44332. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  44333. ** invoked at the conclusion of each write-transaction.
  44334. */
  44335. static void btreeClearHasContent(BtShared *pBt){
  44336. sqlite3BitvecDestroy(pBt->pHasContent);
  44337. pBt->pHasContent = 0;
  44338. }
  44339. /*
  44340. ** Save the current cursor position in the variables BtCursor.nKey
  44341. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  44342. **
  44343. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  44344. ** prior to calling this routine.
  44345. */
  44346. static int saveCursorPosition(BtCursor *pCur){
  44347. int rc;
  44348. assert( CURSOR_VALID==pCur->eState );
  44349. assert( 0==pCur->pKey );
  44350. assert( cursorHoldsMutex(pCur) );
  44351. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  44352. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  44353. /* If this is an intKey table, then the above call to BtreeKeySize()
  44354. ** stores the integer key in pCur->nKey. In this case this value is
  44355. ** all that is required. Otherwise, if pCur is not open on an intKey
  44356. ** table, then malloc space for and store the pCur->nKey bytes of key
  44357. ** data.
  44358. */
  44359. if( 0==pCur->apPage[0]->intKey ){
  44360. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  44361. if( pKey ){
  44362. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  44363. if( rc==SQLITE_OK ){
  44364. pCur->pKey = pKey;
  44365. }else{
  44366. sqlite3_free(pKey);
  44367. }
  44368. }else{
  44369. rc = SQLITE_NOMEM;
  44370. }
  44371. }
  44372. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  44373. if( rc==SQLITE_OK ){
  44374. int i;
  44375. for(i=0; i<=pCur->iPage; i++){
  44376. releasePage(pCur->apPage[i]);
  44377. pCur->apPage[i] = 0;
  44378. }
  44379. pCur->iPage = -1;
  44380. pCur->eState = CURSOR_REQUIRESEEK;
  44381. }
  44382. invalidateOverflowCache(pCur);
  44383. return rc;
  44384. }
  44385. /*
  44386. ** Save the positions of all cursors (except pExcept) that are open on
  44387. ** the table with root-page iRoot. Usually, this is called just before cursor
  44388. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  44389. */
  44390. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  44391. BtCursor *p;
  44392. assert( sqlite3_mutex_held(pBt->mutex) );
  44393. assert( pExcept==0 || pExcept->pBt==pBt );
  44394. for(p=pBt->pCursor; p; p=p->pNext){
  44395. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
  44396. p->eState==CURSOR_VALID ){
  44397. int rc = saveCursorPosition(p);
  44398. if( SQLITE_OK!=rc ){
  44399. return rc;
  44400. }
  44401. }
  44402. }
  44403. return SQLITE_OK;
  44404. }
  44405. /*
  44406. ** Clear the current cursor position.
  44407. */
  44408. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  44409. assert( cursorHoldsMutex(pCur) );
  44410. sqlite3_free(pCur->pKey);
  44411. pCur->pKey = 0;
  44412. pCur->eState = CURSOR_INVALID;
  44413. }
  44414. /*
  44415. ** In this version of BtreeMoveto, pKey is a packed index record
  44416. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  44417. ** record and then call BtreeMovetoUnpacked() to do the work.
  44418. */
  44419. static int btreeMoveto(
  44420. BtCursor *pCur, /* Cursor open on the btree to be searched */
  44421. const void *pKey, /* Packed key if the btree is an index */
  44422. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  44423. int bias, /* Bias search to the high end */
  44424. int *pRes /* Write search results here */
  44425. ){
  44426. int rc; /* Status code */
  44427. UnpackedRecord *pIdxKey; /* Unpacked index key */
  44428. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  44429. if( pKey ){
  44430. assert( nKey==(i64)(int)nKey );
  44431. pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
  44432. aSpace, sizeof(aSpace));
  44433. if( pIdxKey==0 ) return SQLITE_NOMEM;
  44434. }else{
  44435. pIdxKey = 0;
  44436. }
  44437. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  44438. if( pKey ){
  44439. sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
  44440. }
  44441. return rc;
  44442. }
  44443. /*
  44444. ** Restore the cursor to the position it was in (or as close to as possible)
  44445. ** when saveCursorPosition() was called. Note that this call deletes the
  44446. ** saved position info stored by saveCursorPosition(), so there can be
  44447. ** at most one effective restoreCursorPosition() call after each
  44448. ** saveCursorPosition().
  44449. */
  44450. static int btreeRestoreCursorPosition(BtCursor *pCur){
  44451. int rc;
  44452. assert( cursorHoldsMutex(pCur) );
  44453. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  44454. if( pCur->eState==CURSOR_FAULT ){
  44455. return pCur->skipNext;
  44456. }
  44457. pCur->eState = CURSOR_INVALID;
  44458. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  44459. if( rc==SQLITE_OK ){
  44460. sqlite3_free(pCur->pKey);
  44461. pCur->pKey = 0;
  44462. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  44463. }
  44464. return rc;
  44465. }
  44466. #define restoreCursorPosition(p) \
  44467. (p->eState>=CURSOR_REQUIRESEEK ? \
  44468. btreeRestoreCursorPosition(p) : \
  44469. SQLITE_OK)
  44470. /*
  44471. ** Determine whether or not a cursor has moved from the position it
  44472. ** was last placed at. Cursors can move when the row they are pointing
  44473. ** at is deleted out from under them.
  44474. **
  44475. ** This routine returns an error code if something goes wrong. The
  44476. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  44477. */
  44478. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  44479. int rc;
  44480. rc = restoreCursorPosition(pCur);
  44481. if( rc ){
  44482. *pHasMoved = 1;
  44483. return rc;
  44484. }
  44485. if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
  44486. *pHasMoved = 1;
  44487. }else{
  44488. *pHasMoved = 0;
  44489. }
  44490. return SQLITE_OK;
  44491. }
  44492. #ifndef SQLITE_OMIT_AUTOVACUUM
  44493. /*
  44494. ** Given a page number of a regular database page, return the page
  44495. ** number for the pointer-map page that contains the entry for the
  44496. ** input page number.
  44497. **
  44498. ** Return 0 (not a valid page) for pgno==1 since there is
  44499. ** no pointer map associated with page 1. The integrity_check logic
  44500. ** requires that ptrmapPageno(*,1)!=1.
  44501. */
  44502. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  44503. int nPagesPerMapPage;
  44504. Pgno iPtrMap, ret;
  44505. assert( sqlite3_mutex_held(pBt->mutex) );
  44506. if( pgno<2 ) return 0;
  44507. nPagesPerMapPage = (pBt->usableSize/5)+1;
  44508. iPtrMap = (pgno-2)/nPagesPerMapPage;
  44509. ret = (iPtrMap*nPagesPerMapPage) + 2;
  44510. if( ret==PENDING_BYTE_PAGE(pBt) ){
  44511. ret++;
  44512. }
  44513. return ret;
  44514. }
  44515. /*
  44516. ** Write an entry into the pointer map.
  44517. **
  44518. ** This routine updates the pointer map entry for page number 'key'
  44519. ** so that it maps to type 'eType' and parent page number 'pgno'.
  44520. **
  44521. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  44522. ** a no-op. If an error occurs, the appropriate error code is written
  44523. ** into *pRC.
  44524. */
  44525. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  44526. DbPage *pDbPage; /* The pointer map page */
  44527. u8 *pPtrmap; /* The pointer map data */
  44528. Pgno iPtrmap; /* The pointer map page number */
  44529. int offset; /* Offset in pointer map page */
  44530. int rc; /* Return code from subfunctions */
  44531. if( *pRC ) return;
  44532. assert( sqlite3_mutex_held(pBt->mutex) );
  44533. /* The master-journal page number must never be used as a pointer map page */
  44534. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  44535. assert( pBt->autoVacuum );
  44536. if( key==0 ){
  44537. *pRC = SQLITE_CORRUPT_BKPT;
  44538. return;
  44539. }
  44540. iPtrmap = PTRMAP_PAGENO(pBt, key);
  44541. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  44542. if( rc!=SQLITE_OK ){
  44543. *pRC = rc;
  44544. return;
  44545. }
  44546. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  44547. if( offset<0 ){
  44548. *pRC = SQLITE_CORRUPT_BKPT;
  44549. goto ptrmap_exit;
  44550. }
  44551. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  44552. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  44553. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  44554. *pRC= rc = sqlite3PagerWrite(pDbPage);
  44555. if( rc==SQLITE_OK ){
  44556. pPtrmap[offset] = eType;
  44557. put4byte(&pPtrmap[offset+1], parent);
  44558. }
  44559. }
  44560. ptrmap_exit:
  44561. sqlite3PagerUnref(pDbPage);
  44562. }
  44563. /*
  44564. ** Read an entry from the pointer map.
  44565. **
  44566. ** This routine retrieves the pointer map entry for page 'key', writing
  44567. ** the type and parent page number to *pEType and *pPgno respectively.
  44568. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  44569. */
  44570. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  44571. DbPage *pDbPage; /* The pointer map page */
  44572. int iPtrmap; /* Pointer map page index */
  44573. u8 *pPtrmap; /* Pointer map page data */
  44574. int offset; /* Offset of entry in pointer map */
  44575. int rc;
  44576. assert( sqlite3_mutex_held(pBt->mutex) );
  44577. iPtrmap = PTRMAP_PAGENO(pBt, key);
  44578. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  44579. if( rc!=0 ){
  44580. return rc;
  44581. }
  44582. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  44583. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  44584. assert( pEType!=0 );
  44585. *pEType = pPtrmap[offset];
  44586. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  44587. sqlite3PagerUnref(pDbPage);
  44588. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  44589. return SQLITE_OK;
  44590. }
  44591. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  44592. #define ptrmapPut(w,x,y,z,rc)
  44593. #define ptrmapGet(w,x,y,z) SQLITE_OK
  44594. #define ptrmapPutOvflPtr(x, y, rc)
  44595. #endif
  44596. /*
  44597. ** Given a btree page and a cell index (0 means the first cell on
  44598. ** the page, 1 means the second cell, and so forth) return a pointer
  44599. ** to the cell content.
  44600. **
  44601. ** This routine works only for pages that do not contain overflow cells.
  44602. */
  44603. #define findCell(P,I) \
  44604. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
  44605. /*
  44606. ** This a more complex version of findCell() that works for
  44607. ** pages that do contain overflow cells.
  44608. */
  44609. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  44610. int i;
  44611. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  44612. for(i=pPage->nOverflow-1; i>=0; i--){
  44613. int k;
  44614. struct _OvflCell *pOvfl;
  44615. pOvfl = &pPage->aOvfl[i];
  44616. k = pOvfl->idx;
  44617. if( k<=iCell ){
  44618. if( k==iCell ){
  44619. return pOvfl->pCell;
  44620. }
  44621. iCell--;
  44622. }
  44623. }
  44624. return findCell(pPage, iCell);
  44625. }
  44626. /*
  44627. ** Parse a cell content block and fill in the CellInfo structure. There
  44628. ** are two versions of this function. btreeParseCell() takes a
  44629. ** cell index as the second argument and btreeParseCellPtr()
  44630. ** takes a pointer to the body of the cell as its second argument.
  44631. **
  44632. ** Within this file, the parseCell() macro can be called instead of
  44633. ** btreeParseCellPtr(). Using some compilers, this will be faster.
  44634. */
  44635. static void btreeParseCellPtr(
  44636. MemPage *pPage, /* Page containing the cell */
  44637. u8 *pCell, /* Pointer to the cell text. */
  44638. CellInfo *pInfo /* Fill in this structure */
  44639. ){
  44640. u16 n; /* Number bytes in cell content header */
  44641. u32 nPayload; /* Number of bytes of cell payload */
  44642. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  44643. pInfo->pCell = pCell;
  44644. assert( pPage->leaf==0 || pPage->leaf==1 );
  44645. n = pPage->childPtrSize;
  44646. assert( n==4-4*pPage->leaf );
  44647. if( pPage->intKey ){
  44648. if( pPage->hasData ){
  44649. n += getVarint32(&pCell[n], nPayload);
  44650. }else{
  44651. nPayload = 0;
  44652. }
  44653. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  44654. pInfo->nData = nPayload;
  44655. }else{
  44656. pInfo->nData = 0;
  44657. n += getVarint32(&pCell[n], nPayload);
  44658. pInfo->nKey = nPayload;
  44659. }
  44660. pInfo->nPayload = nPayload;
  44661. pInfo->nHeader = n;
  44662. testcase( nPayload==pPage->maxLocal );
  44663. testcase( nPayload==pPage->maxLocal+1 );
  44664. if( likely(nPayload<=pPage->maxLocal) ){
  44665. /* This is the (easy) common case where the entire payload fits
  44666. ** on the local page. No overflow is required.
  44667. */
  44668. if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
  44669. pInfo->nLocal = (u16)nPayload;
  44670. pInfo->iOverflow = 0;
  44671. }else{
  44672. /* If the payload will not fit completely on the local page, we have
  44673. ** to decide how much to store locally and how much to spill onto
  44674. ** overflow pages. The strategy is to minimize the amount of unused
  44675. ** space on overflow pages while keeping the amount of local storage
  44676. ** in between minLocal and maxLocal.
  44677. **
  44678. ** Warning: changing the way overflow payload is distributed in any
  44679. ** way will result in an incompatible file format.
  44680. */
  44681. int minLocal; /* Minimum amount of payload held locally */
  44682. int maxLocal; /* Maximum amount of payload held locally */
  44683. int surplus; /* Overflow payload available for local storage */
  44684. minLocal = pPage->minLocal;
  44685. maxLocal = pPage->maxLocal;
  44686. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  44687. testcase( surplus==maxLocal );
  44688. testcase( surplus==maxLocal+1 );
  44689. if( surplus <= maxLocal ){
  44690. pInfo->nLocal = (u16)surplus;
  44691. }else{
  44692. pInfo->nLocal = (u16)minLocal;
  44693. }
  44694. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  44695. pInfo->nSize = pInfo->iOverflow + 4;
  44696. }
  44697. }
  44698. #define parseCell(pPage, iCell, pInfo) \
  44699. btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  44700. static void btreeParseCell(
  44701. MemPage *pPage, /* Page containing the cell */
  44702. int iCell, /* The cell index. First cell is 0 */
  44703. CellInfo *pInfo /* Fill in this structure */
  44704. ){
  44705. parseCell(pPage, iCell, pInfo);
  44706. }
  44707. /*
  44708. ** Compute the total number of bytes that a Cell needs in the cell
  44709. ** data area of the btree-page. The return number includes the cell
  44710. ** data header and the local payload, but not any overflow page or
  44711. ** the space used by the cell pointer.
  44712. */
  44713. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  44714. u8 *pIter = &pCell[pPage->childPtrSize];
  44715. u32 nSize;
  44716. #ifdef SQLITE_DEBUG
  44717. /* The value returned by this function should always be the same as
  44718. ** the (CellInfo.nSize) value found by doing a full parse of the
  44719. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  44720. ** this function verifies that this invariant is not violated. */
  44721. CellInfo debuginfo;
  44722. btreeParseCellPtr(pPage, pCell, &debuginfo);
  44723. #endif
  44724. if( pPage->intKey ){
  44725. u8 *pEnd;
  44726. if( pPage->hasData ){
  44727. pIter += getVarint32(pIter, nSize);
  44728. }else{
  44729. nSize = 0;
  44730. }
  44731. /* pIter now points at the 64-bit integer key value, a variable length
  44732. ** integer. The following block moves pIter to point at the first byte
  44733. ** past the end of the key value. */
  44734. pEnd = &pIter[9];
  44735. while( (*pIter++)&0x80 && pIter<pEnd );
  44736. }else{
  44737. pIter += getVarint32(pIter, nSize);
  44738. }
  44739. testcase( nSize==pPage->maxLocal );
  44740. testcase( nSize==pPage->maxLocal+1 );
  44741. if( nSize>pPage->maxLocal ){
  44742. int minLocal = pPage->minLocal;
  44743. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  44744. testcase( nSize==pPage->maxLocal );
  44745. testcase( nSize==pPage->maxLocal+1 );
  44746. if( nSize>pPage->maxLocal ){
  44747. nSize = minLocal;
  44748. }
  44749. nSize += 4;
  44750. }
  44751. nSize += (u32)(pIter - pCell);
  44752. /* The minimum size of any cell is 4 bytes. */
  44753. if( nSize<4 ){
  44754. nSize = 4;
  44755. }
  44756. assert( nSize==debuginfo.nSize );
  44757. return (u16)nSize;
  44758. }
  44759. #ifdef SQLITE_DEBUG
  44760. /* This variation on cellSizePtr() is used inside of assert() statements
  44761. ** only. */
  44762. static u16 cellSize(MemPage *pPage, int iCell){
  44763. return cellSizePtr(pPage, findCell(pPage, iCell));
  44764. }
  44765. #endif
  44766. #ifndef SQLITE_OMIT_AUTOVACUUM
  44767. /*
  44768. ** If the cell pCell, part of page pPage contains a pointer
  44769. ** to an overflow page, insert an entry into the pointer-map
  44770. ** for the overflow page.
  44771. */
  44772. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  44773. CellInfo info;
  44774. if( *pRC ) return;
  44775. assert( pCell!=0 );
  44776. btreeParseCellPtr(pPage, pCell, &info);
  44777. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  44778. if( info.iOverflow ){
  44779. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  44780. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  44781. }
  44782. }
  44783. #endif
  44784. /*
  44785. ** Defragment the page given. All Cells are moved to the
  44786. ** end of the page and all free space is collected into one
  44787. ** big FreeBlk that occurs in between the header and cell
  44788. ** pointer array and the cell content area.
  44789. */
  44790. static int defragmentPage(MemPage *pPage){
  44791. int i; /* Loop counter */
  44792. int pc; /* Address of a i-th cell */
  44793. int hdr; /* Offset to the page header */
  44794. int size; /* Size of a cell */
  44795. int usableSize; /* Number of usable bytes on a page */
  44796. int cellOffset; /* Offset to the cell pointer array */
  44797. int cbrk; /* Offset to the cell content area */
  44798. int nCell; /* Number of cells on the page */
  44799. unsigned char *data; /* The page data */
  44800. unsigned char *temp; /* Temp area for cell content */
  44801. int iCellFirst; /* First allowable cell index */
  44802. int iCellLast; /* Last possible cell index */
  44803. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  44804. assert( pPage->pBt!=0 );
  44805. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  44806. assert( pPage->nOverflow==0 );
  44807. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  44808. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  44809. data = pPage->aData;
  44810. hdr = pPage->hdrOffset;
  44811. cellOffset = pPage->cellOffset;
  44812. nCell = pPage->nCell;
  44813. assert( nCell==get2byte(&data[hdr+3]) );
  44814. usableSize = pPage->pBt->usableSize;
  44815. cbrk = get2byte(&data[hdr+5]);
  44816. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  44817. cbrk = usableSize;
  44818. iCellFirst = cellOffset + 2*nCell;
  44819. iCellLast = usableSize - 4;
  44820. for(i=0; i<nCell; i++){
  44821. u8 *pAddr; /* The i-th cell pointer */
  44822. pAddr = &data[cellOffset + i*2];
  44823. pc = get2byte(pAddr);
  44824. testcase( pc==iCellFirst );
  44825. testcase( pc==iCellLast );
  44826. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  44827. /* These conditions have already been verified in btreeInitPage()
  44828. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  44829. */
  44830. if( pc<iCellFirst || pc>iCellLast ){
  44831. return SQLITE_CORRUPT_BKPT;
  44832. }
  44833. #endif
  44834. assert( pc>=iCellFirst && pc<=iCellLast );
  44835. size = cellSizePtr(pPage, &temp[pc]);
  44836. cbrk -= size;
  44837. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  44838. if( cbrk<iCellFirst ){
  44839. return SQLITE_CORRUPT_BKPT;
  44840. }
  44841. #else
  44842. if( cbrk<iCellFirst || pc+size>usableSize ){
  44843. return SQLITE_CORRUPT_BKPT;
  44844. }
  44845. #endif
  44846. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  44847. testcase( cbrk+size==usableSize );
  44848. testcase( pc+size==usableSize );
  44849. memcpy(&data[cbrk], &temp[pc], size);
  44850. put2byte(pAddr, cbrk);
  44851. }
  44852. assert( cbrk>=iCellFirst );
  44853. put2byte(&data[hdr+5], cbrk);
  44854. data[hdr+1] = 0;
  44855. data[hdr+2] = 0;
  44856. data[hdr+7] = 0;
  44857. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  44858. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  44859. if( cbrk-iCellFirst!=pPage->nFree ){
  44860. return SQLITE_CORRUPT_BKPT;
  44861. }
  44862. return SQLITE_OK;
  44863. }
  44864. /*
  44865. ** Allocate nByte bytes of space from within the B-Tree page passed
  44866. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  44867. ** of the first byte of allocated space. Return either SQLITE_OK or
  44868. ** an error code (usually SQLITE_CORRUPT).
  44869. **
  44870. ** The caller guarantees that there is sufficient space to make the
  44871. ** allocation. This routine might need to defragment in order to bring
  44872. ** all the space together, however. This routine will avoid using
  44873. ** the first two bytes past the cell pointer area since presumably this
  44874. ** allocation is being made in order to insert a new cell, so we will
  44875. ** also end up needing a new cell pointer.
  44876. */
  44877. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  44878. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  44879. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  44880. int nFrag; /* Number of fragmented bytes on pPage */
  44881. int top; /* First byte of cell content area */
  44882. int gap; /* First byte of gap between cell pointers and cell content */
  44883. int rc; /* Integer return code */
  44884. int usableSize; /* Usable size of the page */
  44885. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  44886. assert( pPage->pBt );
  44887. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  44888. assert( nByte>=0 ); /* Minimum cell size is 4 */
  44889. assert( pPage->nFree>=nByte );
  44890. assert( pPage->nOverflow==0 );
  44891. usableSize = pPage->pBt->usableSize;
  44892. assert( nByte < usableSize-8 );
  44893. nFrag = data[hdr+7];
  44894. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  44895. gap = pPage->cellOffset + 2*pPage->nCell;
  44896. top = get2byteNotZero(&data[hdr+5]);
  44897. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  44898. testcase( gap+2==top );
  44899. testcase( gap+1==top );
  44900. testcase( gap==top );
  44901. if( nFrag>=60 ){
  44902. /* Always defragment highly fragmented pages */
  44903. rc = defragmentPage(pPage);
  44904. if( rc ) return rc;
  44905. top = get2byteNotZero(&data[hdr+5]);
  44906. }else if( gap+2<=top ){
  44907. /* Search the freelist looking for a free slot big enough to satisfy
  44908. ** the request. The allocation is made from the first free slot in
  44909. ** the list that is large enough to accomadate it.
  44910. */
  44911. int pc, addr;
  44912. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  44913. int size; /* Size of the free slot */
  44914. if( pc>usableSize-4 || pc<addr+4 ){
  44915. return SQLITE_CORRUPT_BKPT;
  44916. }
  44917. size = get2byte(&data[pc+2]);
  44918. if( size>=nByte ){
  44919. int x = size - nByte;
  44920. testcase( x==4 );
  44921. testcase( x==3 );
  44922. if( x<4 ){
  44923. /* Remove the slot from the free-list. Update the number of
  44924. ** fragmented bytes within the page. */
  44925. memcpy(&data[addr], &data[pc], 2);
  44926. data[hdr+7] = (u8)(nFrag + x);
  44927. }else if( size+pc > usableSize ){
  44928. return SQLITE_CORRUPT_BKPT;
  44929. }else{
  44930. /* The slot remains on the free-list. Reduce its size to account
  44931. ** for the portion used by the new allocation. */
  44932. put2byte(&data[pc+2], x);
  44933. }
  44934. *pIdx = pc + x;
  44935. return SQLITE_OK;
  44936. }
  44937. }
  44938. }
  44939. /* Check to make sure there is enough space in the gap to satisfy
  44940. ** the allocation. If not, defragment.
  44941. */
  44942. testcase( gap+2+nByte==top );
  44943. if( gap+2+nByte>top ){
  44944. rc = defragmentPage(pPage);
  44945. if( rc ) return rc;
  44946. top = get2byteNotZero(&data[hdr+5]);
  44947. assert( gap+nByte<=top );
  44948. }
  44949. /* Allocate memory from the gap in between the cell pointer array
  44950. ** and the cell content area. The btreeInitPage() call has already
  44951. ** validated the freelist. Given that the freelist is valid, there
  44952. ** is no way that the allocation can extend off the end of the page.
  44953. ** The assert() below verifies the previous sentence.
  44954. */
  44955. top -= nByte;
  44956. put2byte(&data[hdr+5], top);
  44957. assert( top+nByte <= (int)pPage->pBt->usableSize );
  44958. *pIdx = top;
  44959. return SQLITE_OK;
  44960. }
  44961. /*
  44962. ** Return a section of the pPage->aData to the freelist.
  44963. ** The first byte of the new free block is pPage->aDisk[start]
  44964. ** and the size of the block is "size" bytes.
  44965. **
  44966. ** Most of the effort here is involved in coalesing adjacent
  44967. ** free blocks into a single big free block.
  44968. */
  44969. static int freeSpace(MemPage *pPage, int start, int size){
  44970. int addr, pbegin, hdr;
  44971. int iLast; /* Largest possible freeblock offset */
  44972. unsigned char *data = pPage->aData;
  44973. assert( pPage->pBt!=0 );
  44974. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  44975. assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  44976. assert( (start + size) <= (int)pPage->pBt->usableSize );
  44977. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  44978. assert( size>=0 ); /* Minimum cell size is 4 */
  44979. if( pPage->pBt->secureDelete ){
  44980. /* Overwrite deleted information with zeros when the secure_delete
  44981. ** option is enabled */
  44982. memset(&data[start], 0, size);
  44983. }
  44984. /* Add the space back into the linked list of freeblocks. Note that
  44985. ** even though the freeblock list was checked by btreeInitPage(),
  44986. ** btreeInitPage() did not detect overlapping cells or
  44987. ** freeblocks that overlapped cells. Nor does it detect when the
  44988. ** cell content area exceeds the value in the page header. If these
  44989. ** situations arise, then subsequent insert operations might corrupt
  44990. ** the freelist. So we do need to check for corruption while scanning
  44991. ** the freelist.
  44992. */
  44993. hdr = pPage->hdrOffset;
  44994. addr = hdr + 1;
  44995. iLast = pPage->pBt->usableSize - 4;
  44996. assert( start<=iLast );
  44997. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  44998. if( pbegin<addr+4 ){
  44999. return SQLITE_CORRUPT_BKPT;
  45000. }
  45001. addr = pbegin;
  45002. }
  45003. if( pbegin>iLast ){
  45004. return SQLITE_CORRUPT_BKPT;
  45005. }
  45006. assert( pbegin>addr || pbegin==0 );
  45007. put2byte(&data[addr], start);
  45008. put2byte(&data[start], pbegin);
  45009. put2byte(&data[start+2], size);
  45010. pPage->nFree = pPage->nFree + (u16)size;
  45011. /* Coalesce adjacent free blocks */
  45012. addr = hdr + 1;
  45013. while( (pbegin = get2byte(&data[addr]))>0 ){
  45014. int pnext, psize, x;
  45015. assert( pbegin>addr );
  45016. assert( pbegin <= (int)pPage->pBt->usableSize-4 );
  45017. pnext = get2byte(&data[pbegin]);
  45018. psize = get2byte(&data[pbegin+2]);
  45019. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  45020. int frag = pnext - (pbegin+psize);
  45021. if( (frag<0) || (frag>(int)data[hdr+7]) ){
  45022. return SQLITE_CORRUPT_BKPT;
  45023. }
  45024. data[hdr+7] -= (u8)frag;
  45025. x = get2byte(&data[pnext]);
  45026. put2byte(&data[pbegin], x);
  45027. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  45028. put2byte(&data[pbegin+2], x);
  45029. }else{
  45030. addr = pbegin;
  45031. }
  45032. }
  45033. /* If the cell content area begins with a freeblock, remove it. */
  45034. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  45035. int top;
  45036. pbegin = get2byte(&data[hdr+1]);
  45037. memcpy(&data[hdr+1], &data[pbegin], 2);
  45038. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  45039. put2byte(&data[hdr+5], top);
  45040. }
  45041. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  45042. return SQLITE_OK;
  45043. }
  45044. /*
  45045. ** Decode the flags byte (the first byte of the header) for a page
  45046. ** and initialize fields of the MemPage structure accordingly.
  45047. **
  45048. ** Only the following combinations are supported. Anything different
  45049. ** indicates a corrupt database files:
  45050. **
  45051. ** PTF_ZERODATA
  45052. ** PTF_ZERODATA | PTF_LEAF
  45053. ** PTF_LEAFDATA | PTF_INTKEY
  45054. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  45055. */
  45056. static int decodeFlags(MemPage *pPage, int flagByte){
  45057. BtShared *pBt; /* A copy of pPage->pBt */
  45058. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  45059. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  45060. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  45061. flagByte &= ~PTF_LEAF;
  45062. pPage->childPtrSize = 4-4*pPage->leaf;
  45063. pBt = pPage->pBt;
  45064. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  45065. pPage->intKey = 1;
  45066. pPage->hasData = pPage->leaf;
  45067. pPage->maxLocal = pBt->maxLeaf;
  45068. pPage->minLocal = pBt->minLeaf;
  45069. }else if( flagByte==PTF_ZERODATA ){
  45070. pPage->intKey = 0;
  45071. pPage->hasData = 0;
  45072. pPage->maxLocal = pBt->maxLocal;
  45073. pPage->minLocal = pBt->minLocal;
  45074. }else{
  45075. return SQLITE_CORRUPT_BKPT;
  45076. }
  45077. return SQLITE_OK;
  45078. }
  45079. /*
  45080. ** Initialize the auxiliary information for a disk block.
  45081. **
  45082. ** Return SQLITE_OK on success. If we see that the page does
  45083. ** not contain a well-formed database page, then return
  45084. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  45085. ** guarantee that the page is well-formed. It only shows that
  45086. ** we failed to detect any corruption.
  45087. */
  45088. static int btreeInitPage(MemPage *pPage){
  45089. assert( pPage->pBt!=0 );
  45090. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  45091. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  45092. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  45093. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  45094. if( !pPage->isInit ){
  45095. u16 pc; /* Address of a freeblock within pPage->aData[] */
  45096. u8 hdr; /* Offset to beginning of page header */
  45097. u8 *data; /* Equal to pPage->aData */
  45098. BtShared *pBt; /* The main btree structure */
  45099. int usableSize; /* Amount of usable space on each page */
  45100. u16 cellOffset; /* Offset from start of page to first cell pointer */
  45101. int nFree; /* Number of unused bytes on the page */
  45102. int top; /* First byte of the cell content area */
  45103. int iCellFirst; /* First allowable cell or freeblock offset */
  45104. int iCellLast; /* Last possible cell or freeblock offset */
  45105. pBt = pPage->pBt;
  45106. hdr = pPage->hdrOffset;
  45107. data = pPage->aData;
  45108. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  45109. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  45110. pPage->maskPage = (u16)(pBt->pageSize - 1);
  45111. pPage->nOverflow = 0;
  45112. usableSize = pBt->usableSize;
  45113. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  45114. top = get2byteNotZero(&data[hdr+5]);
  45115. pPage->nCell = get2byte(&data[hdr+3]);
  45116. if( pPage->nCell>MX_CELL(pBt) ){
  45117. /* To many cells for a single page. The page must be corrupt */
  45118. return SQLITE_CORRUPT_BKPT;
  45119. }
  45120. testcase( pPage->nCell==MX_CELL(pBt) );
  45121. /* A malformed database page might cause us to read past the end
  45122. ** of page when parsing a cell.
  45123. **
  45124. ** The following block of code checks early to see if a cell extends
  45125. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  45126. ** returned if it does.
  45127. */
  45128. iCellFirst = cellOffset + 2*pPage->nCell;
  45129. iCellLast = usableSize - 4;
  45130. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  45131. {
  45132. int i; /* Index into the cell pointer array */
  45133. int sz; /* Size of a cell */
  45134. if( !pPage->leaf ) iCellLast--;
  45135. for(i=0; i<pPage->nCell; i++){
  45136. pc = get2byte(&data[cellOffset+i*2]);
  45137. testcase( pc==iCellFirst );
  45138. testcase( pc==iCellLast );
  45139. if( pc<iCellFirst || pc>iCellLast ){
  45140. return SQLITE_CORRUPT_BKPT;
  45141. }
  45142. sz = cellSizePtr(pPage, &data[pc]);
  45143. testcase( pc+sz==usableSize );
  45144. if( pc+sz>usableSize ){
  45145. return SQLITE_CORRUPT_BKPT;
  45146. }
  45147. }
  45148. if( !pPage->leaf ) iCellLast++;
  45149. }
  45150. #endif
  45151. /* Compute the total free space on the page */
  45152. pc = get2byte(&data[hdr+1]);
  45153. nFree = data[hdr+7] + top;
  45154. while( pc>0 ){
  45155. u16 next, size;
  45156. if( pc<iCellFirst || pc>iCellLast ){
  45157. /* Start of free block is off the page */
  45158. return SQLITE_CORRUPT_BKPT;
  45159. }
  45160. next = get2byte(&data[pc]);
  45161. size = get2byte(&data[pc+2]);
  45162. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  45163. /* Free blocks must be in ascending order. And the last byte of
  45164. ** the free-block must lie on the database page. */
  45165. return SQLITE_CORRUPT_BKPT;
  45166. }
  45167. nFree = nFree + size;
  45168. pc = next;
  45169. }
  45170. /* At this point, nFree contains the sum of the offset to the start
  45171. ** of the cell-content area plus the number of free bytes within
  45172. ** the cell-content area. If this is greater than the usable-size
  45173. ** of the page, then the page must be corrupted. This check also
  45174. ** serves to verify that the offset to the start of the cell-content
  45175. ** area, according to the page header, lies within the page.
  45176. */
  45177. if( nFree>usableSize ){
  45178. return SQLITE_CORRUPT_BKPT;
  45179. }
  45180. pPage->nFree = (u16)(nFree - iCellFirst);
  45181. pPage->isInit = 1;
  45182. }
  45183. return SQLITE_OK;
  45184. }
  45185. /*
  45186. ** Set up a raw page so that it looks like a database page holding
  45187. ** no entries.
  45188. */
  45189. static void zeroPage(MemPage *pPage, int flags){
  45190. unsigned char *data = pPage->aData;
  45191. BtShared *pBt = pPage->pBt;
  45192. u8 hdr = pPage->hdrOffset;
  45193. u16 first;
  45194. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  45195. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  45196. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  45197. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  45198. assert( sqlite3_mutex_held(pBt->mutex) );
  45199. if( pBt->secureDelete ){
  45200. memset(&data[hdr], 0, pBt->usableSize - hdr);
  45201. }
  45202. data[hdr] = (char)flags;
  45203. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  45204. memset(&data[hdr+1], 0, 4);
  45205. data[hdr+7] = 0;
  45206. put2byte(&data[hdr+5], pBt->usableSize);
  45207. pPage->nFree = (u16)(pBt->usableSize - first);
  45208. decodeFlags(pPage, flags);
  45209. pPage->hdrOffset = hdr;
  45210. pPage->cellOffset = first;
  45211. pPage->nOverflow = 0;
  45212. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  45213. pPage->maskPage = (u16)(pBt->pageSize - 1);
  45214. pPage->nCell = 0;
  45215. pPage->isInit = 1;
  45216. }
  45217. /*
  45218. ** Convert a DbPage obtained from the pager into a MemPage used by
  45219. ** the btree layer.
  45220. */
  45221. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  45222. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  45223. pPage->aData = sqlite3PagerGetData(pDbPage);
  45224. pPage->pDbPage = pDbPage;
  45225. pPage->pBt = pBt;
  45226. pPage->pgno = pgno;
  45227. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  45228. return pPage;
  45229. }
  45230. /*
  45231. ** Get a page from the pager. Initialize the MemPage.pBt and
  45232. ** MemPage.aData elements if needed.
  45233. **
  45234. ** If the noContent flag is set, it means that we do not care about
  45235. ** the content of the page at this time. So do not go to the disk
  45236. ** to fetch the content. Just fill in the content with zeros for now.
  45237. ** If in the future we call sqlite3PagerWrite() on this page, that
  45238. ** means we have started to be concerned about content and the disk
  45239. ** read should occur at that point.
  45240. */
  45241. static int btreeGetPage(
  45242. BtShared *pBt, /* The btree */
  45243. Pgno pgno, /* Number of the page to fetch */
  45244. MemPage **ppPage, /* Return the page in this parameter */
  45245. int noContent /* Do not load page content if true */
  45246. ){
  45247. int rc;
  45248. DbPage *pDbPage;
  45249. assert( sqlite3_mutex_held(pBt->mutex) );
  45250. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
  45251. if( rc ) return rc;
  45252. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  45253. return SQLITE_OK;
  45254. }
  45255. /*
  45256. ** Retrieve a page from the pager cache. If the requested page is not
  45257. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  45258. ** MemPage.aData elements if needed.
  45259. */
  45260. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  45261. DbPage *pDbPage;
  45262. assert( sqlite3_mutex_held(pBt->mutex) );
  45263. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  45264. if( pDbPage ){
  45265. return btreePageFromDbPage(pDbPage, pgno, pBt);
  45266. }
  45267. return 0;
  45268. }
  45269. /*
  45270. ** Return the size of the database file in pages. If there is any kind of
  45271. ** error, return ((unsigned int)-1).
  45272. */
  45273. static Pgno btreePagecount(BtShared *pBt){
  45274. return pBt->nPage;
  45275. }
  45276. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  45277. assert( sqlite3BtreeHoldsMutex(p) );
  45278. assert( ((p->pBt->nPage)&0x8000000)==0 );
  45279. return (int)btreePagecount(p->pBt);
  45280. }
  45281. /*
  45282. ** Get a page from the pager and initialize it. This routine is just a
  45283. ** convenience wrapper around separate calls to btreeGetPage() and
  45284. ** btreeInitPage().
  45285. **
  45286. ** If an error occurs, then the value *ppPage is set to is undefined. It
  45287. ** may remain unchanged, or it may be set to an invalid value.
  45288. */
  45289. static int getAndInitPage(
  45290. BtShared *pBt, /* The database file */
  45291. Pgno pgno, /* Number of the page to get */
  45292. MemPage **ppPage /* Write the page pointer here */
  45293. ){
  45294. int rc;
  45295. assert( sqlite3_mutex_held(pBt->mutex) );
  45296. if( pgno>btreePagecount(pBt) ){
  45297. rc = SQLITE_CORRUPT_BKPT;
  45298. }else{
  45299. rc = btreeGetPage(pBt, pgno, ppPage, 0);
  45300. if( rc==SQLITE_OK ){
  45301. rc = btreeInitPage(*ppPage);
  45302. if( rc!=SQLITE_OK ){
  45303. releasePage(*ppPage);
  45304. }
  45305. }
  45306. }
  45307. testcase( pgno==0 );
  45308. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  45309. return rc;
  45310. }
  45311. /*
  45312. ** Release a MemPage. This should be called once for each prior
  45313. ** call to btreeGetPage.
  45314. */
  45315. static void releasePage(MemPage *pPage){
  45316. if( pPage ){
  45317. assert( pPage->aData );
  45318. assert( pPage->pBt );
  45319. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  45320. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  45321. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  45322. sqlite3PagerUnref(pPage->pDbPage);
  45323. }
  45324. }
  45325. /*
  45326. ** During a rollback, when the pager reloads information into the cache
  45327. ** so that the cache is restored to its original state at the start of
  45328. ** the transaction, for each page restored this routine is called.
  45329. **
  45330. ** This routine needs to reset the extra data section at the end of the
  45331. ** page to agree with the restored data.
  45332. */
  45333. static void pageReinit(DbPage *pData){
  45334. MemPage *pPage;
  45335. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  45336. assert( sqlite3PagerPageRefcount(pData)>0 );
  45337. if( pPage->isInit ){
  45338. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  45339. pPage->isInit = 0;
  45340. if( sqlite3PagerPageRefcount(pData)>1 ){
  45341. /* pPage might not be a btree page; it might be an overflow page
  45342. ** or ptrmap page or a free page. In those cases, the following
  45343. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  45344. ** But no harm is done by this. And it is very important that
  45345. ** btreeInitPage() be called on every btree page so we make
  45346. ** the call for every page that comes in for re-initing. */
  45347. btreeInitPage(pPage);
  45348. }
  45349. }
  45350. }
  45351. /*
  45352. ** Invoke the busy handler for a btree.
  45353. */
  45354. static int btreeInvokeBusyHandler(void *pArg){
  45355. BtShared *pBt = (BtShared*)pArg;
  45356. assert( pBt->db );
  45357. assert( sqlite3_mutex_held(pBt->db->mutex) );
  45358. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  45359. }
  45360. /*
  45361. ** Open a database file.
  45362. **
  45363. ** zFilename is the name of the database file. If zFilename is NULL
  45364. ** then an ephemeral database is created. The ephemeral database might
  45365. ** be exclusively in memory, or it might use a disk-based memory cache.
  45366. ** Either way, the ephemeral database will be automatically deleted
  45367. ** when sqlite3BtreeClose() is called.
  45368. **
  45369. ** If zFilename is ":memory:" then an in-memory database is created
  45370. ** that is automatically destroyed when it is closed.
  45371. **
  45372. ** The "flags" parameter is a bitmask that might contain bits
  45373. ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
  45374. ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
  45375. ** These flags are passed through into sqlite3PagerOpen() and must
  45376. ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
  45377. **
  45378. ** If the database is already opened in the same database connection
  45379. ** and we are in shared cache mode, then the open will fail with an
  45380. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  45381. ** objects in the same database connection since doing so will lead
  45382. ** to problems with locking.
  45383. */
  45384. SQLITE_PRIVATE int sqlite3BtreeOpen(
  45385. const char *zFilename, /* Name of the file containing the BTree database */
  45386. sqlite3 *db, /* Associated database handle */
  45387. Btree **ppBtree, /* Pointer to new Btree object written here */
  45388. int flags, /* Options */
  45389. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  45390. ){
  45391. sqlite3_vfs *pVfs; /* The VFS to use for this btree */
  45392. BtShared *pBt = 0; /* Shared part of btree structure */
  45393. Btree *p; /* Handle to return */
  45394. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  45395. int rc = SQLITE_OK; /* Result code from this function */
  45396. u8 nReserve; /* Byte of unused space on each page */
  45397. unsigned char zDbHeader[100]; /* Database header content */
  45398. /* True if opening an ephemeral, temporary database */
  45399. const int isTempDb = zFilename==0 || zFilename[0]==0;
  45400. /* Set the variable isMemdb to true for an in-memory database, or
  45401. ** false for a file-based database.
  45402. */
  45403. #ifdef SQLITE_OMIT_MEMORYDB
  45404. const int isMemdb = 0;
  45405. #else
  45406. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  45407. || (isTempDb && sqlite3TempInMemory(db));
  45408. #endif
  45409. assert( db!=0 );
  45410. assert( sqlite3_mutex_held(db->mutex) );
  45411. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  45412. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  45413. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  45414. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  45415. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  45416. if( db->flags & SQLITE_NoReadlock ){
  45417. flags |= BTREE_NO_READLOCK;
  45418. }
  45419. if( isMemdb ){
  45420. flags |= BTREE_MEMORY;
  45421. }
  45422. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  45423. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  45424. }
  45425. pVfs = db->pVfs;
  45426. p = sqlite3MallocZero(sizeof(Btree));
  45427. if( !p ){
  45428. return SQLITE_NOMEM;
  45429. }
  45430. p->inTrans = TRANS_NONE;
  45431. p->db = db;
  45432. #ifndef SQLITE_OMIT_SHARED_CACHE
  45433. p->lock.pBtree = p;
  45434. p->lock.iTable = 1;
  45435. #endif
  45436. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  45437. /*
  45438. ** If this Btree is a candidate for shared cache, try to find an
  45439. ** existing BtShared object that we can share with
  45440. */
  45441. if( isMemdb==0 && isTempDb==0 ){
  45442. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  45443. int nFullPathname = pVfs->mxPathname+1;
  45444. char *zFullPathname = sqlite3Malloc(nFullPathname);
  45445. sqlite3_mutex *mutexShared;
  45446. p->sharable = 1;
  45447. if( !zFullPathname ){
  45448. sqlite3_free(p);
  45449. return SQLITE_NOMEM;
  45450. }
  45451. sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
  45452. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  45453. sqlite3_mutex_enter(mutexOpen);
  45454. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  45455. sqlite3_mutex_enter(mutexShared);
  45456. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  45457. assert( pBt->nRef>0 );
  45458. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
  45459. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  45460. int iDb;
  45461. for(iDb=db->nDb-1; iDb>=0; iDb--){
  45462. Btree *pExisting = db->aDb[iDb].pBt;
  45463. if( pExisting && pExisting->pBt==pBt ){
  45464. sqlite3_mutex_leave(mutexShared);
  45465. sqlite3_mutex_leave(mutexOpen);
  45466. sqlite3_free(zFullPathname);
  45467. sqlite3_free(p);
  45468. return SQLITE_CONSTRAINT;
  45469. }
  45470. }
  45471. p->pBt = pBt;
  45472. pBt->nRef++;
  45473. break;
  45474. }
  45475. }
  45476. sqlite3_mutex_leave(mutexShared);
  45477. sqlite3_free(zFullPathname);
  45478. }
  45479. #ifdef SQLITE_DEBUG
  45480. else{
  45481. /* In debug mode, we mark all persistent databases as sharable
  45482. ** even when they are not. This exercises the locking code and
  45483. ** gives more opportunity for asserts(sqlite3_mutex_held())
  45484. ** statements to find locking problems.
  45485. */
  45486. p->sharable = 1;
  45487. }
  45488. #endif
  45489. }
  45490. #endif
  45491. if( pBt==0 ){
  45492. /*
  45493. ** The following asserts make sure that structures used by the btree are
  45494. ** the right size. This is to guard against size changes that result
  45495. ** when compiling on a different architecture.
  45496. */
  45497. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  45498. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  45499. assert( sizeof(u32)==4 );
  45500. assert( sizeof(u16)==2 );
  45501. assert( sizeof(Pgno)==4 );
  45502. pBt = sqlite3MallocZero( sizeof(*pBt) );
  45503. if( pBt==0 ){
  45504. rc = SQLITE_NOMEM;
  45505. goto btree_open_out;
  45506. }
  45507. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  45508. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  45509. if( rc==SQLITE_OK ){
  45510. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  45511. }
  45512. if( rc!=SQLITE_OK ){
  45513. goto btree_open_out;
  45514. }
  45515. pBt->openFlags = (u8)flags;
  45516. pBt->db = db;
  45517. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  45518. p->pBt = pBt;
  45519. pBt->pCursor = 0;
  45520. pBt->pPage1 = 0;
  45521. pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
  45522. #ifdef SQLITE_SECURE_DELETE
  45523. pBt->secureDelete = 1;
  45524. #endif
  45525. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  45526. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  45527. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  45528. pBt->pageSize = 0;
  45529. #ifndef SQLITE_OMIT_AUTOVACUUM
  45530. /* If the magic name ":memory:" will create an in-memory database, then
  45531. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  45532. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  45533. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  45534. ** regular file-name. In this case the auto-vacuum applies as per normal.
  45535. */
  45536. if( zFilename && !isMemdb ){
  45537. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  45538. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  45539. }
  45540. #endif
  45541. nReserve = 0;
  45542. }else{
  45543. nReserve = zDbHeader[20];
  45544. pBt->pageSizeFixed = 1;
  45545. #ifndef SQLITE_OMIT_AUTOVACUUM
  45546. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  45547. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  45548. #endif
  45549. }
  45550. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  45551. if( rc ) goto btree_open_out;
  45552. pBt->usableSize = pBt->pageSize - nReserve;
  45553. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  45554. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  45555. /* Add the new BtShared object to the linked list sharable BtShareds.
  45556. */
  45557. if( p->sharable ){
  45558. sqlite3_mutex *mutexShared;
  45559. pBt->nRef = 1;
  45560. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  45561. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  45562. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  45563. if( pBt->mutex==0 ){
  45564. rc = SQLITE_NOMEM;
  45565. db->mallocFailed = 0;
  45566. goto btree_open_out;
  45567. }
  45568. }
  45569. sqlite3_mutex_enter(mutexShared);
  45570. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  45571. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  45572. sqlite3_mutex_leave(mutexShared);
  45573. }
  45574. #endif
  45575. }
  45576. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  45577. /* If the new Btree uses a sharable pBtShared, then link the new
  45578. ** Btree into the list of all sharable Btrees for the same connection.
  45579. ** The list is kept in ascending order by pBt address.
  45580. */
  45581. if( p->sharable ){
  45582. int i;
  45583. Btree *pSib;
  45584. for(i=0; i<db->nDb; i++){
  45585. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  45586. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  45587. if( p->pBt<pSib->pBt ){
  45588. p->pNext = pSib;
  45589. p->pPrev = 0;
  45590. pSib->pPrev = p;
  45591. }else{
  45592. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  45593. pSib = pSib->pNext;
  45594. }
  45595. p->pNext = pSib->pNext;
  45596. p->pPrev = pSib;
  45597. if( p->pNext ){
  45598. p->pNext->pPrev = p;
  45599. }
  45600. pSib->pNext = p;
  45601. }
  45602. break;
  45603. }
  45604. }
  45605. }
  45606. #endif
  45607. *ppBtree = p;
  45608. btree_open_out:
  45609. if( rc!=SQLITE_OK ){
  45610. if( pBt && pBt->pPager ){
  45611. sqlite3PagerClose(pBt->pPager);
  45612. }
  45613. sqlite3_free(pBt);
  45614. sqlite3_free(p);
  45615. *ppBtree = 0;
  45616. }else{
  45617. /* If the B-Tree was successfully opened, set the pager-cache size to the
  45618. ** default value. Except, when opening on an existing shared pager-cache,
  45619. ** do not change the pager-cache size.
  45620. */
  45621. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  45622. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  45623. }
  45624. }
  45625. if( mutexOpen ){
  45626. assert( sqlite3_mutex_held(mutexOpen) );
  45627. sqlite3_mutex_leave(mutexOpen);
  45628. }
  45629. return rc;
  45630. }
  45631. /*
  45632. ** Decrement the BtShared.nRef counter. When it reaches zero,
  45633. ** remove the BtShared structure from the sharing list. Return
  45634. ** true if the BtShared.nRef counter reaches zero and return
  45635. ** false if it is still positive.
  45636. */
  45637. static int removeFromSharingList(BtShared *pBt){
  45638. #ifndef SQLITE_OMIT_SHARED_CACHE
  45639. sqlite3_mutex *pMaster;
  45640. BtShared *pList;
  45641. int removed = 0;
  45642. assert( sqlite3_mutex_notheld(pBt->mutex) );
  45643. pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  45644. sqlite3_mutex_enter(pMaster);
  45645. pBt->nRef--;
  45646. if( pBt->nRef<=0 ){
  45647. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  45648. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  45649. }else{
  45650. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  45651. while( ALWAYS(pList) && pList->pNext!=pBt ){
  45652. pList=pList->pNext;
  45653. }
  45654. if( ALWAYS(pList) ){
  45655. pList->pNext = pBt->pNext;
  45656. }
  45657. }
  45658. if( SQLITE_THREADSAFE ){
  45659. sqlite3_mutex_free(pBt->mutex);
  45660. }
  45661. removed = 1;
  45662. }
  45663. sqlite3_mutex_leave(pMaster);
  45664. return removed;
  45665. #else
  45666. return 1;
  45667. #endif
  45668. }
  45669. /*
  45670. ** Make sure pBt->pTmpSpace points to an allocation of
  45671. ** MX_CELL_SIZE(pBt) bytes.
  45672. */
  45673. static void allocateTempSpace(BtShared *pBt){
  45674. if( !pBt->pTmpSpace ){
  45675. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  45676. }
  45677. }
  45678. /*
  45679. ** Free the pBt->pTmpSpace allocation
  45680. */
  45681. static void freeTempSpace(BtShared *pBt){
  45682. sqlite3PageFree( pBt->pTmpSpace);
  45683. pBt->pTmpSpace = 0;
  45684. }
  45685. /*
  45686. ** Close an open database and invalidate all cursors.
  45687. */
  45688. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  45689. BtShared *pBt = p->pBt;
  45690. BtCursor *pCur;
  45691. /* Close all cursors opened via this handle. */
  45692. assert( sqlite3_mutex_held(p->db->mutex) );
  45693. sqlite3BtreeEnter(p);
  45694. pCur = pBt->pCursor;
  45695. while( pCur ){
  45696. BtCursor *pTmp = pCur;
  45697. pCur = pCur->pNext;
  45698. if( pTmp->pBtree==p ){
  45699. sqlite3BtreeCloseCursor(pTmp);
  45700. }
  45701. }
  45702. /* Rollback any active transaction and free the handle structure.
  45703. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  45704. ** this handle.
  45705. */
  45706. sqlite3BtreeRollback(p);
  45707. sqlite3BtreeLeave(p);
  45708. /* If there are still other outstanding references to the shared-btree
  45709. ** structure, return now. The remainder of this procedure cleans
  45710. ** up the shared-btree.
  45711. */
  45712. assert( p->wantToLock==0 && p->locked==0 );
  45713. if( !p->sharable || removeFromSharingList(pBt) ){
  45714. /* The pBt is no longer on the sharing list, so we can access
  45715. ** it without having to hold the mutex.
  45716. **
  45717. ** Clean out and delete the BtShared object.
  45718. */
  45719. assert( !pBt->pCursor );
  45720. sqlite3PagerClose(pBt->pPager);
  45721. if( pBt->xFreeSchema && pBt->pSchema ){
  45722. pBt->xFreeSchema(pBt->pSchema);
  45723. }
  45724. sqlite3DbFree(0, pBt->pSchema);
  45725. freeTempSpace(pBt);
  45726. sqlite3_free(pBt);
  45727. }
  45728. #ifndef SQLITE_OMIT_SHARED_CACHE
  45729. assert( p->wantToLock==0 );
  45730. assert( p->locked==0 );
  45731. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  45732. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  45733. #endif
  45734. sqlite3_free(p);
  45735. return SQLITE_OK;
  45736. }
  45737. /*
  45738. ** Change the limit on the number of pages allowed in the cache.
  45739. **
  45740. ** The maximum number of cache pages is set to the absolute
  45741. ** value of mxPage. If mxPage is negative, the pager will
  45742. ** operate asynchronously - it will not stop to do fsync()s
  45743. ** to insure data is written to the disk surface before
  45744. ** continuing. Transactions still work if synchronous is off,
  45745. ** and the database cannot be corrupted if this program
  45746. ** crashes. But if the operating system crashes or there is
  45747. ** an abrupt power failure when synchronous is off, the database
  45748. ** could be left in an inconsistent and unrecoverable state.
  45749. ** Synchronous is on by default so database corruption is not
  45750. ** normally a worry.
  45751. */
  45752. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  45753. BtShared *pBt = p->pBt;
  45754. assert( sqlite3_mutex_held(p->db->mutex) );
  45755. sqlite3BtreeEnter(p);
  45756. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  45757. sqlite3BtreeLeave(p);
  45758. return SQLITE_OK;
  45759. }
  45760. /*
  45761. ** Change the way data is synced to disk in order to increase or decrease
  45762. ** how well the database resists damage due to OS crashes and power
  45763. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  45764. ** there is a high probability of damage) Level 2 is the default. There
  45765. ** is a very low but non-zero probability of damage. Level 3 reduces the
  45766. ** probability of damage to near zero but with a write performance reduction.
  45767. */
  45768. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  45769. SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
  45770. Btree *p, /* The btree to set the safety level on */
  45771. int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
  45772. int fullSync, /* PRAGMA fullfsync. */
  45773. int ckptFullSync /* PRAGMA checkpoint_fullfync */
  45774. ){
  45775. BtShared *pBt = p->pBt;
  45776. assert( sqlite3_mutex_held(p->db->mutex) );
  45777. assert( level>=1 && level<=3 );
  45778. sqlite3BtreeEnter(p);
  45779. sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
  45780. sqlite3BtreeLeave(p);
  45781. return SQLITE_OK;
  45782. }
  45783. #endif
  45784. /*
  45785. ** Return TRUE if the given btree is set to safety level 1. In other
  45786. ** words, return TRUE if no sync() occurs on the disk files.
  45787. */
  45788. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  45789. BtShared *pBt = p->pBt;
  45790. int rc;
  45791. assert( sqlite3_mutex_held(p->db->mutex) );
  45792. sqlite3BtreeEnter(p);
  45793. assert( pBt && pBt->pPager );
  45794. rc = sqlite3PagerNosync(pBt->pPager);
  45795. sqlite3BtreeLeave(p);
  45796. return rc;
  45797. }
  45798. /*
  45799. ** Change the default pages size and the number of reserved bytes per page.
  45800. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  45801. ** without changing anything.
  45802. **
  45803. ** The page size must be a power of 2 between 512 and 65536. If the page
  45804. ** size supplied does not meet this constraint then the page size is not
  45805. ** changed.
  45806. **
  45807. ** Page sizes are constrained to be a power of two so that the region
  45808. ** of the database file used for locking (beginning at PENDING_BYTE,
  45809. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  45810. ** at the beginning of a page.
  45811. **
  45812. ** If parameter nReserve is less than zero, then the number of reserved
  45813. ** bytes per page is left unchanged.
  45814. **
  45815. ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
  45816. ** and autovacuum mode can no longer be changed.
  45817. */
  45818. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  45819. int rc = SQLITE_OK;
  45820. BtShared *pBt = p->pBt;
  45821. assert( nReserve>=-1 && nReserve<=255 );
  45822. sqlite3BtreeEnter(p);
  45823. if( pBt->pageSizeFixed ){
  45824. sqlite3BtreeLeave(p);
  45825. return SQLITE_READONLY;
  45826. }
  45827. if( nReserve<0 ){
  45828. nReserve = pBt->pageSize - pBt->usableSize;
  45829. }
  45830. assert( nReserve>=0 && nReserve<=255 );
  45831. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  45832. ((pageSize-1)&pageSize)==0 ){
  45833. assert( (pageSize & 7)==0 );
  45834. assert( !pBt->pPage1 && !pBt->pCursor );
  45835. pBt->pageSize = (u32)pageSize;
  45836. freeTempSpace(pBt);
  45837. }
  45838. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  45839. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  45840. if( iFix ) pBt->pageSizeFixed = 1;
  45841. sqlite3BtreeLeave(p);
  45842. return rc;
  45843. }
  45844. /*
  45845. ** Return the currently defined page size
  45846. */
  45847. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  45848. return p->pBt->pageSize;
  45849. }
  45850. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  45851. /*
  45852. ** Return the number of bytes of space at the end of every page that
  45853. ** are intentually left unused. This is the "reserved" space that is
  45854. ** sometimes used by extensions.
  45855. */
  45856. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  45857. int n;
  45858. sqlite3BtreeEnter(p);
  45859. n = p->pBt->pageSize - p->pBt->usableSize;
  45860. sqlite3BtreeLeave(p);
  45861. return n;
  45862. }
  45863. /*
  45864. ** Set the maximum page count for a database if mxPage is positive.
  45865. ** No changes are made if mxPage is 0 or negative.
  45866. ** Regardless of the value of mxPage, return the maximum page count.
  45867. */
  45868. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  45869. int n;
  45870. sqlite3BtreeEnter(p);
  45871. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  45872. sqlite3BtreeLeave(p);
  45873. return n;
  45874. }
  45875. /*
  45876. ** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1,
  45877. ** then make no changes. Always return the value of the secureDelete
  45878. ** setting after the change.
  45879. */
  45880. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  45881. int b;
  45882. if( p==0 ) return 0;
  45883. sqlite3BtreeEnter(p);
  45884. if( newFlag>=0 ){
  45885. p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
  45886. }
  45887. b = p->pBt->secureDelete;
  45888. sqlite3BtreeLeave(p);
  45889. return b;
  45890. }
  45891. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  45892. /*
  45893. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  45894. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  45895. ** is disabled. The default value for the auto-vacuum property is
  45896. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  45897. */
  45898. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  45899. #ifdef SQLITE_OMIT_AUTOVACUUM
  45900. return SQLITE_READONLY;
  45901. #else
  45902. BtShared *pBt = p->pBt;
  45903. int rc = SQLITE_OK;
  45904. u8 av = (u8)autoVacuum;
  45905. sqlite3BtreeEnter(p);
  45906. if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
  45907. rc = SQLITE_READONLY;
  45908. }else{
  45909. pBt->autoVacuum = av ?1:0;
  45910. pBt->incrVacuum = av==2 ?1:0;
  45911. }
  45912. sqlite3BtreeLeave(p);
  45913. return rc;
  45914. #endif
  45915. }
  45916. /*
  45917. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  45918. ** enabled 1 is returned. Otherwise 0.
  45919. */
  45920. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  45921. #ifdef SQLITE_OMIT_AUTOVACUUM
  45922. return BTREE_AUTOVACUUM_NONE;
  45923. #else
  45924. int rc;
  45925. sqlite3BtreeEnter(p);
  45926. rc = (
  45927. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  45928. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  45929. BTREE_AUTOVACUUM_INCR
  45930. );
  45931. sqlite3BtreeLeave(p);
  45932. return rc;
  45933. #endif
  45934. }
  45935. /*
  45936. ** Get a reference to pPage1 of the database file. This will
  45937. ** also acquire a readlock on that file.
  45938. **
  45939. ** SQLITE_OK is returned on success. If the file is not a
  45940. ** well-formed database file, then SQLITE_CORRUPT is returned.
  45941. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  45942. ** is returned if we run out of memory.
  45943. */
  45944. static int lockBtree(BtShared *pBt){
  45945. int rc; /* Result code from subfunctions */
  45946. MemPage *pPage1; /* Page 1 of the database file */
  45947. int nPage; /* Number of pages in the database */
  45948. int nPageFile = 0; /* Number of pages in the database file */
  45949. int nPageHeader; /* Number of pages in the database according to hdr */
  45950. assert( sqlite3_mutex_held(pBt->mutex) );
  45951. assert( pBt->pPage1==0 );
  45952. rc = sqlite3PagerSharedLock(pBt->pPager);
  45953. if( rc!=SQLITE_OK ) return rc;
  45954. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  45955. if( rc!=SQLITE_OK ) return rc;
  45956. /* Do some checking to help insure the file we opened really is
  45957. ** a valid database file.
  45958. */
  45959. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  45960. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  45961. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  45962. nPage = nPageFile;
  45963. }
  45964. if( nPage>0 ){
  45965. u32 pageSize;
  45966. u32 usableSize;
  45967. u8 *page1 = pPage1->aData;
  45968. rc = SQLITE_NOTADB;
  45969. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  45970. goto page1_init_failed;
  45971. }
  45972. #ifdef SQLITE_OMIT_WAL
  45973. if( page1[18]>1 ){
  45974. pBt->readOnly = 1;
  45975. }
  45976. if( page1[19]>1 ){
  45977. goto page1_init_failed;
  45978. }
  45979. #else
  45980. if( page1[18]>2 ){
  45981. pBt->readOnly = 1;
  45982. }
  45983. if( page1[19]>2 ){
  45984. goto page1_init_failed;
  45985. }
  45986. /* If the write version is set to 2, this database should be accessed
  45987. ** in WAL mode. If the log is not already open, open it now. Then
  45988. ** return SQLITE_OK and return without populating BtShared.pPage1.
  45989. ** The caller detects this and calls this function again. This is
  45990. ** required as the version of page 1 currently in the page1 buffer
  45991. ** may not be the latest version - there may be a newer one in the log
  45992. ** file.
  45993. */
  45994. if( page1[19]==2 && pBt->doNotUseWAL==0 ){
  45995. int isOpen = 0;
  45996. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  45997. if( rc!=SQLITE_OK ){
  45998. goto page1_init_failed;
  45999. }else if( isOpen==0 ){
  46000. releasePage(pPage1);
  46001. return SQLITE_OK;
  46002. }
  46003. rc = SQLITE_NOTADB;
  46004. }
  46005. #endif
  46006. /* The maximum embedded fraction must be exactly 25%. And the minimum
  46007. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  46008. ** The original design allowed these amounts to vary, but as of
  46009. ** version 3.6.0, we require them to be fixed.
  46010. */
  46011. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  46012. goto page1_init_failed;
  46013. }
  46014. pageSize = (page1[16]<<8) | (page1[17]<<16);
  46015. if( ((pageSize-1)&pageSize)!=0
  46016. || pageSize>SQLITE_MAX_PAGE_SIZE
  46017. || pageSize<=256
  46018. ){
  46019. goto page1_init_failed;
  46020. }
  46021. assert( (pageSize & 7)==0 );
  46022. usableSize = pageSize - page1[20];
  46023. if( (u32)pageSize!=pBt->pageSize ){
  46024. /* After reading the first page of the database assuming a page size
  46025. ** of BtShared.pageSize, we have discovered that the page-size is
  46026. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  46027. ** zero and return SQLITE_OK. The caller will call this function
  46028. ** again with the correct page-size.
  46029. */
  46030. releasePage(pPage1);
  46031. pBt->usableSize = usableSize;
  46032. pBt->pageSize = pageSize;
  46033. freeTempSpace(pBt);
  46034. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  46035. pageSize-usableSize);
  46036. return rc;
  46037. }
  46038. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  46039. rc = SQLITE_CORRUPT_BKPT;
  46040. goto page1_init_failed;
  46041. }
  46042. if( usableSize<480 ){
  46043. goto page1_init_failed;
  46044. }
  46045. pBt->pageSize = pageSize;
  46046. pBt->usableSize = usableSize;
  46047. #ifndef SQLITE_OMIT_AUTOVACUUM
  46048. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  46049. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  46050. #endif
  46051. }
  46052. /* maxLocal is the maximum amount of payload to store locally for
  46053. ** a cell. Make sure it is small enough so that at least minFanout
  46054. ** cells can will fit on one page. We assume a 10-byte page header.
  46055. ** Besides the payload, the cell must store:
  46056. ** 2-byte pointer to the cell
  46057. ** 4-byte child pointer
  46058. ** 9-byte nKey value
  46059. ** 4-byte nData value
  46060. ** 4-byte overflow page pointer
  46061. ** So a cell consists of a 2-byte pointer, a header which is as much as
  46062. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  46063. ** page pointer.
  46064. */
  46065. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  46066. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  46067. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  46068. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  46069. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  46070. pBt->pPage1 = pPage1;
  46071. pBt->nPage = nPage;
  46072. return SQLITE_OK;
  46073. page1_init_failed:
  46074. releasePage(pPage1);
  46075. pBt->pPage1 = 0;
  46076. return rc;
  46077. }
  46078. /*
  46079. ** If there are no outstanding cursors and we are not in the middle
  46080. ** of a transaction but there is a read lock on the database, then
  46081. ** this routine unrefs the first page of the database file which
  46082. ** has the effect of releasing the read lock.
  46083. **
  46084. ** If there is a transaction in progress, this routine is a no-op.
  46085. */
  46086. static void unlockBtreeIfUnused(BtShared *pBt){
  46087. assert( sqlite3_mutex_held(pBt->mutex) );
  46088. assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
  46089. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  46090. assert( pBt->pPage1->aData );
  46091. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  46092. assert( pBt->pPage1->aData );
  46093. releasePage(pBt->pPage1);
  46094. pBt->pPage1 = 0;
  46095. }
  46096. }
  46097. /*
  46098. ** If pBt points to an empty file then convert that empty file
  46099. ** into a new empty database by initializing the first page of
  46100. ** the database.
  46101. */
  46102. static int newDatabase(BtShared *pBt){
  46103. MemPage *pP1;
  46104. unsigned char *data;
  46105. int rc;
  46106. assert( sqlite3_mutex_held(pBt->mutex) );
  46107. if( pBt->nPage>0 ){
  46108. return SQLITE_OK;
  46109. }
  46110. pP1 = pBt->pPage1;
  46111. assert( pP1!=0 );
  46112. data = pP1->aData;
  46113. rc = sqlite3PagerWrite(pP1->pDbPage);
  46114. if( rc ) return rc;
  46115. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  46116. assert( sizeof(zMagicHeader)==16 );
  46117. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  46118. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  46119. data[18] = 1;
  46120. data[19] = 1;
  46121. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  46122. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  46123. data[21] = 64;
  46124. data[22] = 32;
  46125. data[23] = 32;
  46126. memset(&data[24], 0, 100-24);
  46127. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  46128. pBt->pageSizeFixed = 1;
  46129. #ifndef SQLITE_OMIT_AUTOVACUUM
  46130. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  46131. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  46132. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  46133. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  46134. #endif
  46135. pBt->nPage = 1;
  46136. data[31] = 1;
  46137. return SQLITE_OK;
  46138. }
  46139. /*
  46140. ** Attempt to start a new transaction. A write-transaction
  46141. ** is started if the second argument is nonzero, otherwise a read-
  46142. ** transaction. If the second argument is 2 or more and exclusive
  46143. ** transaction is started, meaning that no other process is allowed
  46144. ** to access the database. A preexisting transaction may not be
  46145. ** upgraded to exclusive by calling this routine a second time - the
  46146. ** exclusivity flag only works for a new transaction.
  46147. **
  46148. ** A write-transaction must be started before attempting any
  46149. ** changes to the database. None of the following routines
  46150. ** will work unless a transaction is started first:
  46151. **
  46152. ** sqlite3BtreeCreateTable()
  46153. ** sqlite3BtreeCreateIndex()
  46154. ** sqlite3BtreeClearTable()
  46155. ** sqlite3BtreeDropTable()
  46156. ** sqlite3BtreeInsert()
  46157. ** sqlite3BtreeDelete()
  46158. ** sqlite3BtreeUpdateMeta()
  46159. **
  46160. ** If an initial attempt to acquire the lock fails because of lock contention
  46161. ** and the database was previously unlocked, then invoke the busy handler
  46162. ** if there is one. But if there was previously a read-lock, do not
  46163. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  46164. ** returned when there is already a read-lock in order to avoid a deadlock.
  46165. **
  46166. ** Suppose there are two processes A and B. A has a read lock and B has
  46167. ** a reserved lock. B tries to promote to exclusive but is blocked because
  46168. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  46169. ** One or the other of the two processes must give way or there can be
  46170. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  46171. ** when A already has a read lock, we encourage A to give up and let B
  46172. ** proceed.
  46173. */
  46174. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  46175. sqlite3 *pBlock = 0;
  46176. BtShared *pBt = p->pBt;
  46177. int rc = SQLITE_OK;
  46178. sqlite3BtreeEnter(p);
  46179. btreeIntegrity(p);
  46180. /* If the btree is already in a write-transaction, or it
  46181. ** is already in a read-transaction and a read-transaction
  46182. ** is requested, this is a no-op.
  46183. */
  46184. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  46185. goto trans_begun;
  46186. }
  46187. /* Write transactions are not possible on a read-only database */
  46188. if( pBt->readOnly && wrflag ){
  46189. rc = SQLITE_READONLY;
  46190. goto trans_begun;
  46191. }
  46192. #ifndef SQLITE_OMIT_SHARED_CACHE
  46193. /* If another database handle has already opened a write transaction
  46194. ** on this shared-btree structure and a second write transaction is
  46195. ** requested, return SQLITE_LOCKED.
  46196. */
  46197. if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
  46198. pBlock = pBt->pWriter->db;
  46199. }else if( wrflag>1 ){
  46200. BtLock *pIter;
  46201. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  46202. if( pIter->pBtree!=p ){
  46203. pBlock = pIter->pBtree->db;
  46204. break;
  46205. }
  46206. }
  46207. }
  46208. if( pBlock ){
  46209. sqlite3ConnectionBlocked(p->db, pBlock);
  46210. rc = SQLITE_LOCKED_SHAREDCACHE;
  46211. goto trans_begun;
  46212. }
  46213. #endif
  46214. /* Any read-only or read-write transaction implies a read-lock on
  46215. ** page 1. So if some other shared-cache client already has a write-lock
  46216. ** on page 1, the transaction cannot be opened. */
  46217. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  46218. if( SQLITE_OK!=rc ) goto trans_begun;
  46219. pBt->initiallyEmpty = (u8)(pBt->nPage==0);
  46220. do {
  46221. /* Call lockBtree() until either pBt->pPage1 is populated or
  46222. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  46223. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  46224. ** reading page 1 it discovers that the page-size of the database
  46225. ** file is not pBt->pageSize. In this case lockBtree() will update
  46226. ** pBt->pageSize to the page-size of the file on disk.
  46227. */
  46228. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  46229. if( rc==SQLITE_OK && wrflag ){
  46230. if( pBt->readOnly ){
  46231. rc = SQLITE_READONLY;
  46232. }else{
  46233. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  46234. if( rc==SQLITE_OK ){
  46235. rc = newDatabase(pBt);
  46236. }
  46237. }
  46238. }
  46239. if( rc!=SQLITE_OK ){
  46240. unlockBtreeIfUnused(pBt);
  46241. }
  46242. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  46243. btreeInvokeBusyHandler(pBt) );
  46244. if( rc==SQLITE_OK ){
  46245. if( p->inTrans==TRANS_NONE ){
  46246. pBt->nTransaction++;
  46247. #ifndef SQLITE_OMIT_SHARED_CACHE
  46248. if( p->sharable ){
  46249. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  46250. p->lock.eLock = READ_LOCK;
  46251. p->lock.pNext = pBt->pLock;
  46252. pBt->pLock = &p->lock;
  46253. }
  46254. #endif
  46255. }
  46256. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  46257. if( p->inTrans>pBt->inTransaction ){
  46258. pBt->inTransaction = p->inTrans;
  46259. }
  46260. if( wrflag ){
  46261. MemPage *pPage1 = pBt->pPage1;
  46262. #ifndef SQLITE_OMIT_SHARED_CACHE
  46263. assert( !pBt->pWriter );
  46264. pBt->pWriter = p;
  46265. pBt->isExclusive = (u8)(wrflag>1);
  46266. #endif
  46267. /* If the db-size header field is incorrect (as it may be if an old
  46268. ** client has been writing the database file), update it now. Doing
  46269. ** this sooner rather than later means the database size can safely
  46270. ** re-read the database size from page 1 if a savepoint or transaction
  46271. ** rollback occurs within the transaction.
  46272. */
  46273. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  46274. rc = sqlite3PagerWrite(pPage1->pDbPage);
  46275. if( rc==SQLITE_OK ){
  46276. put4byte(&pPage1->aData[28], pBt->nPage);
  46277. }
  46278. }
  46279. }
  46280. }
  46281. trans_begun:
  46282. if( rc==SQLITE_OK && wrflag ){
  46283. /* This call makes sure that the pager has the correct number of
  46284. ** open savepoints. If the second parameter is greater than 0 and
  46285. ** the sub-journal is not already open, then it will be opened here.
  46286. */
  46287. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  46288. }
  46289. btreeIntegrity(p);
  46290. sqlite3BtreeLeave(p);
  46291. return rc;
  46292. }
  46293. #ifndef SQLITE_OMIT_AUTOVACUUM
  46294. /*
  46295. ** Set the pointer-map entries for all children of page pPage. Also, if
  46296. ** pPage contains cells that point to overflow pages, set the pointer
  46297. ** map entries for the overflow pages as well.
  46298. */
  46299. static int setChildPtrmaps(MemPage *pPage){
  46300. int i; /* Counter variable */
  46301. int nCell; /* Number of cells in page pPage */
  46302. int rc; /* Return code */
  46303. BtShared *pBt = pPage->pBt;
  46304. u8 isInitOrig = pPage->isInit;
  46305. Pgno pgno = pPage->pgno;
  46306. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46307. rc = btreeInitPage(pPage);
  46308. if( rc!=SQLITE_OK ){
  46309. goto set_child_ptrmaps_out;
  46310. }
  46311. nCell = pPage->nCell;
  46312. for(i=0; i<nCell; i++){
  46313. u8 *pCell = findCell(pPage, i);
  46314. ptrmapPutOvflPtr(pPage, pCell, &rc);
  46315. if( !pPage->leaf ){
  46316. Pgno childPgno = get4byte(pCell);
  46317. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  46318. }
  46319. }
  46320. if( !pPage->leaf ){
  46321. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  46322. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  46323. }
  46324. set_child_ptrmaps_out:
  46325. pPage->isInit = isInitOrig;
  46326. return rc;
  46327. }
  46328. /*
  46329. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  46330. ** that it points to iTo. Parameter eType describes the type of pointer to
  46331. ** be modified, as follows:
  46332. **
  46333. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  46334. ** page of pPage.
  46335. **
  46336. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  46337. ** page pointed to by one of the cells on pPage.
  46338. **
  46339. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  46340. ** overflow page in the list.
  46341. */
  46342. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  46343. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  46344. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  46345. if( eType==PTRMAP_OVERFLOW2 ){
  46346. /* The pointer is always the first 4 bytes of the page in this case. */
  46347. if( get4byte(pPage->aData)!=iFrom ){
  46348. return SQLITE_CORRUPT_BKPT;
  46349. }
  46350. put4byte(pPage->aData, iTo);
  46351. }else{
  46352. u8 isInitOrig = pPage->isInit;
  46353. int i;
  46354. int nCell;
  46355. btreeInitPage(pPage);
  46356. nCell = pPage->nCell;
  46357. for(i=0; i<nCell; i++){
  46358. u8 *pCell = findCell(pPage, i);
  46359. if( eType==PTRMAP_OVERFLOW1 ){
  46360. CellInfo info;
  46361. btreeParseCellPtr(pPage, pCell, &info);
  46362. if( info.iOverflow ){
  46363. if( iFrom==get4byte(&pCell[info.iOverflow]) ){
  46364. put4byte(&pCell[info.iOverflow], iTo);
  46365. break;
  46366. }
  46367. }
  46368. }else{
  46369. if( get4byte(pCell)==iFrom ){
  46370. put4byte(pCell, iTo);
  46371. break;
  46372. }
  46373. }
  46374. }
  46375. if( i==nCell ){
  46376. if( eType!=PTRMAP_BTREE ||
  46377. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  46378. return SQLITE_CORRUPT_BKPT;
  46379. }
  46380. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  46381. }
  46382. pPage->isInit = isInitOrig;
  46383. }
  46384. return SQLITE_OK;
  46385. }
  46386. /*
  46387. ** Move the open database page pDbPage to location iFreePage in the
  46388. ** database. The pDbPage reference remains valid.
  46389. **
  46390. ** The isCommit flag indicates that there is no need to remember that
  46391. ** the journal needs to be sync()ed before database page pDbPage->pgno
  46392. ** can be written to. The caller has already promised not to write to that
  46393. ** page.
  46394. */
  46395. static int relocatePage(
  46396. BtShared *pBt, /* Btree */
  46397. MemPage *pDbPage, /* Open page to move */
  46398. u8 eType, /* Pointer map 'type' entry for pDbPage */
  46399. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  46400. Pgno iFreePage, /* The location to move pDbPage to */
  46401. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  46402. ){
  46403. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  46404. Pgno iDbPage = pDbPage->pgno;
  46405. Pager *pPager = pBt->pPager;
  46406. int rc;
  46407. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  46408. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  46409. assert( sqlite3_mutex_held(pBt->mutex) );
  46410. assert( pDbPage->pBt==pBt );
  46411. /* Move page iDbPage from its current location to page number iFreePage */
  46412. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  46413. iDbPage, iFreePage, iPtrPage, eType));
  46414. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  46415. if( rc!=SQLITE_OK ){
  46416. return rc;
  46417. }
  46418. pDbPage->pgno = iFreePage;
  46419. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  46420. ** that point to overflow pages. The pointer map entries for all these
  46421. ** pages need to be changed.
  46422. **
  46423. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  46424. ** pointer to a subsequent overflow page. If this is the case, then
  46425. ** the pointer map needs to be updated for the subsequent overflow page.
  46426. */
  46427. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  46428. rc = setChildPtrmaps(pDbPage);
  46429. if( rc!=SQLITE_OK ){
  46430. return rc;
  46431. }
  46432. }else{
  46433. Pgno nextOvfl = get4byte(pDbPage->aData);
  46434. if( nextOvfl!=0 ){
  46435. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  46436. if( rc!=SQLITE_OK ){
  46437. return rc;
  46438. }
  46439. }
  46440. }
  46441. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  46442. ** that it points at iFreePage. Also fix the pointer map entry for
  46443. ** iPtrPage.
  46444. */
  46445. if( eType!=PTRMAP_ROOTPAGE ){
  46446. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  46447. if( rc!=SQLITE_OK ){
  46448. return rc;
  46449. }
  46450. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  46451. if( rc!=SQLITE_OK ){
  46452. releasePage(pPtrPage);
  46453. return rc;
  46454. }
  46455. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  46456. releasePage(pPtrPage);
  46457. if( rc==SQLITE_OK ){
  46458. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  46459. }
  46460. }
  46461. return rc;
  46462. }
  46463. /* Forward declaration required by incrVacuumStep(). */
  46464. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  46465. /*
  46466. ** Perform a single step of an incremental-vacuum. If successful,
  46467. ** return SQLITE_OK. If there is no work to do (and therefore no
  46468. ** point in calling this function again), return SQLITE_DONE.
  46469. **
  46470. ** More specificly, this function attempts to re-organize the
  46471. ** database so that the last page of the file currently in use
  46472. ** is no longer in use.
  46473. **
  46474. ** If the nFin parameter is non-zero, this function assumes
  46475. ** that the caller will keep calling incrVacuumStep() until
  46476. ** it returns SQLITE_DONE or an error, and that nFin is the
  46477. ** number of pages the database file will contain after this
  46478. ** process is complete. If nFin is zero, it is assumed that
  46479. ** incrVacuumStep() will be called a finite amount of times
  46480. ** which may or may not empty the freelist. A full autovacuum
  46481. ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==0.
  46482. */
  46483. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
  46484. Pgno nFreeList; /* Number of pages still on the free-list */
  46485. int rc;
  46486. assert( sqlite3_mutex_held(pBt->mutex) );
  46487. assert( iLastPg>nFin );
  46488. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  46489. u8 eType;
  46490. Pgno iPtrPage;
  46491. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  46492. if( nFreeList==0 ){
  46493. return SQLITE_DONE;
  46494. }
  46495. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  46496. if( rc!=SQLITE_OK ){
  46497. return rc;
  46498. }
  46499. if( eType==PTRMAP_ROOTPAGE ){
  46500. return SQLITE_CORRUPT_BKPT;
  46501. }
  46502. if( eType==PTRMAP_FREEPAGE ){
  46503. if( nFin==0 ){
  46504. /* Remove the page from the files free-list. This is not required
  46505. ** if nFin is non-zero. In that case, the free-list will be
  46506. ** truncated to zero after this function returns, so it doesn't
  46507. ** matter if it still contains some garbage entries.
  46508. */
  46509. Pgno iFreePg;
  46510. MemPage *pFreePg;
  46511. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
  46512. if( rc!=SQLITE_OK ){
  46513. return rc;
  46514. }
  46515. assert( iFreePg==iLastPg );
  46516. releasePage(pFreePg);
  46517. }
  46518. } else {
  46519. Pgno iFreePg; /* Index of free page to move pLastPg to */
  46520. MemPage *pLastPg;
  46521. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  46522. if( rc!=SQLITE_OK ){
  46523. return rc;
  46524. }
  46525. /* If nFin is zero, this loop runs exactly once and page pLastPg
  46526. ** is swapped with the first free page pulled off the free list.
  46527. **
  46528. ** On the other hand, if nFin is greater than zero, then keep
  46529. ** looping until a free-page located within the first nFin pages
  46530. ** of the file is found.
  46531. */
  46532. do {
  46533. MemPage *pFreePg;
  46534. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
  46535. if( rc!=SQLITE_OK ){
  46536. releasePage(pLastPg);
  46537. return rc;
  46538. }
  46539. releasePage(pFreePg);
  46540. }while( nFin!=0 && iFreePg>nFin );
  46541. assert( iFreePg<iLastPg );
  46542. rc = sqlite3PagerWrite(pLastPg->pDbPage);
  46543. if( rc==SQLITE_OK ){
  46544. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
  46545. }
  46546. releasePage(pLastPg);
  46547. if( rc!=SQLITE_OK ){
  46548. return rc;
  46549. }
  46550. }
  46551. }
  46552. if( nFin==0 ){
  46553. iLastPg--;
  46554. while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
  46555. if( PTRMAP_ISPAGE(pBt, iLastPg) ){
  46556. MemPage *pPg;
  46557. rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
  46558. if( rc!=SQLITE_OK ){
  46559. return rc;
  46560. }
  46561. rc = sqlite3PagerWrite(pPg->pDbPage);
  46562. releasePage(pPg);
  46563. if( rc!=SQLITE_OK ){
  46564. return rc;
  46565. }
  46566. }
  46567. iLastPg--;
  46568. }
  46569. sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
  46570. pBt->nPage = iLastPg;
  46571. }
  46572. return SQLITE_OK;
  46573. }
  46574. /*
  46575. ** A write-transaction must be opened before calling this function.
  46576. ** It performs a single unit of work towards an incremental vacuum.
  46577. **
  46578. ** If the incremental vacuum is finished after this function has run,
  46579. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  46580. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  46581. */
  46582. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  46583. int rc;
  46584. BtShared *pBt = p->pBt;
  46585. sqlite3BtreeEnter(p);
  46586. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  46587. if( !pBt->autoVacuum ){
  46588. rc = SQLITE_DONE;
  46589. }else{
  46590. invalidateAllOverflowCache(pBt);
  46591. rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
  46592. if( rc==SQLITE_OK ){
  46593. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  46594. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  46595. }
  46596. }
  46597. sqlite3BtreeLeave(p);
  46598. return rc;
  46599. }
  46600. /*
  46601. ** This routine is called prior to sqlite3PagerCommit when a transaction
  46602. ** is commited for an auto-vacuum database.
  46603. **
  46604. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  46605. ** the database file should be truncated to during the commit process.
  46606. ** i.e. the database has been reorganized so that only the first *pnTrunc
  46607. ** pages are in use.
  46608. */
  46609. static int autoVacuumCommit(BtShared *pBt){
  46610. int rc = SQLITE_OK;
  46611. Pager *pPager = pBt->pPager;
  46612. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  46613. assert( sqlite3_mutex_held(pBt->mutex) );
  46614. invalidateAllOverflowCache(pBt);
  46615. assert(pBt->autoVacuum);
  46616. if( !pBt->incrVacuum ){
  46617. Pgno nFin; /* Number of pages in database after autovacuuming */
  46618. Pgno nFree; /* Number of pages on the freelist initially */
  46619. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  46620. Pgno iFree; /* The next page to be freed */
  46621. int nEntry; /* Number of entries on one ptrmap page */
  46622. Pgno nOrig; /* Database size before freeing */
  46623. nOrig = btreePagecount(pBt);
  46624. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  46625. /* It is not possible to create a database for which the final page
  46626. ** is either a pointer-map page or the pending-byte page. If one
  46627. ** is encountered, this indicates corruption.
  46628. */
  46629. return SQLITE_CORRUPT_BKPT;
  46630. }
  46631. nFree = get4byte(&pBt->pPage1->aData[36]);
  46632. nEntry = pBt->usableSize/5;
  46633. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  46634. nFin = nOrig - nFree - nPtrmap;
  46635. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  46636. nFin--;
  46637. }
  46638. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  46639. nFin--;
  46640. }
  46641. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  46642. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  46643. rc = incrVacuumStep(pBt, nFin, iFree);
  46644. }
  46645. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  46646. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  46647. put4byte(&pBt->pPage1->aData[32], 0);
  46648. put4byte(&pBt->pPage1->aData[36], 0);
  46649. put4byte(&pBt->pPage1->aData[28], nFin);
  46650. sqlite3PagerTruncateImage(pBt->pPager, nFin);
  46651. pBt->nPage = nFin;
  46652. }
  46653. if( rc!=SQLITE_OK ){
  46654. sqlite3PagerRollback(pPager);
  46655. }
  46656. }
  46657. assert( nRef==sqlite3PagerRefcount(pPager) );
  46658. return rc;
  46659. }
  46660. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  46661. # define setChildPtrmaps(x) SQLITE_OK
  46662. #endif
  46663. /*
  46664. ** This routine does the first phase of a two-phase commit. This routine
  46665. ** causes a rollback journal to be created (if it does not already exist)
  46666. ** and populated with enough information so that if a power loss occurs
  46667. ** the database can be restored to its original state by playing back
  46668. ** the journal. Then the contents of the journal are flushed out to
  46669. ** the disk. After the journal is safely on oxide, the changes to the
  46670. ** database are written into the database file and flushed to oxide.
  46671. ** At the end of this call, the rollback journal still exists on the
  46672. ** disk and we are still holding all locks, so the transaction has not
  46673. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  46674. ** commit process.
  46675. **
  46676. ** This call is a no-op if no write-transaction is currently active on pBt.
  46677. **
  46678. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  46679. ** the name of a master journal file that should be written into the
  46680. ** individual journal file, or is NULL, indicating no master journal file
  46681. ** (single database transaction).
  46682. **
  46683. ** When this is called, the master journal should already have been
  46684. ** created, populated with this journal pointer and synced to disk.
  46685. **
  46686. ** Once this is routine has returned, the only thing required to commit
  46687. ** the write-transaction for this database file is to delete the journal.
  46688. */
  46689. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  46690. int rc = SQLITE_OK;
  46691. if( p->inTrans==TRANS_WRITE ){
  46692. BtShared *pBt = p->pBt;
  46693. sqlite3BtreeEnter(p);
  46694. #ifndef SQLITE_OMIT_AUTOVACUUM
  46695. if( pBt->autoVacuum ){
  46696. rc = autoVacuumCommit(pBt);
  46697. if( rc!=SQLITE_OK ){
  46698. sqlite3BtreeLeave(p);
  46699. return rc;
  46700. }
  46701. }
  46702. #endif
  46703. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  46704. sqlite3BtreeLeave(p);
  46705. }
  46706. return rc;
  46707. }
  46708. /*
  46709. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  46710. ** at the conclusion of a transaction.
  46711. */
  46712. static void btreeEndTransaction(Btree *p){
  46713. BtShared *pBt = p->pBt;
  46714. assert( sqlite3BtreeHoldsMutex(p) );
  46715. btreeClearHasContent(pBt);
  46716. if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
  46717. /* If there are other active statements that belong to this database
  46718. ** handle, downgrade to a read-only transaction. The other statements
  46719. ** may still be reading from the database. */
  46720. downgradeAllSharedCacheTableLocks(p);
  46721. p->inTrans = TRANS_READ;
  46722. }else{
  46723. /* If the handle had any kind of transaction open, decrement the
  46724. ** transaction count of the shared btree. If the transaction count
  46725. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  46726. ** call below will unlock the pager. */
  46727. if( p->inTrans!=TRANS_NONE ){
  46728. clearAllSharedCacheTableLocks(p);
  46729. pBt->nTransaction--;
  46730. if( 0==pBt->nTransaction ){
  46731. pBt->inTransaction = TRANS_NONE;
  46732. }
  46733. }
  46734. /* Set the current transaction state to TRANS_NONE and unlock the
  46735. ** pager if this call closed the only read or write transaction. */
  46736. p->inTrans = TRANS_NONE;
  46737. unlockBtreeIfUnused(pBt);
  46738. }
  46739. btreeIntegrity(p);
  46740. }
  46741. /*
  46742. ** Commit the transaction currently in progress.
  46743. **
  46744. ** This routine implements the second phase of a 2-phase commit. The
  46745. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  46746. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  46747. ** routine did all the work of writing information out to disk and flushing the
  46748. ** contents so that they are written onto the disk platter. All this
  46749. ** routine has to do is delete or truncate or zero the header in the
  46750. ** the rollback journal (which causes the transaction to commit) and
  46751. ** drop locks.
  46752. **
  46753. ** Normally, if an error occurs while the pager layer is attempting to
  46754. ** finalize the underlying journal file, this function returns an error and
  46755. ** the upper layer will attempt a rollback. However, if the second argument
  46756. ** is non-zero then this b-tree transaction is part of a multi-file
  46757. ** transaction. In this case, the transaction has already been committed
  46758. ** (by deleting a master journal file) and the caller will ignore this
  46759. ** functions return code. So, even if an error occurs in the pager layer,
  46760. ** reset the b-tree objects internal state to indicate that the write
  46761. ** transaction has been closed. This is quite safe, as the pager will have
  46762. ** transitioned to the error state.
  46763. **
  46764. ** This will release the write lock on the database file. If there
  46765. ** are no active cursors, it also releases the read lock.
  46766. */
  46767. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  46768. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  46769. sqlite3BtreeEnter(p);
  46770. btreeIntegrity(p);
  46771. /* If the handle has a write-transaction open, commit the shared-btrees
  46772. ** transaction and set the shared state to TRANS_READ.
  46773. */
  46774. if( p->inTrans==TRANS_WRITE ){
  46775. int rc;
  46776. BtShared *pBt = p->pBt;
  46777. assert( pBt->inTransaction==TRANS_WRITE );
  46778. assert( pBt->nTransaction>0 );
  46779. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  46780. if( rc!=SQLITE_OK && bCleanup==0 ){
  46781. sqlite3BtreeLeave(p);
  46782. return rc;
  46783. }
  46784. pBt->inTransaction = TRANS_READ;
  46785. }
  46786. btreeEndTransaction(p);
  46787. sqlite3BtreeLeave(p);
  46788. return SQLITE_OK;
  46789. }
  46790. /*
  46791. ** Do both phases of a commit.
  46792. */
  46793. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  46794. int rc;
  46795. sqlite3BtreeEnter(p);
  46796. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  46797. if( rc==SQLITE_OK ){
  46798. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  46799. }
  46800. sqlite3BtreeLeave(p);
  46801. return rc;
  46802. }
  46803. #ifndef NDEBUG
  46804. /*
  46805. ** Return the number of write-cursors open on this handle. This is for use
  46806. ** in assert() expressions, so it is only compiled if NDEBUG is not
  46807. ** defined.
  46808. **
  46809. ** For the purposes of this routine, a write-cursor is any cursor that
  46810. ** is capable of writing to the databse. That means the cursor was
  46811. ** originally opened for writing and the cursor has not be disabled
  46812. ** by having its state changed to CURSOR_FAULT.
  46813. */
  46814. static int countWriteCursors(BtShared *pBt){
  46815. BtCursor *pCur;
  46816. int r = 0;
  46817. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  46818. if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
  46819. }
  46820. return r;
  46821. }
  46822. #endif
  46823. /*
  46824. ** This routine sets the state to CURSOR_FAULT and the error
  46825. ** code to errCode for every cursor on BtShared that pBtree
  46826. ** references.
  46827. **
  46828. ** Every cursor is tripped, including cursors that belong
  46829. ** to other database connections that happen to be sharing
  46830. ** the cache with pBtree.
  46831. **
  46832. ** This routine gets called when a rollback occurs.
  46833. ** All cursors using the same cache must be tripped
  46834. ** to prevent them from trying to use the btree after
  46835. ** the rollback. The rollback may have deleted tables
  46836. ** or moved root pages, so it is not sufficient to
  46837. ** save the state of the cursor. The cursor must be
  46838. ** invalidated.
  46839. */
  46840. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  46841. BtCursor *p;
  46842. sqlite3BtreeEnter(pBtree);
  46843. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  46844. int i;
  46845. sqlite3BtreeClearCursor(p);
  46846. p->eState = CURSOR_FAULT;
  46847. p->skipNext = errCode;
  46848. for(i=0; i<=p->iPage; i++){
  46849. releasePage(p->apPage[i]);
  46850. p->apPage[i] = 0;
  46851. }
  46852. }
  46853. sqlite3BtreeLeave(pBtree);
  46854. }
  46855. /*
  46856. ** Rollback the transaction in progress. All cursors will be
  46857. ** invalided by this operation. Any attempt to use a cursor
  46858. ** that was open at the beginning of this operation will result
  46859. ** in an error.
  46860. **
  46861. ** This will release the write lock on the database file. If there
  46862. ** are no active cursors, it also releases the read lock.
  46863. */
  46864. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
  46865. int rc;
  46866. BtShared *pBt = p->pBt;
  46867. MemPage *pPage1;
  46868. sqlite3BtreeEnter(p);
  46869. rc = saveAllCursors(pBt, 0, 0);
  46870. #ifndef SQLITE_OMIT_SHARED_CACHE
  46871. if( rc!=SQLITE_OK ){
  46872. /* This is a horrible situation. An IO or malloc() error occurred whilst
  46873. ** trying to save cursor positions. If this is an automatic rollback (as
  46874. ** the result of a constraint, malloc() failure or IO error) then
  46875. ** the cache may be internally inconsistent (not contain valid trees) so
  46876. ** we cannot simply return the error to the caller. Instead, abort
  46877. ** all queries that may be using any of the cursors that failed to save.
  46878. */
  46879. sqlite3BtreeTripAllCursors(p, rc);
  46880. }
  46881. #endif
  46882. btreeIntegrity(p);
  46883. if( p->inTrans==TRANS_WRITE ){
  46884. int rc2;
  46885. assert( TRANS_WRITE==pBt->inTransaction );
  46886. rc2 = sqlite3PagerRollback(pBt->pPager);
  46887. if( rc2!=SQLITE_OK ){
  46888. rc = rc2;
  46889. }
  46890. /* The rollback may have destroyed the pPage1->aData value. So
  46891. ** call btreeGetPage() on page 1 again to make
  46892. ** sure pPage1->aData is set correctly. */
  46893. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  46894. int nPage = get4byte(28+(u8*)pPage1->aData);
  46895. testcase( nPage==0 );
  46896. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  46897. testcase( pBt->nPage!=nPage );
  46898. pBt->nPage = nPage;
  46899. releasePage(pPage1);
  46900. }
  46901. assert( countWriteCursors(pBt)==0 );
  46902. pBt->inTransaction = TRANS_READ;
  46903. }
  46904. btreeEndTransaction(p);
  46905. sqlite3BtreeLeave(p);
  46906. return rc;
  46907. }
  46908. /*
  46909. ** Start a statement subtransaction. The subtransaction can can be rolled
  46910. ** back independently of the main transaction. You must start a transaction
  46911. ** before starting a subtransaction. The subtransaction is ended automatically
  46912. ** if the main transaction commits or rolls back.
  46913. **
  46914. ** Statement subtransactions are used around individual SQL statements
  46915. ** that are contained within a BEGIN...COMMIT block. If a constraint
  46916. ** error occurs within the statement, the effect of that one statement
  46917. ** can be rolled back without having to rollback the entire transaction.
  46918. **
  46919. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  46920. ** value passed as the second parameter is the total number of savepoints,
  46921. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  46922. ** are no active savepoints and no other statement-transactions open,
  46923. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  46924. ** using the sqlite3BtreeSavepoint() function.
  46925. */
  46926. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  46927. int rc;
  46928. BtShared *pBt = p->pBt;
  46929. sqlite3BtreeEnter(p);
  46930. assert( p->inTrans==TRANS_WRITE );
  46931. assert( pBt->readOnly==0 );
  46932. assert( iStatement>0 );
  46933. assert( iStatement>p->db->nSavepoint );
  46934. assert( pBt->inTransaction==TRANS_WRITE );
  46935. /* At the pager level, a statement transaction is a savepoint with
  46936. ** an index greater than all savepoints created explicitly using
  46937. ** SQL statements. It is illegal to open, release or rollback any
  46938. ** such savepoints while the statement transaction savepoint is active.
  46939. */
  46940. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  46941. sqlite3BtreeLeave(p);
  46942. return rc;
  46943. }
  46944. /*
  46945. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  46946. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  46947. ** savepoint identified by parameter iSavepoint, depending on the value
  46948. ** of op.
  46949. **
  46950. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  46951. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  46952. ** contents of the entire transaction are rolled back. This is different
  46953. ** from a normal transaction rollback, as no locks are released and the
  46954. ** transaction remains open.
  46955. */
  46956. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  46957. int rc = SQLITE_OK;
  46958. if( p && p->inTrans==TRANS_WRITE ){
  46959. BtShared *pBt = p->pBt;
  46960. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  46961. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  46962. sqlite3BtreeEnter(p);
  46963. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  46964. if( rc==SQLITE_OK ){
  46965. if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
  46966. rc = newDatabase(pBt);
  46967. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  46968. /* The database size was written into the offset 28 of the header
  46969. ** when the transaction started, so we know that the value at offset
  46970. ** 28 is nonzero. */
  46971. assert( pBt->nPage>0 );
  46972. }
  46973. sqlite3BtreeLeave(p);
  46974. }
  46975. return rc;
  46976. }
  46977. /*
  46978. ** Create a new cursor for the BTree whose root is on the page
  46979. ** iTable. If a read-only cursor is requested, it is assumed that
  46980. ** the caller already has at least a read-only transaction open
  46981. ** on the database already. If a write-cursor is requested, then
  46982. ** the caller is assumed to have an open write transaction.
  46983. **
  46984. ** If wrFlag==0, then the cursor can only be used for reading.
  46985. ** If wrFlag==1, then the cursor can be used for reading or for
  46986. ** writing if other conditions for writing are also met. These
  46987. ** are the conditions that must be met in order for writing to
  46988. ** be allowed:
  46989. **
  46990. ** 1: The cursor must have been opened with wrFlag==1
  46991. **
  46992. ** 2: Other database connections that share the same pager cache
  46993. ** but which are not in the READ_UNCOMMITTED state may not have
  46994. ** cursors open with wrFlag==0 on the same table. Otherwise
  46995. ** the changes made by this write cursor would be visible to
  46996. ** the read cursors in the other database connection.
  46997. **
  46998. ** 3: The database must be writable (not on read-only media)
  46999. **
  47000. ** 4: There must be an active transaction.
  47001. **
  47002. ** No checking is done to make sure that page iTable really is the
  47003. ** root page of a b-tree. If it is not, then the cursor acquired
  47004. ** will not work correctly.
  47005. **
  47006. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  47007. ** on pCur to initialize the memory space prior to invoking this routine.
  47008. */
  47009. static int btreeCursor(
  47010. Btree *p, /* The btree */
  47011. int iTable, /* Root page of table to open */
  47012. int wrFlag, /* 1 to write. 0 read-only */
  47013. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  47014. BtCursor *pCur /* Space for new cursor */
  47015. ){
  47016. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  47017. assert( sqlite3BtreeHoldsMutex(p) );
  47018. assert( wrFlag==0 || wrFlag==1 );
  47019. /* The following assert statements verify that if this is a sharable
  47020. ** b-tree database, the connection is holding the required table locks,
  47021. ** and that no other connection has any open cursor that conflicts with
  47022. ** this lock. */
  47023. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  47024. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  47025. /* Assert that the caller has opened the required transaction. */
  47026. assert( p->inTrans>TRANS_NONE );
  47027. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  47028. assert( pBt->pPage1 && pBt->pPage1->aData );
  47029. if( NEVER(wrFlag && pBt->readOnly) ){
  47030. return SQLITE_READONLY;
  47031. }
  47032. if( iTable==1 && btreePagecount(pBt)==0 ){
  47033. return SQLITE_EMPTY;
  47034. }
  47035. /* Now that no other errors can occur, finish filling in the BtCursor
  47036. ** variables and link the cursor into the BtShared list. */
  47037. pCur->pgnoRoot = (Pgno)iTable;
  47038. pCur->iPage = -1;
  47039. pCur->pKeyInfo = pKeyInfo;
  47040. pCur->pBtree = p;
  47041. pCur->pBt = pBt;
  47042. pCur->wrFlag = (u8)wrFlag;
  47043. pCur->pNext = pBt->pCursor;
  47044. if( pCur->pNext ){
  47045. pCur->pNext->pPrev = pCur;
  47046. }
  47047. pBt->pCursor = pCur;
  47048. pCur->eState = CURSOR_INVALID;
  47049. pCur->cachedRowid = 0;
  47050. return SQLITE_OK;
  47051. }
  47052. SQLITE_PRIVATE int sqlite3BtreeCursor(
  47053. Btree *p, /* The btree */
  47054. int iTable, /* Root page of table to open */
  47055. int wrFlag, /* 1 to write. 0 read-only */
  47056. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  47057. BtCursor *pCur /* Write new cursor here */
  47058. ){
  47059. int rc;
  47060. sqlite3BtreeEnter(p);
  47061. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  47062. sqlite3BtreeLeave(p);
  47063. return rc;
  47064. }
  47065. /*
  47066. ** Return the size of a BtCursor object in bytes.
  47067. **
  47068. ** This interfaces is needed so that users of cursors can preallocate
  47069. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  47070. ** to users so they cannot do the sizeof() themselves - they must call
  47071. ** this routine.
  47072. */
  47073. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  47074. return ROUND8(sizeof(BtCursor));
  47075. }
  47076. /*
  47077. ** Initialize memory that will be converted into a BtCursor object.
  47078. **
  47079. ** The simple approach here would be to memset() the entire object
  47080. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  47081. ** do not need to be zeroed and they are large, so we can save a lot
  47082. ** of run-time by skipping the initialization of those elements.
  47083. */
  47084. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  47085. memset(p, 0, offsetof(BtCursor, iPage));
  47086. }
  47087. /*
  47088. ** Set the cached rowid value of every cursor in the same database file
  47089. ** as pCur and having the same root page number as pCur. The value is
  47090. ** set to iRowid.
  47091. **
  47092. ** Only positive rowid values are considered valid for this cache.
  47093. ** The cache is initialized to zero, indicating an invalid cache.
  47094. ** A btree will work fine with zero or negative rowids. We just cannot
  47095. ** cache zero or negative rowids, which means tables that use zero or
  47096. ** negative rowids might run a little slower. But in practice, zero
  47097. ** or negative rowids are very uncommon so this should not be a problem.
  47098. */
  47099. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  47100. BtCursor *p;
  47101. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  47102. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  47103. }
  47104. assert( pCur->cachedRowid==iRowid );
  47105. }
  47106. /*
  47107. ** Return the cached rowid for the given cursor. A negative or zero
  47108. ** return value indicates that the rowid cache is invalid and should be
  47109. ** ignored. If the rowid cache has never before been set, then a
  47110. ** zero is returned.
  47111. */
  47112. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  47113. return pCur->cachedRowid;
  47114. }
  47115. /*
  47116. ** Close a cursor. The read lock on the database file is released
  47117. ** when the last cursor is closed.
  47118. */
  47119. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  47120. Btree *pBtree = pCur->pBtree;
  47121. if( pBtree ){
  47122. int i;
  47123. BtShared *pBt = pCur->pBt;
  47124. sqlite3BtreeEnter(pBtree);
  47125. sqlite3BtreeClearCursor(pCur);
  47126. if( pCur->pPrev ){
  47127. pCur->pPrev->pNext = pCur->pNext;
  47128. }else{
  47129. pBt->pCursor = pCur->pNext;
  47130. }
  47131. if( pCur->pNext ){
  47132. pCur->pNext->pPrev = pCur->pPrev;
  47133. }
  47134. for(i=0; i<=pCur->iPage; i++){
  47135. releasePage(pCur->apPage[i]);
  47136. }
  47137. unlockBtreeIfUnused(pBt);
  47138. invalidateOverflowCache(pCur);
  47139. /* sqlite3_free(pCur); */
  47140. sqlite3BtreeLeave(pBtree);
  47141. }
  47142. return SQLITE_OK;
  47143. }
  47144. /*
  47145. ** Make sure the BtCursor* given in the argument has a valid
  47146. ** BtCursor.info structure. If it is not already valid, call
  47147. ** btreeParseCell() to fill it in.
  47148. **
  47149. ** BtCursor.info is a cache of the information in the current cell.
  47150. ** Using this cache reduces the number of calls to btreeParseCell().
  47151. **
  47152. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  47153. ** compiler to crash when getCellInfo() is implemented as a macro.
  47154. ** But there is a measureable speed advantage to using the macro on gcc
  47155. ** (when less compiler optimizations like -Os or -O0 are used and the
  47156. ** compiler is not doing agressive inlining.) So we use a real function
  47157. ** for MSVC and a macro for everything else. Ticket #2457.
  47158. */
  47159. #ifndef NDEBUG
  47160. static void assertCellInfo(BtCursor *pCur){
  47161. CellInfo info;
  47162. int iPage = pCur->iPage;
  47163. memset(&info, 0, sizeof(info));
  47164. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  47165. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  47166. }
  47167. #else
  47168. #define assertCellInfo(x)
  47169. #endif
  47170. #ifdef _MSC_VER
  47171. /* Use a real function in MSVC to work around bugs in that compiler. */
  47172. static void getCellInfo(BtCursor *pCur){
  47173. if( pCur->info.nSize==0 ){
  47174. int iPage = pCur->iPage;
  47175. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  47176. pCur->validNKey = 1;
  47177. }else{
  47178. assertCellInfo(pCur);
  47179. }
  47180. }
  47181. #else /* if not _MSC_VER */
  47182. /* Use a macro in all other compilers so that the function is inlined */
  47183. #define getCellInfo(pCur) \
  47184. if( pCur->info.nSize==0 ){ \
  47185. int iPage = pCur->iPage; \
  47186. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  47187. pCur->validNKey = 1; \
  47188. }else{ \
  47189. assertCellInfo(pCur); \
  47190. }
  47191. #endif /* _MSC_VER */
  47192. #ifndef NDEBUG /* The next routine used only within assert() statements */
  47193. /*
  47194. ** Return true if the given BtCursor is valid. A valid cursor is one
  47195. ** that is currently pointing to a row in a (non-empty) table.
  47196. ** This is a verification routine is used only within assert() statements.
  47197. */
  47198. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  47199. return pCur && pCur->eState==CURSOR_VALID;
  47200. }
  47201. #endif /* NDEBUG */
  47202. /*
  47203. ** Set *pSize to the size of the buffer needed to hold the value of
  47204. ** the key for the current entry. If the cursor is not pointing
  47205. ** to a valid entry, *pSize is set to 0.
  47206. **
  47207. ** For a table with the INTKEY flag set, this routine returns the key
  47208. ** itself, not the number of bytes in the key.
  47209. **
  47210. ** The caller must position the cursor prior to invoking this routine.
  47211. **
  47212. ** This routine cannot fail. It always returns SQLITE_OK.
  47213. */
  47214. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  47215. assert( cursorHoldsMutex(pCur) );
  47216. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  47217. if( pCur->eState!=CURSOR_VALID ){
  47218. *pSize = 0;
  47219. }else{
  47220. getCellInfo(pCur);
  47221. *pSize = pCur->info.nKey;
  47222. }
  47223. return SQLITE_OK;
  47224. }
  47225. /*
  47226. ** Set *pSize to the number of bytes of data in the entry the
  47227. ** cursor currently points to.
  47228. **
  47229. ** The caller must guarantee that the cursor is pointing to a non-NULL
  47230. ** valid entry. In other words, the calling procedure must guarantee
  47231. ** that the cursor has Cursor.eState==CURSOR_VALID.
  47232. **
  47233. ** Failure is not possible. This function always returns SQLITE_OK.
  47234. ** It might just as well be a procedure (returning void) but we continue
  47235. ** to return an integer result code for historical reasons.
  47236. */
  47237. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  47238. assert( cursorHoldsMutex(pCur) );
  47239. assert( pCur->eState==CURSOR_VALID );
  47240. getCellInfo(pCur);
  47241. *pSize = pCur->info.nData;
  47242. return SQLITE_OK;
  47243. }
  47244. /*
  47245. ** Given the page number of an overflow page in the database (parameter
  47246. ** ovfl), this function finds the page number of the next page in the
  47247. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  47248. ** pointer-map data instead of reading the content of page ovfl to do so.
  47249. **
  47250. ** If an error occurs an SQLite error code is returned. Otherwise:
  47251. **
  47252. ** The page number of the next overflow page in the linked list is
  47253. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  47254. ** list, *pPgnoNext is set to zero.
  47255. **
  47256. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  47257. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  47258. ** reference. It is the responsibility of the caller to call releasePage()
  47259. ** on *ppPage to free the reference. In no reference was obtained (because
  47260. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  47261. ** *ppPage is set to zero.
  47262. */
  47263. static int getOverflowPage(
  47264. BtShared *pBt, /* The database file */
  47265. Pgno ovfl, /* Current overflow page number */
  47266. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  47267. Pgno *pPgnoNext /* OUT: Next overflow page number */
  47268. ){
  47269. Pgno next = 0;
  47270. MemPage *pPage = 0;
  47271. int rc = SQLITE_OK;
  47272. assert( sqlite3_mutex_held(pBt->mutex) );
  47273. assert(pPgnoNext);
  47274. #ifndef SQLITE_OMIT_AUTOVACUUM
  47275. /* Try to find the next page in the overflow list using the
  47276. ** autovacuum pointer-map pages. Guess that the next page in
  47277. ** the overflow list is page number (ovfl+1). If that guess turns
  47278. ** out to be wrong, fall back to loading the data of page
  47279. ** number ovfl to determine the next page number.
  47280. */
  47281. if( pBt->autoVacuum ){
  47282. Pgno pgno;
  47283. Pgno iGuess = ovfl+1;
  47284. u8 eType;
  47285. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  47286. iGuess++;
  47287. }
  47288. if( iGuess<=btreePagecount(pBt) ){
  47289. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  47290. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  47291. next = iGuess;
  47292. rc = SQLITE_DONE;
  47293. }
  47294. }
  47295. }
  47296. #endif
  47297. assert( next==0 || rc==SQLITE_DONE );
  47298. if( rc==SQLITE_OK ){
  47299. rc = btreeGetPage(pBt, ovfl, &pPage, 0);
  47300. assert( rc==SQLITE_OK || pPage==0 );
  47301. if( rc==SQLITE_OK ){
  47302. next = get4byte(pPage->aData);
  47303. }
  47304. }
  47305. *pPgnoNext = next;
  47306. if( ppPage ){
  47307. *ppPage = pPage;
  47308. }else{
  47309. releasePage(pPage);
  47310. }
  47311. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  47312. }
  47313. /*
  47314. ** Copy data from a buffer to a page, or from a page to a buffer.
  47315. **
  47316. ** pPayload is a pointer to data stored on database page pDbPage.
  47317. ** If argument eOp is false, then nByte bytes of data are copied
  47318. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  47319. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  47320. ** of data are copied from the buffer pBuf to pPayload.
  47321. **
  47322. ** SQLITE_OK is returned on success, otherwise an error code.
  47323. */
  47324. static int copyPayload(
  47325. void *pPayload, /* Pointer to page data */
  47326. void *pBuf, /* Pointer to buffer */
  47327. int nByte, /* Number of bytes to copy */
  47328. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  47329. DbPage *pDbPage /* Page containing pPayload */
  47330. ){
  47331. if( eOp ){
  47332. /* Copy data from buffer to page (a write operation) */
  47333. int rc = sqlite3PagerWrite(pDbPage);
  47334. if( rc!=SQLITE_OK ){
  47335. return rc;
  47336. }
  47337. memcpy(pPayload, pBuf, nByte);
  47338. }else{
  47339. /* Copy data from page to buffer (a read operation) */
  47340. memcpy(pBuf, pPayload, nByte);
  47341. }
  47342. return SQLITE_OK;
  47343. }
  47344. /*
  47345. ** This function is used to read or overwrite payload information
  47346. ** for the entry that the pCur cursor is pointing to. If the eOp
  47347. ** parameter is 0, this is a read operation (data copied into
  47348. ** buffer pBuf). If it is non-zero, a write (data copied from
  47349. ** buffer pBuf).
  47350. **
  47351. ** A total of "amt" bytes are read or written beginning at "offset".
  47352. ** Data is read to or from the buffer pBuf.
  47353. **
  47354. ** The content being read or written might appear on the main page
  47355. ** or be scattered out on multiple overflow pages.
  47356. **
  47357. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  47358. ** cursor entry uses one or more overflow pages, this function
  47359. ** allocates space for and lazily popluates the overflow page-list
  47360. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  47361. ** cache to make seeking to the supplied offset more efficient.
  47362. **
  47363. ** Once an overflow page-list cache has been allocated, it may be
  47364. ** invalidated if some other cursor writes to the same table, or if
  47365. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  47366. ** mode, the following events may invalidate an overflow page-list cache.
  47367. **
  47368. ** * An incremental vacuum,
  47369. ** * A commit in auto_vacuum="full" mode,
  47370. ** * Creating a table (may require moving an overflow page).
  47371. */
  47372. static int accessPayload(
  47373. BtCursor *pCur, /* Cursor pointing to entry to read from */
  47374. u32 offset, /* Begin reading this far into payload */
  47375. u32 amt, /* Read this many bytes */
  47376. unsigned char *pBuf, /* Write the bytes into this buffer */
  47377. int eOp /* zero to read. non-zero to write. */
  47378. ){
  47379. unsigned char *aPayload;
  47380. int rc = SQLITE_OK;
  47381. u32 nKey;
  47382. int iIdx = 0;
  47383. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  47384. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  47385. assert( pPage );
  47386. assert( pCur->eState==CURSOR_VALID );
  47387. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  47388. assert( cursorHoldsMutex(pCur) );
  47389. getCellInfo(pCur);
  47390. aPayload = pCur->info.pCell + pCur->info.nHeader;
  47391. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  47392. if( NEVER(offset+amt > nKey+pCur->info.nData)
  47393. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  47394. ){
  47395. /* Trying to read or write past the end of the data is an error */
  47396. return SQLITE_CORRUPT_BKPT;
  47397. }
  47398. /* Check if data must be read/written to/from the btree page itself. */
  47399. if( offset<pCur->info.nLocal ){
  47400. int a = amt;
  47401. if( a+offset>pCur->info.nLocal ){
  47402. a = pCur->info.nLocal - offset;
  47403. }
  47404. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  47405. offset = 0;
  47406. pBuf += a;
  47407. amt -= a;
  47408. }else{
  47409. offset -= pCur->info.nLocal;
  47410. }
  47411. if( rc==SQLITE_OK && amt>0 ){
  47412. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  47413. Pgno nextPage;
  47414. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  47415. #ifndef SQLITE_OMIT_INCRBLOB
  47416. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  47417. ** has not been allocated, allocate it now. The array is sized at
  47418. ** one entry for each overflow page in the overflow chain. The
  47419. ** page number of the first overflow page is stored in aOverflow[0],
  47420. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  47421. ** (the cache is lazily populated).
  47422. */
  47423. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  47424. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  47425. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  47426. /* nOvfl is always positive. If it were zero, fetchPayload would have
  47427. ** been used instead of this routine. */
  47428. if( ALWAYS(nOvfl) && !pCur->aOverflow ){
  47429. rc = SQLITE_NOMEM;
  47430. }
  47431. }
  47432. /* If the overflow page-list cache has been allocated and the
  47433. ** entry for the first required overflow page is valid, skip
  47434. ** directly to it.
  47435. */
  47436. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  47437. iIdx = (offset/ovflSize);
  47438. nextPage = pCur->aOverflow[iIdx];
  47439. offset = (offset%ovflSize);
  47440. }
  47441. #endif
  47442. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  47443. #ifndef SQLITE_OMIT_INCRBLOB
  47444. /* If required, populate the overflow page-list cache. */
  47445. if( pCur->aOverflow ){
  47446. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  47447. pCur->aOverflow[iIdx] = nextPage;
  47448. }
  47449. #endif
  47450. if( offset>=ovflSize ){
  47451. /* The only reason to read this page is to obtain the page
  47452. ** number for the next page in the overflow chain. The page
  47453. ** data is not required. So first try to lookup the overflow
  47454. ** page-list cache, if any, then fall back to the getOverflowPage()
  47455. ** function.
  47456. */
  47457. #ifndef SQLITE_OMIT_INCRBLOB
  47458. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  47459. nextPage = pCur->aOverflow[iIdx+1];
  47460. } else
  47461. #endif
  47462. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  47463. offset -= ovflSize;
  47464. }else{
  47465. /* Need to read this page properly. It contains some of the
  47466. ** range of data that is being read (eOp==0) or written (eOp!=0).
  47467. */
  47468. DbPage *pDbPage;
  47469. int a = amt;
  47470. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
  47471. if( rc==SQLITE_OK ){
  47472. aPayload = sqlite3PagerGetData(pDbPage);
  47473. nextPage = get4byte(aPayload);
  47474. if( a + offset > ovflSize ){
  47475. a = ovflSize - offset;
  47476. }
  47477. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  47478. sqlite3PagerUnref(pDbPage);
  47479. offset = 0;
  47480. amt -= a;
  47481. pBuf += a;
  47482. }
  47483. }
  47484. }
  47485. }
  47486. if( rc==SQLITE_OK && amt>0 ){
  47487. return SQLITE_CORRUPT_BKPT;
  47488. }
  47489. return rc;
  47490. }
  47491. /*
  47492. ** Read part of the key associated with cursor pCur. Exactly
  47493. ** "amt" bytes will be transfered into pBuf[]. The transfer
  47494. ** begins at "offset".
  47495. **
  47496. ** The caller must ensure that pCur is pointing to a valid row
  47497. ** in the table.
  47498. **
  47499. ** Return SQLITE_OK on success or an error code if anything goes
  47500. ** wrong. An error is returned if "offset+amt" is larger than
  47501. ** the available payload.
  47502. */
  47503. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  47504. assert( cursorHoldsMutex(pCur) );
  47505. assert( pCur->eState==CURSOR_VALID );
  47506. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  47507. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  47508. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  47509. }
  47510. /*
  47511. ** Read part of the data associated with cursor pCur. Exactly
  47512. ** "amt" bytes will be transfered into pBuf[]. The transfer
  47513. ** begins at "offset".
  47514. **
  47515. ** Return SQLITE_OK on success or an error code if anything goes
  47516. ** wrong. An error is returned if "offset+amt" is larger than
  47517. ** the available payload.
  47518. */
  47519. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  47520. int rc;
  47521. #ifndef SQLITE_OMIT_INCRBLOB
  47522. if ( pCur->eState==CURSOR_INVALID ){
  47523. return SQLITE_ABORT;
  47524. }
  47525. #endif
  47526. assert( cursorHoldsMutex(pCur) );
  47527. rc = restoreCursorPosition(pCur);
  47528. if( rc==SQLITE_OK ){
  47529. assert( pCur->eState==CURSOR_VALID );
  47530. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  47531. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  47532. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  47533. }
  47534. return rc;
  47535. }
  47536. /*
  47537. ** Return a pointer to payload information from the entry that the
  47538. ** pCur cursor is pointing to. The pointer is to the beginning of
  47539. ** the key if skipKey==0 and it points to the beginning of data if
  47540. ** skipKey==1. The number of bytes of available key/data is written
  47541. ** into *pAmt. If *pAmt==0, then the value returned will not be
  47542. ** a valid pointer.
  47543. **
  47544. ** This routine is an optimization. It is common for the entire key
  47545. ** and data to fit on the local page and for there to be no overflow
  47546. ** pages. When that is so, this routine can be used to access the
  47547. ** key and data without making a copy. If the key and/or data spills
  47548. ** onto overflow pages, then accessPayload() must be used to reassemble
  47549. ** the key/data and copy it into a preallocated buffer.
  47550. **
  47551. ** The pointer returned by this routine looks directly into the cached
  47552. ** page of the database. The data might change or move the next time
  47553. ** any btree routine is called.
  47554. */
  47555. static const unsigned char *fetchPayload(
  47556. BtCursor *pCur, /* Cursor pointing to entry to read from */
  47557. int *pAmt, /* Write the number of available bytes here */
  47558. int skipKey /* read beginning at data if this is true */
  47559. ){
  47560. unsigned char *aPayload;
  47561. MemPage *pPage;
  47562. u32 nKey;
  47563. u32 nLocal;
  47564. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  47565. assert( pCur->eState==CURSOR_VALID );
  47566. assert( cursorHoldsMutex(pCur) );
  47567. pPage = pCur->apPage[pCur->iPage];
  47568. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  47569. if( NEVER(pCur->info.nSize==0) ){
  47570. btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
  47571. &pCur->info);
  47572. }
  47573. aPayload = pCur->info.pCell;
  47574. aPayload += pCur->info.nHeader;
  47575. if( pPage->intKey ){
  47576. nKey = 0;
  47577. }else{
  47578. nKey = (int)pCur->info.nKey;
  47579. }
  47580. if( skipKey ){
  47581. aPayload += nKey;
  47582. nLocal = pCur->info.nLocal - nKey;
  47583. }else{
  47584. nLocal = pCur->info.nLocal;
  47585. assert( nLocal<=nKey );
  47586. }
  47587. *pAmt = nLocal;
  47588. return aPayload;
  47589. }
  47590. /*
  47591. ** For the entry that cursor pCur is point to, return as
  47592. ** many bytes of the key or data as are available on the local
  47593. ** b-tree page. Write the number of available bytes into *pAmt.
  47594. **
  47595. ** The pointer returned is ephemeral. The key/data may move
  47596. ** or be destroyed on the next call to any Btree routine,
  47597. ** including calls from other threads against the same cache.
  47598. ** Hence, a mutex on the BtShared should be held prior to calling
  47599. ** this routine.
  47600. **
  47601. ** These routines is used to get quick access to key and data
  47602. ** in the common case where no overflow pages are used.
  47603. */
  47604. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  47605. const void *p = 0;
  47606. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  47607. assert( cursorHoldsMutex(pCur) );
  47608. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  47609. p = (const void*)fetchPayload(pCur, pAmt, 0);
  47610. }
  47611. return p;
  47612. }
  47613. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  47614. const void *p = 0;
  47615. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  47616. assert( cursorHoldsMutex(pCur) );
  47617. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  47618. p = (const void*)fetchPayload(pCur, pAmt, 1);
  47619. }
  47620. return p;
  47621. }
  47622. /*
  47623. ** Move the cursor down to a new child page. The newPgno argument is the
  47624. ** page number of the child page to move to.
  47625. **
  47626. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  47627. ** the new child page does not match the flags field of the parent (i.e.
  47628. ** if an intkey page appears to be the parent of a non-intkey page, or
  47629. ** vice-versa).
  47630. */
  47631. static int moveToChild(BtCursor *pCur, u32 newPgno){
  47632. int rc;
  47633. int i = pCur->iPage;
  47634. MemPage *pNewPage;
  47635. BtShared *pBt = pCur->pBt;
  47636. assert( cursorHoldsMutex(pCur) );
  47637. assert( pCur->eState==CURSOR_VALID );
  47638. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  47639. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  47640. return SQLITE_CORRUPT_BKPT;
  47641. }
  47642. rc = getAndInitPage(pBt, newPgno, &pNewPage);
  47643. if( rc ) return rc;
  47644. pCur->apPage[i+1] = pNewPage;
  47645. pCur->aiIdx[i+1] = 0;
  47646. pCur->iPage++;
  47647. pCur->info.nSize = 0;
  47648. pCur->validNKey = 0;
  47649. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  47650. return SQLITE_CORRUPT_BKPT;
  47651. }
  47652. return SQLITE_OK;
  47653. }
  47654. #ifndef NDEBUG
  47655. /*
  47656. ** Page pParent is an internal (non-leaf) tree page. This function
  47657. ** asserts that page number iChild is the left-child if the iIdx'th
  47658. ** cell in page pParent. Or, if iIdx is equal to the total number of
  47659. ** cells in pParent, that page number iChild is the right-child of
  47660. ** the page.
  47661. */
  47662. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  47663. assert( iIdx<=pParent->nCell );
  47664. if( iIdx==pParent->nCell ){
  47665. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  47666. }else{
  47667. assert( get4byte(findCell(pParent, iIdx))==iChild );
  47668. }
  47669. }
  47670. #else
  47671. # define assertParentIndex(x,y,z)
  47672. #endif
  47673. /*
  47674. ** Move the cursor up to the parent page.
  47675. **
  47676. ** pCur->idx is set to the cell index that contains the pointer
  47677. ** to the page we are coming from. If we are coming from the
  47678. ** right-most child page then pCur->idx is set to one more than
  47679. ** the largest cell index.
  47680. */
  47681. static void moveToParent(BtCursor *pCur){
  47682. assert( cursorHoldsMutex(pCur) );
  47683. assert( pCur->eState==CURSOR_VALID );
  47684. assert( pCur->iPage>0 );
  47685. assert( pCur->apPage[pCur->iPage] );
  47686. assertParentIndex(
  47687. pCur->apPage[pCur->iPage-1],
  47688. pCur->aiIdx[pCur->iPage-1],
  47689. pCur->apPage[pCur->iPage]->pgno
  47690. );
  47691. releasePage(pCur->apPage[pCur->iPage]);
  47692. pCur->iPage--;
  47693. pCur->info.nSize = 0;
  47694. pCur->validNKey = 0;
  47695. }
  47696. /*
  47697. ** Move the cursor to point to the root page of its b-tree structure.
  47698. **
  47699. ** If the table has a virtual root page, then the cursor is moved to point
  47700. ** to the virtual root page instead of the actual root page. A table has a
  47701. ** virtual root page when the actual root page contains no cells and a
  47702. ** single child page. This can only happen with the table rooted at page 1.
  47703. **
  47704. ** If the b-tree structure is empty, the cursor state is set to
  47705. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  47706. ** cell located on the root (or virtual root) page and the cursor state
  47707. ** is set to CURSOR_VALID.
  47708. **
  47709. ** If this function returns successfully, it may be assumed that the
  47710. ** page-header flags indicate that the [virtual] root-page is the expected
  47711. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  47712. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  47713. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  47714. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  47715. ** b-tree).
  47716. */
  47717. static int moveToRoot(BtCursor *pCur){
  47718. MemPage *pRoot;
  47719. int rc = SQLITE_OK;
  47720. Btree *p = pCur->pBtree;
  47721. BtShared *pBt = p->pBt;
  47722. assert( cursorHoldsMutex(pCur) );
  47723. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  47724. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  47725. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  47726. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  47727. if( pCur->eState==CURSOR_FAULT ){
  47728. assert( pCur->skipNext!=SQLITE_OK );
  47729. return pCur->skipNext;
  47730. }
  47731. sqlite3BtreeClearCursor(pCur);
  47732. }
  47733. if( pCur->iPage>=0 ){
  47734. int i;
  47735. for(i=1; i<=pCur->iPage; i++){
  47736. releasePage(pCur->apPage[i]);
  47737. }
  47738. pCur->iPage = 0;
  47739. }else{
  47740. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
  47741. if( rc!=SQLITE_OK ){
  47742. pCur->eState = CURSOR_INVALID;
  47743. return rc;
  47744. }
  47745. pCur->iPage = 0;
  47746. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  47747. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  47748. ** NULL, the caller expects a table b-tree. If this is not the case,
  47749. ** return an SQLITE_CORRUPT error. */
  47750. assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
  47751. if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
  47752. return SQLITE_CORRUPT_BKPT;
  47753. }
  47754. }
  47755. /* Assert that the root page is of the correct type. This must be the
  47756. ** case as the call to this function that loaded the root-page (either
  47757. ** this call or a previous invocation) would have detected corruption
  47758. ** if the assumption were not true, and it is not possible for the flags
  47759. ** byte to have been modified while this cursor is holding a reference
  47760. ** to the page. */
  47761. pRoot = pCur->apPage[0];
  47762. assert( pRoot->pgno==pCur->pgnoRoot );
  47763. assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
  47764. pCur->aiIdx[0] = 0;
  47765. pCur->info.nSize = 0;
  47766. pCur->atLast = 0;
  47767. pCur->validNKey = 0;
  47768. if( pRoot->nCell==0 && !pRoot->leaf ){
  47769. Pgno subpage;
  47770. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  47771. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  47772. pCur->eState = CURSOR_VALID;
  47773. rc = moveToChild(pCur, subpage);
  47774. }else{
  47775. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  47776. }
  47777. return rc;
  47778. }
  47779. /*
  47780. ** Move the cursor down to the left-most leaf entry beneath the
  47781. ** entry to which it is currently pointing.
  47782. **
  47783. ** The left-most leaf is the one with the smallest key - the first
  47784. ** in ascending order.
  47785. */
  47786. static int moveToLeftmost(BtCursor *pCur){
  47787. Pgno pgno;
  47788. int rc = SQLITE_OK;
  47789. MemPage *pPage;
  47790. assert( cursorHoldsMutex(pCur) );
  47791. assert( pCur->eState==CURSOR_VALID );
  47792. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  47793. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  47794. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  47795. rc = moveToChild(pCur, pgno);
  47796. }
  47797. return rc;
  47798. }
  47799. /*
  47800. ** Move the cursor down to the right-most leaf entry beneath the
  47801. ** page to which it is currently pointing. Notice the difference
  47802. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  47803. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  47804. ** finds the right-most entry beneath the *page*.
  47805. **
  47806. ** The right-most entry is the one with the largest key - the last
  47807. ** key in ascending order.
  47808. */
  47809. static int moveToRightmost(BtCursor *pCur){
  47810. Pgno pgno;
  47811. int rc = SQLITE_OK;
  47812. MemPage *pPage = 0;
  47813. assert( cursorHoldsMutex(pCur) );
  47814. assert( pCur->eState==CURSOR_VALID );
  47815. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  47816. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  47817. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  47818. rc = moveToChild(pCur, pgno);
  47819. }
  47820. if( rc==SQLITE_OK ){
  47821. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  47822. pCur->info.nSize = 0;
  47823. pCur->validNKey = 0;
  47824. }
  47825. return rc;
  47826. }
  47827. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  47828. ** on success. Set *pRes to 0 if the cursor actually points to something
  47829. ** or set *pRes to 1 if the table is empty.
  47830. */
  47831. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  47832. int rc;
  47833. assert( cursorHoldsMutex(pCur) );
  47834. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  47835. rc = moveToRoot(pCur);
  47836. if( rc==SQLITE_OK ){
  47837. if( pCur->eState==CURSOR_INVALID ){
  47838. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  47839. *pRes = 1;
  47840. }else{
  47841. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  47842. *pRes = 0;
  47843. rc = moveToLeftmost(pCur);
  47844. }
  47845. }
  47846. return rc;
  47847. }
  47848. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  47849. ** on success. Set *pRes to 0 if the cursor actually points to something
  47850. ** or set *pRes to 1 if the table is empty.
  47851. */
  47852. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  47853. int rc;
  47854. assert( cursorHoldsMutex(pCur) );
  47855. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  47856. /* If the cursor already points to the last entry, this is a no-op. */
  47857. if( CURSOR_VALID==pCur->eState && pCur->atLast ){
  47858. #ifdef SQLITE_DEBUG
  47859. /* This block serves to assert() that the cursor really does point
  47860. ** to the last entry in the b-tree. */
  47861. int ii;
  47862. for(ii=0; ii<pCur->iPage; ii++){
  47863. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  47864. }
  47865. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  47866. assert( pCur->apPage[pCur->iPage]->leaf );
  47867. #endif
  47868. return SQLITE_OK;
  47869. }
  47870. rc = moveToRoot(pCur);
  47871. if( rc==SQLITE_OK ){
  47872. if( CURSOR_INVALID==pCur->eState ){
  47873. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  47874. *pRes = 1;
  47875. }else{
  47876. assert( pCur->eState==CURSOR_VALID );
  47877. *pRes = 0;
  47878. rc = moveToRightmost(pCur);
  47879. pCur->atLast = rc==SQLITE_OK ?1:0;
  47880. }
  47881. }
  47882. return rc;
  47883. }
  47884. /* Move the cursor so that it points to an entry near the key
  47885. ** specified by pIdxKey or intKey. Return a success code.
  47886. **
  47887. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  47888. ** must be NULL. For index tables, pIdxKey is used and intKey
  47889. ** is ignored.
  47890. **
  47891. ** If an exact match is not found, then the cursor is always
  47892. ** left pointing at a leaf page which would hold the entry if it
  47893. ** were present. The cursor might point to an entry that comes
  47894. ** before or after the key.
  47895. **
  47896. ** An integer is written into *pRes which is the result of
  47897. ** comparing the key with the entry to which the cursor is
  47898. ** pointing. The meaning of the integer written into
  47899. ** *pRes is as follows:
  47900. **
  47901. ** *pRes<0 The cursor is left pointing at an entry that
  47902. ** is smaller than intKey/pIdxKey or if the table is empty
  47903. ** and the cursor is therefore left point to nothing.
  47904. **
  47905. ** *pRes==0 The cursor is left pointing at an entry that
  47906. ** exactly matches intKey/pIdxKey.
  47907. **
  47908. ** *pRes>0 The cursor is left pointing at an entry that
  47909. ** is larger than intKey/pIdxKey.
  47910. **
  47911. */
  47912. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  47913. BtCursor *pCur, /* The cursor to be moved */
  47914. UnpackedRecord *pIdxKey, /* Unpacked index key */
  47915. i64 intKey, /* The table key */
  47916. int biasRight, /* If true, bias the search to the high end */
  47917. int *pRes /* Write search results here */
  47918. ){
  47919. int rc;
  47920. assert( cursorHoldsMutex(pCur) );
  47921. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  47922. assert( pRes );
  47923. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  47924. /* If the cursor is already positioned at the point we are trying
  47925. ** to move to, then just return without doing any work */
  47926. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  47927. && pCur->apPage[0]->intKey
  47928. ){
  47929. if( pCur->info.nKey==intKey ){
  47930. *pRes = 0;
  47931. return SQLITE_OK;
  47932. }
  47933. if( pCur->atLast && pCur->info.nKey<intKey ){
  47934. *pRes = -1;
  47935. return SQLITE_OK;
  47936. }
  47937. }
  47938. rc = moveToRoot(pCur);
  47939. if( rc ){
  47940. return rc;
  47941. }
  47942. assert( pCur->apPage[pCur->iPage] );
  47943. assert( pCur->apPage[pCur->iPage]->isInit );
  47944. assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
  47945. if( pCur->eState==CURSOR_INVALID ){
  47946. *pRes = -1;
  47947. assert( pCur->apPage[pCur->iPage]->nCell==0 );
  47948. return SQLITE_OK;
  47949. }
  47950. assert( pCur->apPage[0]->intKey || pIdxKey );
  47951. for(;;){
  47952. int lwr, upr;
  47953. Pgno chldPg;
  47954. MemPage *pPage = pCur->apPage[pCur->iPage];
  47955. int c;
  47956. /* pPage->nCell must be greater than zero. If this is the root-page
  47957. ** the cursor would have been INVALID above and this for(;;) loop
  47958. ** not run. If this is not the root-page, then the moveToChild() routine
  47959. ** would have already detected db corruption. Similarly, pPage must
  47960. ** be the right kind (index or table) of b-tree page. Otherwise
  47961. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  47962. assert( pPage->nCell>0 );
  47963. assert( pPage->intKey==(pIdxKey==0) );
  47964. lwr = 0;
  47965. upr = pPage->nCell-1;
  47966. if( biasRight ){
  47967. pCur->aiIdx[pCur->iPage] = (u16)upr;
  47968. }else{
  47969. pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
  47970. }
  47971. for(;;){
  47972. int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
  47973. u8 *pCell; /* Pointer to current cell in pPage */
  47974. pCur->info.nSize = 0;
  47975. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  47976. if( pPage->intKey ){
  47977. i64 nCellKey;
  47978. if( pPage->hasData ){
  47979. u32 dummy;
  47980. pCell += getVarint32(pCell, dummy);
  47981. }
  47982. getVarint(pCell, (u64*)&nCellKey);
  47983. if( nCellKey==intKey ){
  47984. c = 0;
  47985. }else if( nCellKey<intKey ){
  47986. c = -1;
  47987. }else{
  47988. assert( nCellKey>intKey );
  47989. c = +1;
  47990. }
  47991. pCur->validNKey = 1;
  47992. pCur->info.nKey = nCellKey;
  47993. }else{
  47994. /* The maximum supported page-size is 65536 bytes. This means that
  47995. ** the maximum number of record bytes stored on an index B-Tree
  47996. ** page is less than 16384 bytes and may be stored as a 2-byte
  47997. ** varint. This information is used to attempt to avoid parsing
  47998. ** the entire cell by checking for the cases where the record is
  47999. ** stored entirely within the b-tree page by inspecting the first
  48000. ** 2 bytes of the cell.
  48001. */
  48002. int nCell = pCell[0];
  48003. if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
  48004. /* This branch runs if the record-size field of the cell is a
  48005. ** single byte varint and the record fits entirely on the main
  48006. ** b-tree page. */
  48007. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  48008. }else if( !(pCell[1] & 0x80)
  48009. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  48010. ){
  48011. /* The record-size field is a 2 byte varint and the record
  48012. ** fits entirely on the main b-tree page. */
  48013. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  48014. }else{
  48015. /* The record flows over onto one or more overflow pages. In
  48016. ** this case the whole cell needs to be parsed, a buffer allocated
  48017. ** and accessPayload() used to retrieve the record into the
  48018. ** buffer before VdbeRecordCompare() can be called. */
  48019. void *pCellKey;
  48020. u8 * const pCellBody = pCell - pPage->childPtrSize;
  48021. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  48022. nCell = (int)pCur->info.nKey;
  48023. pCellKey = sqlite3Malloc( nCell );
  48024. if( pCellKey==0 ){
  48025. rc = SQLITE_NOMEM;
  48026. goto moveto_finish;
  48027. }
  48028. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  48029. if( rc ){
  48030. sqlite3_free(pCellKey);
  48031. goto moveto_finish;
  48032. }
  48033. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  48034. sqlite3_free(pCellKey);
  48035. }
  48036. }
  48037. if( c==0 ){
  48038. if( pPage->intKey && !pPage->leaf ){
  48039. lwr = idx;
  48040. upr = lwr - 1;
  48041. break;
  48042. }else{
  48043. *pRes = 0;
  48044. rc = SQLITE_OK;
  48045. goto moveto_finish;
  48046. }
  48047. }
  48048. if( c<0 ){
  48049. lwr = idx+1;
  48050. }else{
  48051. upr = idx-1;
  48052. }
  48053. if( lwr>upr ){
  48054. break;
  48055. }
  48056. pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
  48057. }
  48058. assert( lwr==upr+1 );
  48059. assert( pPage->isInit );
  48060. if( pPage->leaf ){
  48061. chldPg = 0;
  48062. }else if( lwr>=pPage->nCell ){
  48063. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  48064. }else{
  48065. chldPg = get4byte(findCell(pPage, lwr));
  48066. }
  48067. if( chldPg==0 ){
  48068. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  48069. *pRes = c;
  48070. rc = SQLITE_OK;
  48071. goto moveto_finish;
  48072. }
  48073. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  48074. pCur->info.nSize = 0;
  48075. pCur->validNKey = 0;
  48076. rc = moveToChild(pCur, chldPg);
  48077. if( rc ) goto moveto_finish;
  48078. }
  48079. moveto_finish:
  48080. return rc;
  48081. }
  48082. /*
  48083. ** Return TRUE if the cursor is not pointing at an entry of the table.
  48084. **
  48085. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  48086. ** past the last entry in the table or sqlite3BtreePrev() moves past
  48087. ** the first entry. TRUE is also returned if the table is empty.
  48088. */
  48089. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  48090. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  48091. ** have been deleted? This API will need to change to return an error code
  48092. ** as well as the boolean result value.
  48093. */
  48094. return (CURSOR_VALID!=pCur->eState);
  48095. }
  48096. /*
  48097. ** Advance the cursor to the next entry in the database. If
  48098. ** successful then set *pRes=0. If the cursor
  48099. ** was already pointing to the last entry in the database before
  48100. ** this routine was called, then set *pRes=1.
  48101. */
  48102. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  48103. int rc;
  48104. int idx;
  48105. MemPage *pPage;
  48106. assert( cursorHoldsMutex(pCur) );
  48107. rc = restoreCursorPosition(pCur);
  48108. if( rc!=SQLITE_OK ){
  48109. return rc;
  48110. }
  48111. assert( pRes!=0 );
  48112. if( CURSOR_INVALID==pCur->eState ){
  48113. *pRes = 1;
  48114. return SQLITE_OK;
  48115. }
  48116. if( pCur->skipNext>0 ){
  48117. pCur->skipNext = 0;
  48118. *pRes = 0;
  48119. return SQLITE_OK;
  48120. }
  48121. pCur->skipNext = 0;
  48122. pPage = pCur->apPage[pCur->iPage];
  48123. idx = ++pCur->aiIdx[pCur->iPage];
  48124. assert( pPage->isInit );
  48125. assert( idx<=pPage->nCell );
  48126. pCur->info.nSize = 0;
  48127. pCur->validNKey = 0;
  48128. if( idx>=pPage->nCell ){
  48129. if( !pPage->leaf ){
  48130. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  48131. if( rc ) return rc;
  48132. rc = moveToLeftmost(pCur);
  48133. *pRes = 0;
  48134. return rc;
  48135. }
  48136. do{
  48137. if( pCur->iPage==0 ){
  48138. *pRes = 1;
  48139. pCur->eState = CURSOR_INVALID;
  48140. return SQLITE_OK;
  48141. }
  48142. moveToParent(pCur);
  48143. pPage = pCur->apPage[pCur->iPage];
  48144. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  48145. *pRes = 0;
  48146. if( pPage->intKey ){
  48147. rc = sqlite3BtreeNext(pCur, pRes);
  48148. }else{
  48149. rc = SQLITE_OK;
  48150. }
  48151. return rc;
  48152. }
  48153. *pRes = 0;
  48154. if( pPage->leaf ){
  48155. return SQLITE_OK;
  48156. }
  48157. rc = moveToLeftmost(pCur);
  48158. return rc;
  48159. }
  48160. /*
  48161. ** Step the cursor to the back to the previous entry in the database. If
  48162. ** successful then set *pRes=0. If the cursor
  48163. ** was already pointing to the first entry in the database before
  48164. ** this routine was called, then set *pRes=1.
  48165. */
  48166. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  48167. int rc;
  48168. MemPage *pPage;
  48169. assert( cursorHoldsMutex(pCur) );
  48170. rc = restoreCursorPosition(pCur);
  48171. if( rc!=SQLITE_OK ){
  48172. return rc;
  48173. }
  48174. pCur->atLast = 0;
  48175. if( CURSOR_INVALID==pCur->eState ){
  48176. *pRes = 1;
  48177. return SQLITE_OK;
  48178. }
  48179. if( pCur->skipNext<0 ){
  48180. pCur->skipNext = 0;
  48181. *pRes = 0;
  48182. return SQLITE_OK;
  48183. }
  48184. pCur->skipNext = 0;
  48185. pPage = pCur->apPage[pCur->iPage];
  48186. assert( pPage->isInit );
  48187. if( !pPage->leaf ){
  48188. int idx = pCur->aiIdx[pCur->iPage];
  48189. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  48190. if( rc ){
  48191. return rc;
  48192. }
  48193. rc = moveToRightmost(pCur);
  48194. }else{
  48195. while( pCur->aiIdx[pCur->iPage]==0 ){
  48196. if( pCur->iPage==0 ){
  48197. pCur->eState = CURSOR_INVALID;
  48198. *pRes = 1;
  48199. return SQLITE_OK;
  48200. }
  48201. moveToParent(pCur);
  48202. }
  48203. pCur->info.nSize = 0;
  48204. pCur->validNKey = 0;
  48205. pCur->aiIdx[pCur->iPage]--;
  48206. pPage = pCur->apPage[pCur->iPage];
  48207. if( pPage->intKey && !pPage->leaf ){
  48208. rc = sqlite3BtreePrevious(pCur, pRes);
  48209. }else{
  48210. rc = SQLITE_OK;
  48211. }
  48212. }
  48213. *pRes = 0;
  48214. return rc;
  48215. }
  48216. /*
  48217. ** Allocate a new page from the database file.
  48218. **
  48219. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  48220. ** has already been called on the new page.) The new page has also
  48221. ** been referenced and the calling routine is responsible for calling
  48222. ** sqlite3PagerUnref() on the new page when it is done.
  48223. **
  48224. ** SQLITE_OK is returned on success. Any other return value indicates
  48225. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  48226. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  48227. **
  48228. ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
  48229. ** locate a page close to the page number "nearby". This can be used in an
  48230. ** attempt to keep related pages close to each other in the database file,
  48231. ** which in turn can make database access faster.
  48232. **
  48233. ** If the "exact" parameter is not 0, and the page-number nearby exists
  48234. ** anywhere on the free-list, then it is guarenteed to be returned. This
  48235. ** is only used by auto-vacuum databases when allocating a new table.
  48236. */
  48237. static int allocateBtreePage(
  48238. BtShared *pBt,
  48239. MemPage **ppPage,
  48240. Pgno *pPgno,
  48241. Pgno nearby,
  48242. u8 exact
  48243. ){
  48244. MemPage *pPage1;
  48245. int rc;
  48246. u32 n; /* Number of pages on the freelist */
  48247. u32 k; /* Number of leaves on the trunk of the freelist */
  48248. MemPage *pTrunk = 0;
  48249. MemPage *pPrevTrunk = 0;
  48250. Pgno mxPage; /* Total size of the database file */
  48251. assert( sqlite3_mutex_held(pBt->mutex) );
  48252. pPage1 = pBt->pPage1;
  48253. mxPage = btreePagecount(pBt);
  48254. n = get4byte(&pPage1->aData[36]);
  48255. testcase( n==mxPage-1 );
  48256. if( n>=mxPage ){
  48257. return SQLITE_CORRUPT_BKPT;
  48258. }
  48259. if( n>0 ){
  48260. /* There are pages on the freelist. Reuse one of those pages. */
  48261. Pgno iTrunk;
  48262. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  48263. /* If the 'exact' parameter was true and a query of the pointer-map
  48264. ** shows that the page 'nearby' is somewhere on the free-list, then
  48265. ** the entire-list will be searched for that page.
  48266. */
  48267. #ifndef SQLITE_OMIT_AUTOVACUUM
  48268. if( exact && nearby<=mxPage ){
  48269. u8 eType;
  48270. assert( nearby>0 );
  48271. assert( pBt->autoVacuum );
  48272. rc = ptrmapGet(pBt, nearby, &eType, 0);
  48273. if( rc ) return rc;
  48274. if( eType==PTRMAP_FREEPAGE ){
  48275. searchList = 1;
  48276. }
  48277. *pPgno = nearby;
  48278. }
  48279. #endif
  48280. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  48281. ** first free-list trunk page. iPrevTrunk is initially 1.
  48282. */
  48283. rc = sqlite3PagerWrite(pPage1->pDbPage);
  48284. if( rc ) return rc;
  48285. put4byte(&pPage1->aData[36], n-1);
  48286. /* The code within this loop is run only once if the 'searchList' variable
  48287. ** is not true. Otherwise, it runs once for each trunk-page on the
  48288. ** free-list until the page 'nearby' is located.
  48289. */
  48290. do {
  48291. pPrevTrunk = pTrunk;
  48292. if( pPrevTrunk ){
  48293. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  48294. }else{
  48295. iTrunk = get4byte(&pPage1->aData[32]);
  48296. }
  48297. testcase( iTrunk==mxPage );
  48298. if( iTrunk>mxPage ){
  48299. rc = SQLITE_CORRUPT_BKPT;
  48300. }else{
  48301. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  48302. }
  48303. if( rc ){
  48304. pTrunk = 0;
  48305. goto end_allocate_page;
  48306. }
  48307. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  48308. if( k==0 && !searchList ){
  48309. /* The trunk has no leaves and the list is not being searched.
  48310. ** So extract the trunk page itself and use it as the newly
  48311. ** allocated page */
  48312. assert( pPrevTrunk==0 );
  48313. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  48314. if( rc ){
  48315. goto end_allocate_page;
  48316. }
  48317. *pPgno = iTrunk;
  48318. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  48319. *ppPage = pTrunk;
  48320. pTrunk = 0;
  48321. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  48322. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  48323. /* Value of k is out of range. Database corruption */
  48324. rc = SQLITE_CORRUPT_BKPT;
  48325. goto end_allocate_page;
  48326. #ifndef SQLITE_OMIT_AUTOVACUUM
  48327. }else if( searchList && nearby==iTrunk ){
  48328. /* The list is being searched and this trunk page is the page
  48329. ** to allocate, regardless of whether it has leaves.
  48330. */
  48331. assert( *pPgno==iTrunk );
  48332. *ppPage = pTrunk;
  48333. searchList = 0;
  48334. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  48335. if( rc ){
  48336. goto end_allocate_page;
  48337. }
  48338. if( k==0 ){
  48339. if( !pPrevTrunk ){
  48340. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  48341. }else{
  48342. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  48343. if( rc!=SQLITE_OK ){
  48344. goto end_allocate_page;
  48345. }
  48346. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  48347. }
  48348. }else{
  48349. /* The trunk page is required by the caller but it contains
  48350. ** pointers to free-list leaves. The first leaf becomes a trunk
  48351. ** page in this case.
  48352. */
  48353. MemPage *pNewTrunk;
  48354. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  48355. if( iNewTrunk>mxPage ){
  48356. rc = SQLITE_CORRUPT_BKPT;
  48357. goto end_allocate_page;
  48358. }
  48359. testcase( iNewTrunk==mxPage );
  48360. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  48361. if( rc!=SQLITE_OK ){
  48362. goto end_allocate_page;
  48363. }
  48364. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  48365. if( rc!=SQLITE_OK ){
  48366. releasePage(pNewTrunk);
  48367. goto end_allocate_page;
  48368. }
  48369. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  48370. put4byte(&pNewTrunk->aData[4], k-1);
  48371. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  48372. releasePage(pNewTrunk);
  48373. if( !pPrevTrunk ){
  48374. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  48375. put4byte(&pPage1->aData[32], iNewTrunk);
  48376. }else{
  48377. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  48378. if( rc ){
  48379. goto end_allocate_page;
  48380. }
  48381. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  48382. }
  48383. }
  48384. pTrunk = 0;
  48385. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  48386. #endif
  48387. }else if( k>0 ){
  48388. /* Extract a leaf from the trunk */
  48389. u32 closest;
  48390. Pgno iPage;
  48391. unsigned char *aData = pTrunk->aData;
  48392. if( nearby>0 ){
  48393. u32 i;
  48394. int dist;
  48395. closest = 0;
  48396. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  48397. for(i=1; i<k; i++){
  48398. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  48399. if( d2<dist ){
  48400. closest = i;
  48401. dist = d2;
  48402. }
  48403. }
  48404. }else{
  48405. closest = 0;
  48406. }
  48407. iPage = get4byte(&aData[8+closest*4]);
  48408. testcase( iPage==mxPage );
  48409. if( iPage>mxPage ){
  48410. rc = SQLITE_CORRUPT_BKPT;
  48411. goto end_allocate_page;
  48412. }
  48413. testcase( iPage==mxPage );
  48414. if( !searchList || iPage==nearby ){
  48415. int noContent;
  48416. *pPgno = iPage;
  48417. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  48418. ": %d more free pages\n",
  48419. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  48420. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  48421. if( rc ) goto end_allocate_page;
  48422. if( closest<k-1 ){
  48423. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  48424. }
  48425. put4byte(&aData[4], k-1);
  48426. noContent = !btreeGetHasContent(pBt, *pPgno);
  48427. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  48428. if( rc==SQLITE_OK ){
  48429. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  48430. if( rc!=SQLITE_OK ){
  48431. releasePage(*ppPage);
  48432. }
  48433. }
  48434. searchList = 0;
  48435. }
  48436. }
  48437. releasePage(pPrevTrunk);
  48438. pPrevTrunk = 0;
  48439. }while( searchList );
  48440. }else{
  48441. /* There are no pages on the freelist, so create a new page at the
  48442. ** end of the file */
  48443. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  48444. if( rc ) return rc;
  48445. pBt->nPage++;
  48446. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  48447. #ifndef SQLITE_OMIT_AUTOVACUUM
  48448. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  48449. /* If *pPgno refers to a pointer-map page, allocate two new pages
  48450. ** at the end of the file instead of one. The first allocated page
  48451. ** becomes a new pointer-map page, the second is used by the caller.
  48452. */
  48453. MemPage *pPg = 0;
  48454. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  48455. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  48456. rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
  48457. if( rc==SQLITE_OK ){
  48458. rc = sqlite3PagerWrite(pPg->pDbPage);
  48459. releasePage(pPg);
  48460. }
  48461. if( rc ) return rc;
  48462. pBt->nPage++;
  48463. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  48464. }
  48465. #endif
  48466. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  48467. *pPgno = pBt->nPage;
  48468. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  48469. rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
  48470. if( rc ) return rc;
  48471. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  48472. if( rc!=SQLITE_OK ){
  48473. releasePage(*ppPage);
  48474. }
  48475. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  48476. }
  48477. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  48478. end_allocate_page:
  48479. releasePage(pTrunk);
  48480. releasePage(pPrevTrunk);
  48481. if( rc==SQLITE_OK ){
  48482. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  48483. releasePage(*ppPage);
  48484. return SQLITE_CORRUPT_BKPT;
  48485. }
  48486. (*ppPage)->isInit = 0;
  48487. }else{
  48488. *ppPage = 0;
  48489. }
  48490. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  48491. return rc;
  48492. }
  48493. /*
  48494. ** This function is used to add page iPage to the database file free-list.
  48495. ** It is assumed that the page is not already a part of the free-list.
  48496. **
  48497. ** The value passed as the second argument to this function is optional.
  48498. ** If the caller happens to have a pointer to the MemPage object
  48499. ** corresponding to page iPage handy, it may pass it as the second value.
  48500. ** Otherwise, it may pass NULL.
  48501. **
  48502. ** If a pointer to a MemPage object is passed as the second argument,
  48503. ** its reference count is not altered by this function.
  48504. */
  48505. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  48506. MemPage *pTrunk = 0; /* Free-list trunk page */
  48507. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  48508. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  48509. MemPage *pPage; /* Page being freed. May be NULL. */
  48510. int rc; /* Return Code */
  48511. int nFree; /* Initial number of pages on free-list */
  48512. assert( sqlite3_mutex_held(pBt->mutex) );
  48513. assert( iPage>1 );
  48514. assert( !pMemPage || pMemPage->pgno==iPage );
  48515. if( pMemPage ){
  48516. pPage = pMemPage;
  48517. sqlite3PagerRef(pPage->pDbPage);
  48518. }else{
  48519. pPage = btreePageLookup(pBt, iPage);
  48520. }
  48521. /* Increment the free page count on pPage1 */
  48522. rc = sqlite3PagerWrite(pPage1->pDbPage);
  48523. if( rc ) goto freepage_out;
  48524. nFree = get4byte(&pPage1->aData[36]);
  48525. put4byte(&pPage1->aData[36], nFree+1);
  48526. if( pBt->secureDelete ){
  48527. /* If the secure_delete option is enabled, then
  48528. ** always fully overwrite deleted information with zeros.
  48529. */
  48530. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  48531. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  48532. ){
  48533. goto freepage_out;
  48534. }
  48535. memset(pPage->aData, 0, pPage->pBt->pageSize);
  48536. }
  48537. /* If the database supports auto-vacuum, write an entry in the pointer-map
  48538. ** to indicate that the page is free.
  48539. */
  48540. if( ISAUTOVACUUM ){
  48541. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  48542. if( rc ) goto freepage_out;
  48543. }
  48544. /* Now manipulate the actual database free-list structure. There are two
  48545. ** possibilities. If the free-list is currently empty, or if the first
  48546. ** trunk page in the free-list is full, then this page will become a
  48547. ** new free-list trunk page. Otherwise, it will become a leaf of the
  48548. ** first trunk page in the current free-list. This block tests if it
  48549. ** is possible to add the page as a new free-list leaf.
  48550. */
  48551. if( nFree!=0 ){
  48552. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  48553. iTrunk = get4byte(&pPage1->aData[32]);
  48554. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  48555. if( rc!=SQLITE_OK ){
  48556. goto freepage_out;
  48557. }
  48558. nLeaf = get4byte(&pTrunk->aData[4]);
  48559. assert( pBt->usableSize>32 );
  48560. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  48561. rc = SQLITE_CORRUPT_BKPT;
  48562. goto freepage_out;
  48563. }
  48564. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  48565. /* In this case there is room on the trunk page to insert the page
  48566. ** being freed as a new leaf.
  48567. **
  48568. ** Note that the trunk page is not really full until it contains
  48569. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  48570. ** coded. But due to a coding error in versions of SQLite prior to
  48571. ** 3.6.0, databases with freelist trunk pages holding more than
  48572. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  48573. ** to maintain backwards compatibility with older versions of SQLite,
  48574. ** we will continue to restrict the number of entries to usableSize/4 - 8
  48575. ** for now. At some point in the future (once everyone has upgraded
  48576. ** to 3.6.0 or later) we should consider fixing the conditional above
  48577. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  48578. */
  48579. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  48580. if( rc==SQLITE_OK ){
  48581. put4byte(&pTrunk->aData[4], nLeaf+1);
  48582. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  48583. if( pPage && !pBt->secureDelete ){
  48584. sqlite3PagerDontWrite(pPage->pDbPage);
  48585. }
  48586. rc = btreeSetHasContent(pBt, iPage);
  48587. }
  48588. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  48589. goto freepage_out;
  48590. }
  48591. }
  48592. /* If control flows to this point, then it was not possible to add the
  48593. ** the page being freed as a leaf page of the first trunk in the free-list.
  48594. ** Possibly because the free-list is empty, or possibly because the
  48595. ** first trunk in the free-list is full. Either way, the page being freed
  48596. ** will become the new first trunk page in the free-list.
  48597. */
  48598. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  48599. goto freepage_out;
  48600. }
  48601. rc = sqlite3PagerWrite(pPage->pDbPage);
  48602. if( rc!=SQLITE_OK ){
  48603. goto freepage_out;
  48604. }
  48605. put4byte(pPage->aData, iTrunk);
  48606. put4byte(&pPage->aData[4], 0);
  48607. put4byte(&pPage1->aData[32], iPage);
  48608. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  48609. freepage_out:
  48610. if( pPage ){
  48611. pPage->isInit = 0;
  48612. }
  48613. releasePage(pPage);
  48614. releasePage(pTrunk);
  48615. return rc;
  48616. }
  48617. static void freePage(MemPage *pPage, int *pRC){
  48618. if( (*pRC)==SQLITE_OK ){
  48619. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  48620. }
  48621. }
  48622. /*
  48623. ** Free any overflow pages associated with the given Cell.
  48624. */
  48625. static int clearCell(MemPage *pPage, unsigned char *pCell){
  48626. BtShared *pBt = pPage->pBt;
  48627. CellInfo info;
  48628. Pgno ovflPgno;
  48629. int rc;
  48630. int nOvfl;
  48631. u32 ovflPageSize;
  48632. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48633. btreeParseCellPtr(pPage, pCell, &info);
  48634. if( info.iOverflow==0 ){
  48635. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  48636. }
  48637. ovflPgno = get4byte(&pCell[info.iOverflow]);
  48638. assert( pBt->usableSize > 4 );
  48639. ovflPageSize = pBt->usableSize - 4;
  48640. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  48641. assert( ovflPgno==0 || nOvfl>0 );
  48642. while( nOvfl-- ){
  48643. Pgno iNext = 0;
  48644. MemPage *pOvfl = 0;
  48645. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  48646. /* 0 is not a legal page number and page 1 cannot be an
  48647. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  48648. ** file the database must be corrupt. */
  48649. return SQLITE_CORRUPT_BKPT;
  48650. }
  48651. if( nOvfl ){
  48652. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  48653. if( rc ) return rc;
  48654. }
  48655. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  48656. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  48657. ){
  48658. /* There is no reason any cursor should have an outstanding reference
  48659. ** to an overflow page belonging to a cell that is being deleted/updated.
  48660. ** So if there exists more than one reference to this page, then it
  48661. ** must not really be an overflow page and the database must be corrupt.
  48662. ** It is helpful to detect this before calling freePage2(), as
  48663. ** freePage2() may zero the page contents if secure-delete mode is
  48664. ** enabled. If this 'overflow' page happens to be a page that the
  48665. ** caller is iterating through or using in some other way, this
  48666. ** can be problematic.
  48667. */
  48668. rc = SQLITE_CORRUPT_BKPT;
  48669. }else{
  48670. rc = freePage2(pBt, pOvfl, ovflPgno);
  48671. }
  48672. if( pOvfl ){
  48673. sqlite3PagerUnref(pOvfl->pDbPage);
  48674. }
  48675. if( rc ) return rc;
  48676. ovflPgno = iNext;
  48677. }
  48678. return SQLITE_OK;
  48679. }
  48680. /*
  48681. ** Create the byte sequence used to represent a cell on page pPage
  48682. ** and write that byte sequence into pCell[]. Overflow pages are
  48683. ** allocated and filled in as necessary. The calling procedure
  48684. ** is responsible for making sure sufficient space has been allocated
  48685. ** for pCell[].
  48686. **
  48687. ** Note that pCell does not necessary need to point to the pPage->aData
  48688. ** area. pCell might point to some temporary storage. The cell will
  48689. ** be constructed in this temporary area then copied into pPage->aData
  48690. ** later.
  48691. */
  48692. static int fillInCell(
  48693. MemPage *pPage, /* The page that contains the cell */
  48694. unsigned char *pCell, /* Complete text of the cell */
  48695. const void *pKey, i64 nKey, /* The key */
  48696. const void *pData,int nData, /* The data */
  48697. int nZero, /* Extra zero bytes to append to pData */
  48698. int *pnSize /* Write cell size here */
  48699. ){
  48700. int nPayload;
  48701. const u8 *pSrc;
  48702. int nSrc, n, rc;
  48703. int spaceLeft;
  48704. MemPage *pOvfl = 0;
  48705. MemPage *pToRelease = 0;
  48706. unsigned char *pPrior;
  48707. unsigned char *pPayload;
  48708. BtShared *pBt = pPage->pBt;
  48709. Pgno pgnoOvfl = 0;
  48710. int nHeader;
  48711. CellInfo info;
  48712. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48713. /* pPage is not necessarily writeable since pCell might be auxiliary
  48714. ** buffer space that is separate from the pPage buffer area */
  48715. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  48716. || sqlite3PagerIswriteable(pPage->pDbPage) );
  48717. /* Fill in the header. */
  48718. nHeader = 0;
  48719. if( !pPage->leaf ){
  48720. nHeader += 4;
  48721. }
  48722. if( pPage->hasData ){
  48723. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  48724. }else{
  48725. nData = nZero = 0;
  48726. }
  48727. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  48728. btreeParseCellPtr(pPage, pCell, &info);
  48729. assert( info.nHeader==nHeader );
  48730. assert( info.nKey==nKey );
  48731. assert( info.nData==(u32)(nData+nZero) );
  48732. /* Fill in the payload */
  48733. nPayload = nData + nZero;
  48734. if( pPage->intKey ){
  48735. pSrc = pData;
  48736. nSrc = nData;
  48737. nData = 0;
  48738. }else{
  48739. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  48740. return SQLITE_CORRUPT_BKPT;
  48741. }
  48742. nPayload += (int)nKey;
  48743. pSrc = pKey;
  48744. nSrc = (int)nKey;
  48745. }
  48746. *pnSize = info.nSize;
  48747. spaceLeft = info.nLocal;
  48748. pPayload = &pCell[nHeader];
  48749. pPrior = &pCell[info.iOverflow];
  48750. while( nPayload>0 ){
  48751. if( spaceLeft==0 ){
  48752. #ifndef SQLITE_OMIT_AUTOVACUUM
  48753. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  48754. if( pBt->autoVacuum ){
  48755. do{
  48756. pgnoOvfl++;
  48757. } while(
  48758. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  48759. );
  48760. }
  48761. #endif
  48762. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  48763. #ifndef SQLITE_OMIT_AUTOVACUUM
  48764. /* If the database supports auto-vacuum, and the second or subsequent
  48765. ** overflow page is being allocated, add an entry to the pointer-map
  48766. ** for that page now.
  48767. **
  48768. ** If this is the first overflow page, then write a partial entry
  48769. ** to the pointer-map. If we write nothing to this pointer-map slot,
  48770. ** then the optimistic overflow chain processing in clearCell()
  48771. ** may misinterpret the uninitialised values and delete the
  48772. ** wrong pages from the database.
  48773. */
  48774. if( pBt->autoVacuum && rc==SQLITE_OK ){
  48775. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  48776. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  48777. if( rc ){
  48778. releasePage(pOvfl);
  48779. }
  48780. }
  48781. #endif
  48782. if( rc ){
  48783. releasePage(pToRelease);
  48784. return rc;
  48785. }
  48786. /* If pToRelease is not zero than pPrior points into the data area
  48787. ** of pToRelease. Make sure pToRelease is still writeable. */
  48788. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  48789. /* If pPrior is part of the data area of pPage, then make sure pPage
  48790. ** is still writeable */
  48791. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  48792. || sqlite3PagerIswriteable(pPage->pDbPage) );
  48793. put4byte(pPrior, pgnoOvfl);
  48794. releasePage(pToRelease);
  48795. pToRelease = pOvfl;
  48796. pPrior = pOvfl->aData;
  48797. put4byte(pPrior, 0);
  48798. pPayload = &pOvfl->aData[4];
  48799. spaceLeft = pBt->usableSize - 4;
  48800. }
  48801. n = nPayload;
  48802. if( n>spaceLeft ) n = spaceLeft;
  48803. /* If pToRelease is not zero than pPayload points into the data area
  48804. ** of pToRelease. Make sure pToRelease is still writeable. */
  48805. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  48806. /* If pPayload is part of the data area of pPage, then make sure pPage
  48807. ** is still writeable */
  48808. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  48809. || sqlite3PagerIswriteable(pPage->pDbPage) );
  48810. if( nSrc>0 ){
  48811. if( n>nSrc ) n = nSrc;
  48812. assert( pSrc );
  48813. memcpy(pPayload, pSrc, n);
  48814. }else{
  48815. memset(pPayload, 0, n);
  48816. }
  48817. nPayload -= n;
  48818. pPayload += n;
  48819. pSrc += n;
  48820. nSrc -= n;
  48821. spaceLeft -= n;
  48822. if( nSrc==0 ){
  48823. nSrc = nData;
  48824. pSrc = pData;
  48825. }
  48826. }
  48827. releasePage(pToRelease);
  48828. return SQLITE_OK;
  48829. }
  48830. /*
  48831. ** Remove the i-th cell from pPage. This routine effects pPage only.
  48832. ** The cell content is not freed or deallocated. It is assumed that
  48833. ** the cell content has been copied someplace else. This routine just
  48834. ** removes the reference to the cell from pPage.
  48835. **
  48836. ** "sz" must be the number of bytes in the cell.
  48837. */
  48838. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  48839. int i; /* Loop counter */
  48840. u32 pc; /* Offset to cell content of cell being deleted */
  48841. u8 *data; /* pPage->aData */
  48842. u8 *ptr; /* Used to move bytes around within data[] */
  48843. int rc; /* The return code */
  48844. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  48845. if( *pRC ) return;
  48846. assert( idx>=0 && idx<pPage->nCell );
  48847. assert( sz==cellSize(pPage, idx) );
  48848. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  48849. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48850. data = pPage->aData;
  48851. ptr = &data[pPage->cellOffset + 2*idx];
  48852. pc = get2byte(ptr);
  48853. hdr = pPage->hdrOffset;
  48854. testcase( pc==get2byte(&data[hdr+5]) );
  48855. testcase( pc+sz==pPage->pBt->usableSize );
  48856. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  48857. *pRC = SQLITE_CORRUPT_BKPT;
  48858. return;
  48859. }
  48860. rc = freeSpace(pPage, pc, sz);
  48861. if( rc ){
  48862. *pRC = rc;
  48863. return;
  48864. }
  48865. for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
  48866. ptr[0] = ptr[2];
  48867. ptr[1] = ptr[3];
  48868. }
  48869. pPage->nCell--;
  48870. put2byte(&data[hdr+3], pPage->nCell);
  48871. pPage->nFree += 2;
  48872. }
  48873. /*
  48874. ** Insert a new cell on pPage at cell index "i". pCell points to the
  48875. ** content of the cell.
  48876. **
  48877. ** If the cell content will fit on the page, then put it there. If it
  48878. ** will not fit, then make a copy of the cell content into pTemp if
  48879. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  48880. ** in pPage->aOvfl[] and make it point to the cell content (either
  48881. ** in pTemp or the original pCell) and also record its index.
  48882. ** Allocating a new entry in pPage->aCell[] implies that
  48883. ** pPage->nOverflow is incremented.
  48884. **
  48885. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  48886. ** cell. The caller will overwrite them after this function returns. If
  48887. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  48888. ** (but pCell+nSkip is always valid).
  48889. */
  48890. static void insertCell(
  48891. MemPage *pPage, /* Page into which we are copying */
  48892. int i, /* New cell becomes the i-th cell of the page */
  48893. u8 *pCell, /* Content of the new cell */
  48894. int sz, /* Bytes of content in pCell */
  48895. u8 *pTemp, /* Temp storage space for pCell, if needed */
  48896. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  48897. int *pRC /* Read and write return code from here */
  48898. ){
  48899. int idx = 0; /* Where to write new cell content in data[] */
  48900. int j; /* Loop counter */
  48901. int end; /* First byte past the last cell pointer in data[] */
  48902. int ins; /* Index in data[] where new cell pointer is inserted */
  48903. int cellOffset; /* Address of first cell pointer in data[] */
  48904. u8 *data; /* The content of the whole page */
  48905. u8 *ptr; /* Used for moving information around in data[] */
  48906. int nSkip = (iChild ? 4 : 0);
  48907. if( *pRC ) return;
  48908. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  48909. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
  48910. assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
  48911. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48912. /* The cell should normally be sized correctly. However, when moving a
  48913. ** malformed cell from a leaf page to an interior page, if the cell size
  48914. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  48915. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  48916. ** the term after the || in the following assert(). */
  48917. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  48918. if( pPage->nOverflow || sz+2>pPage->nFree ){
  48919. if( pTemp ){
  48920. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  48921. pCell = pTemp;
  48922. }
  48923. if( iChild ){
  48924. put4byte(pCell, iChild);
  48925. }
  48926. j = pPage->nOverflow++;
  48927. assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
  48928. pPage->aOvfl[j].pCell = pCell;
  48929. pPage->aOvfl[j].idx = (u16)i;
  48930. }else{
  48931. int rc = sqlite3PagerWrite(pPage->pDbPage);
  48932. if( rc!=SQLITE_OK ){
  48933. *pRC = rc;
  48934. return;
  48935. }
  48936. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  48937. data = pPage->aData;
  48938. cellOffset = pPage->cellOffset;
  48939. end = cellOffset + 2*pPage->nCell;
  48940. ins = cellOffset + 2*i;
  48941. rc = allocateSpace(pPage, sz, &idx);
  48942. if( rc ){ *pRC = rc; return; }
  48943. /* The allocateSpace() routine guarantees the following two properties
  48944. ** if it returns success */
  48945. assert( idx >= end+2 );
  48946. assert( idx+sz <= (int)pPage->pBt->usableSize );
  48947. pPage->nCell++;
  48948. pPage->nFree -= (u16)(2 + sz);
  48949. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  48950. if( iChild ){
  48951. put4byte(&data[idx], iChild);
  48952. }
  48953. for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
  48954. ptr[0] = ptr[-2];
  48955. ptr[1] = ptr[-1];
  48956. }
  48957. put2byte(&data[ins], idx);
  48958. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  48959. #ifndef SQLITE_OMIT_AUTOVACUUM
  48960. if( pPage->pBt->autoVacuum ){
  48961. /* The cell may contain a pointer to an overflow page. If so, write
  48962. ** the entry for the overflow page into the pointer map.
  48963. */
  48964. ptrmapPutOvflPtr(pPage, pCell, pRC);
  48965. }
  48966. #endif
  48967. }
  48968. }
  48969. /*
  48970. ** Add a list of cells to a page. The page should be initially empty.
  48971. ** The cells are guaranteed to fit on the page.
  48972. */
  48973. static void assemblePage(
  48974. MemPage *pPage, /* The page to be assemblied */
  48975. int nCell, /* The number of cells to add to this page */
  48976. u8 **apCell, /* Pointers to cell bodies */
  48977. u16 *aSize /* Sizes of the cells */
  48978. ){
  48979. int i; /* Loop counter */
  48980. u8 *pCellptr; /* Address of next cell pointer */
  48981. int cellbody; /* Address of next cell body */
  48982. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  48983. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  48984. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  48985. assert( pPage->nOverflow==0 );
  48986. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  48987. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  48988. && (int)MX_CELL(pPage->pBt)<=10921);
  48989. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  48990. /* Check that the page has just been zeroed by zeroPage() */
  48991. assert( pPage->nCell==0 );
  48992. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  48993. pCellptr = &data[pPage->cellOffset + nCell*2];
  48994. cellbody = nUsable;
  48995. for(i=nCell-1; i>=0; i--){
  48996. pCellptr -= 2;
  48997. cellbody -= aSize[i];
  48998. put2byte(pCellptr, cellbody);
  48999. memcpy(&data[cellbody], apCell[i], aSize[i]);
  49000. }
  49001. put2byte(&data[hdr+3], nCell);
  49002. put2byte(&data[hdr+5], cellbody);
  49003. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  49004. pPage->nCell = (u16)nCell;
  49005. }
  49006. /*
  49007. ** The following parameters determine how many adjacent pages get involved
  49008. ** in a balancing operation. NN is the number of neighbors on either side
  49009. ** of the page that participate in the balancing operation. NB is the
  49010. ** total number of pages that participate, including the target page and
  49011. ** NN neighbors on either side.
  49012. **
  49013. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  49014. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  49015. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  49016. ** The value of NN appears to give the best results overall.
  49017. */
  49018. #define NN 1 /* Number of neighbors on either side of pPage */
  49019. #define NB (NN*2+1) /* Total pages involved in the balance */
  49020. #ifndef SQLITE_OMIT_QUICKBALANCE
  49021. /*
  49022. ** This version of balance() handles the common special case where
  49023. ** a new entry is being inserted on the extreme right-end of the
  49024. ** tree, in other words, when the new entry will become the largest
  49025. ** entry in the tree.
  49026. **
  49027. ** Instead of trying to balance the 3 right-most leaf pages, just add
  49028. ** a new page to the right-hand side and put the one new entry in
  49029. ** that page. This leaves the right side of the tree somewhat
  49030. ** unbalanced. But odds are that we will be inserting new entries
  49031. ** at the end soon afterwards so the nearly empty page will quickly
  49032. ** fill up. On average.
  49033. **
  49034. ** pPage is the leaf page which is the right-most page in the tree.
  49035. ** pParent is its parent. pPage must have a single overflow entry
  49036. ** which is also the right-most entry on the page.
  49037. **
  49038. ** The pSpace buffer is used to store a temporary copy of the divider
  49039. ** cell that will be inserted into pParent. Such a cell consists of a 4
  49040. ** byte page number followed by a variable length integer. In other
  49041. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  49042. ** least 13 bytes in size.
  49043. */
  49044. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  49045. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  49046. MemPage *pNew; /* Newly allocated page */
  49047. int rc; /* Return Code */
  49048. Pgno pgnoNew; /* Page number of pNew */
  49049. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49050. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  49051. assert( pPage->nOverflow==1 );
  49052. /* This error condition is now caught prior to reaching this function */
  49053. if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
  49054. /* Allocate a new page. This page will become the right-sibling of
  49055. ** pPage. Make the parent page writable, so that the new divider cell
  49056. ** may be inserted. If both these operations are successful, proceed.
  49057. */
  49058. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  49059. if( rc==SQLITE_OK ){
  49060. u8 *pOut = &pSpace[4];
  49061. u8 *pCell = pPage->aOvfl[0].pCell;
  49062. u16 szCell = cellSizePtr(pPage, pCell);
  49063. u8 *pStop;
  49064. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  49065. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  49066. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  49067. assemblePage(pNew, 1, &pCell, &szCell);
  49068. /* If this is an auto-vacuum database, update the pointer map
  49069. ** with entries for the new page, and any pointer from the
  49070. ** cell on the page to an overflow page. If either of these
  49071. ** operations fails, the return code is set, but the contents
  49072. ** of the parent page are still manipulated by thh code below.
  49073. ** That is Ok, at this point the parent page is guaranteed to
  49074. ** be marked as dirty. Returning an error code will cause a
  49075. ** rollback, undoing any changes made to the parent page.
  49076. */
  49077. if( ISAUTOVACUUM ){
  49078. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  49079. if( szCell>pNew->minLocal ){
  49080. ptrmapPutOvflPtr(pNew, pCell, &rc);
  49081. }
  49082. }
  49083. /* Create a divider cell to insert into pParent. The divider cell
  49084. ** consists of a 4-byte page number (the page number of pPage) and
  49085. ** a variable length key value (which must be the same value as the
  49086. ** largest key on pPage).
  49087. **
  49088. ** To find the largest key value on pPage, first find the right-most
  49089. ** cell on pPage. The first two fields of this cell are the
  49090. ** record-length (a variable length integer at most 32-bits in size)
  49091. ** and the key value (a variable length integer, may have any value).
  49092. ** The first of the while(...) loops below skips over the record-length
  49093. ** field. The second while(...) loop copies the key value from the
  49094. ** cell on pPage into the pSpace buffer.
  49095. */
  49096. pCell = findCell(pPage, pPage->nCell-1);
  49097. pStop = &pCell[9];
  49098. while( (*(pCell++)&0x80) && pCell<pStop );
  49099. pStop = &pCell[9];
  49100. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  49101. /* Insert the new divider cell into pParent. */
  49102. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  49103. 0, pPage->pgno, &rc);
  49104. /* Set the right-child pointer of pParent to point to the new page. */
  49105. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  49106. /* Release the reference to the new page. */
  49107. releasePage(pNew);
  49108. }
  49109. return rc;
  49110. }
  49111. #endif /* SQLITE_OMIT_QUICKBALANCE */
  49112. #if 0
  49113. /*
  49114. ** This function does not contribute anything to the operation of SQLite.
  49115. ** it is sometimes activated temporarily while debugging code responsible
  49116. ** for setting pointer-map entries.
  49117. */
  49118. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  49119. int i, j;
  49120. for(i=0; i<nPage; i++){
  49121. Pgno n;
  49122. u8 e;
  49123. MemPage *pPage = apPage[i];
  49124. BtShared *pBt = pPage->pBt;
  49125. assert( pPage->isInit );
  49126. for(j=0; j<pPage->nCell; j++){
  49127. CellInfo info;
  49128. u8 *z;
  49129. z = findCell(pPage, j);
  49130. btreeParseCellPtr(pPage, z, &info);
  49131. if( info.iOverflow ){
  49132. Pgno ovfl = get4byte(&z[info.iOverflow]);
  49133. ptrmapGet(pBt, ovfl, &e, &n);
  49134. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  49135. }
  49136. if( !pPage->leaf ){
  49137. Pgno child = get4byte(z);
  49138. ptrmapGet(pBt, child, &e, &n);
  49139. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  49140. }
  49141. }
  49142. if( !pPage->leaf ){
  49143. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  49144. ptrmapGet(pBt, child, &e, &n);
  49145. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  49146. }
  49147. }
  49148. return 1;
  49149. }
  49150. #endif
  49151. /*
  49152. ** This function is used to copy the contents of the b-tree node stored
  49153. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  49154. ** the pointer-map entries for each child page are updated so that the
  49155. ** parent page stored in the pointer map is page pTo. If pFrom contained
  49156. ** any cells with overflow page pointers, then the corresponding pointer
  49157. ** map entries are also updated so that the parent page is page pTo.
  49158. **
  49159. ** If pFrom is currently carrying any overflow cells (entries in the
  49160. ** MemPage.aOvfl[] array), they are not copied to pTo.
  49161. **
  49162. ** Before returning, page pTo is reinitialized using btreeInitPage().
  49163. **
  49164. ** The performance of this function is not critical. It is only used by
  49165. ** the balance_shallower() and balance_deeper() procedures, neither of
  49166. ** which are called often under normal circumstances.
  49167. */
  49168. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  49169. if( (*pRC)==SQLITE_OK ){
  49170. BtShared * const pBt = pFrom->pBt;
  49171. u8 * const aFrom = pFrom->aData;
  49172. u8 * const aTo = pTo->aData;
  49173. int const iFromHdr = pFrom->hdrOffset;
  49174. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  49175. int rc;
  49176. int iData;
  49177. assert( pFrom->isInit );
  49178. assert( pFrom->nFree>=iToHdr );
  49179. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  49180. /* Copy the b-tree node content from page pFrom to page pTo. */
  49181. iData = get2byte(&aFrom[iFromHdr+5]);
  49182. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  49183. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  49184. /* Reinitialize page pTo so that the contents of the MemPage structure
  49185. ** match the new data. The initialization of pTo can actually fail under
  49186. ** fairly obscure circumstances, even though it is a copy of initialized
  49187. ** page pFrom.
  49188. */
  49189. pTo->isInit = 0;
  49190. rc = btreeInitPage(pTo);
  49191. if( rc!=SQLITE_OK ){
  49192. *pRC = rc;
  49193. return;
  49194. }
  49195. /* If this is an auto-vacuum database, update the pointer-map entries
  49196. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  49197. */
  49198. if( ISAUTOVACUUM ){
  49199. *pRC = setChildPtrmaps(pTo);
  49200. }
  49201. }
  49202. }
  49203. /*
  49204. ** This routine redistributes cells on the iParentIdx'th child of pParent
  49205. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  49206. ** same amount of free space. Usually a single sibling on either side of the
  49207. ** page are used in the balancing, though both siblings might come from one
  49208. ** side if the page is the first or last child of its parent. If the page
  49209. ** has fewer than 2 siblings (something which can only happen if the page
  49210. ** is a root page or a child of a root page) then all available siblings
  49211. ** participate in the balancing.
  49212. **
  49213. ** The number of siblings of the page might be increased or decreased by
  49214. ** one or two in an effort to keep pages nearly full but not over full.
  49215. **
  49216. ** Note that when this routine is called, some of the cells on the page
  49217. ** might not actually be stored in MemPage.aData[]. This can happen
  49218. ** if the page is overfull. This routine ensures that all cells allocated
  49219. ** to the page and its siblings fit into MemPage.aData[] before returning.
  49220. **
  49221. ** In the course of balancing the page and its siblings, cells may be
  49222. ** inserted into or removed from the parent page (pParent). Doing so
  49223. ** may cause the parent page to become overfull or underfull. If this
  49224. ** happens, it is the responsibility of the caller to invoke the correct
  49225. ** balancing routine to fix this problem (see the balance() routine).
  49226. **
  49227. ** If this routine fails for any reason, it might leave the database
  49228. ** in a corrupted state. So if this routine fails, the database should
  49229. ** be rolled back.
  49230. **
  49231. ** The third argument to this function, aOvflSpace, is a pointer to a
  49232. ** buffer big enough to hold one page. If while inserting cells into the parent
  49233. ** page (pParent) the parent page becomes overfull, this buffer is
  49234. ** used to store the parent's overflow cells. Because this function inserts
  49235. ** a maximum of four divider cells into the parent page, and the maximum
  49236. ** size of a cell stored within an internal node is always less than 1/4
  49237. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  49238. ** enough for all overflow cells.
  49239. **
  49240. ** If aOvflSpace is set to a null pointer, this function returns
  49241. ** SQLITE_NOMEM.
  49242. */
  49243. static int balance_nonroot(
  49244. MemPage *pParent, /* Parent page of siblings being balanced */
  49245. int iParentIdx, /* Index of "the page" in pParent */
  49246. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  49247. int isRoot /* True if pParent is a root-page */
  49248. ){
  49249. BtShared *pBt; /* The whole database */
  49250. int nCell = 0; /* Number of cells in apCell[] */
  49251. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  49252. int nNew = 0; /* Number of pages in apNew[] */
  49253. int nOld; /* Number of pages in apOld[] */
  49254. int i, j, k; /* Loop counters */
  49255. int nxDiv; /* Next divider slot in pParent->aCell[] */
  49256. int rc = SQLITE_OK; /* The return code */
  49257. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  49258. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  49259. int usableSpace; /* Bytes in pPage beyond the header */
  49260. int pageFlags; /* Value of pPage->aData[0] */
  49261. int subtotal; /* Subtotal of bytes in cells on one page */
  49262. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  49263. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  49264. int szScratch; /* Size of scratch memory requested */
  49265. MemPage *apOld[NB]; /* pPage and up to two siblings */
  49266. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  49267. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  49268. u8 *pRight; /* Location in parent of right-sibling pointer */
  49269. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  49270. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  49271. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  49272. u8 **apCell = 0; /* All cells begin balanced */
  49273. u16 *szCell; /* Local size of all cells in apCell[] */
  49274. u8 *aSpace1; /* Space for copies of dividers cells */
  49275. Pgno pgno; /* Temp var to store a page number in */
  49276. pBt = pParent->pBt;
  49277. assert( sqlite3_mutex_held(pBt->mutex) );
  49278. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  49279. #if 0
  49280. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  49281. #endif
  49282. /* At this point pParent may have at most one overflow cell. And if
  49283. ** this overflow cell is present, it must be the cell with
  49284. ** index iParentIdx. This scenario comes about when this function
  49285. ** is called (indirectly) from sqlite3BtreeDelete().
  49286. */
  49287. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  49288. assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
  49289. if( !aOvflSpace ){
  49290. return SQLITE_NOMEM;
  49291. }
  49292. /* Find the sibling pages to balance. Also locate the cells in pParent
  49293. ** that divide the siblings. An attempt is made to find NN siblings on
  49294. ** either side of pPage. More siblings are taken from one side, however,
  49295. ** if there are fewer than NN siblings on the other side. If pParent
  49296. ** has NB or fewer children then all children of pParent are taken.
  49297. **
  49298. ** This loop also drops the divider cells from the parent page. This
  49299. ** way, the remainder of the function does not have to deal with any
  49300. ** overflow cells in the parent page, since if any existed they will
  49301. ** have already been removed.
  49302. */
  49303. i = pParent->nOverflow + pParent->nCell;
  49304. if( i<2 ){
  49305. nxDiv = 0;
  49306. nOld = i+1;
  49307. }else{
  49308. nOld = 3;
  49309. if( iParentIdx==0 ){
  49310. nxDiv = 0;
  49311. }else if( iParentIdx==i ){
  49312. nxDiv = i-2;
  49313. }else{
  49314. nxDiv = iParentIdx-1;
  49315. }
  49316. i = 2;
  49317. }
  49318. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  49319. pRight = &pParent->aData[pParent->hdrOffset+8];
  49320. }else{
  49321. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  49322. }
  49323. pgno = get4byte(pRight);
  49324. while( 1 ){
  49325. rc = getAndInitPage(pBt, pgno, &apOld[i]);
  49326. if( rc ){
  49327. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  49328. goto balance_cleanup;
  49329. }
  49330. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  49331. if( (i--)==0 ) break;
  49332. if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
  49333. apDiv[i] = pParent->aOvfl[0].pCell;
  49334. pgno = get4byte(apDiv[i]);
  49335. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  49336. pParent->nOverflow = 0;
  49337. }else{
  49338. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  49339. pgno = get4byte(apDiv[i]);
  49340. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  49341. /* Drop the cell from the parent page. apDiv[i] still points to
  49342. ** the cell within the parent, even though it has been dropped.
  49343. ** This is safe because dropping a cell only overwrites the first
  49344. ** four bytes of it, and this function does not need the first
  49345. ** four bytes of the divider cell. So the pointer is safe to use
  49346. ** later on.
  49347. **
  49348. ** Unless SQLite is compiled in secure-delete mode. In this case,
  49349. ** the dropCell() routine will overwrite the entire cell with zeroes.
  49350. ** In this case, temporarily copy the cell into the aOvflSpace[]
  49351. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  49352. ** is allocated. */
  49353. if( pBt->secureDelete ){
  49354. int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  49355. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  49356. rc = SQLITE_CORRUPT_BKPT;
  49357. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  49358. goto balance_cleanup;
  49359. }else{
  49360. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  49361. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  49362. }
  49363. }
  49364. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  49365. }
  49366. }
  49367. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  49368. ** alignment */
  49369. nMaxCells = (nMaxCells + 3)&~3;
  49370. /*
  49371. ** Allocate space for memory structures
  49372. */
  49373. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  49374. szScratch =
  49375. nMaxCells*sizeof(u8*) /* apCell */
  49376. + nMaxCells*sizeof(u16) /* szCell */
  49377. + pBt->pageSize /* aSpace1 */
  49378. + k*nOld; /* Page copies (apCopy) */
  49379. apCell = sqlite3ScratchMalloc( szScratch );
  49380. if( apCell==0 ){
  49381. rc = SQLITE_NOMEM;
  49382. goto balance_cleanup;
  49383. }
  49384. szCell = (u16*)&apCell[nMaxCells];
  49385. aSpace1 = (u8*)&szCell[nMaxCells];
  49386. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  49387. /*
  49388. ** Load pointers to all cells on sibling pages and the divider cells
  49389. ** into the local apCell[] array. Make copies of the divider cells
  49390. ** into space obtained from aSpace1[] and remove the the divider Cells
  49391. ** from pParent.
  49392. **
  49393. ** If the siblings are on leaf pages, then the child pointers of the
  49394. ** divider cells are stripped from the cells before they are copied
  49395. ** into aSpace1[]. In this way, all cells in apCell[] are without
  49396. ** child pointers. If siblings are not leaves, then all cell in
  49397. ** apCell[] include child pointers. Either way, all cells in apCell[]
  49398. ** are alike.
  49399. **
  49400. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  49401. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  49402. */
  49403. leafCorrection = apOld[0]->leaf*4;
  49404. leafData = apOld[0]->hasData;
  49405. for(i=0; i<nOld; i++){
  49406. int limit;
  49407. /* Before doing anything else, take a copy of the i'th original sibling
  49408. ** The rest of this function will use data from the copies rather
  49409. ** that the original pages since the original pages will be in the
  49410. ** process of being overwritten. */
  49411. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  49412. memcpy(pOld, apOld[i], sizeof(MemPage));
  49413. pOld->aData = (void*)&pOld[1];
  49414. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  49415. limit = pOld->nCell+pOld->nOverflow;
  49416. for(j=0; j<limit; j++){
  49417. assert( nCell<nMaxCells );
  49418. apCell[nCell] = findOverflowCell(pOld, j);
  49419. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  49420. nCell++;
  49421. }
  49422. if( i<nOld-1 && !leafData){
  49423. u16 sz = (u16)szNew[i];
  49424. u8 *pTemp;
  49425. assert( nCell<nMaxCells );
  49426. szCell[nCell] = sz;
  49427. pTemp = &aSpace1[iSpace1];
  49428. iSpace1 += sz;
  49429. assert( sz<=pBt->maxLocal+23 );
  49430. assert( iSpace1 <= (int)pBt->pageSize );
  49431. memcpy(pTemp, apDiv[i], sz);
  49432. apCell[nCell] = pTemp+leafCorrection;
  49433. assert( leafCorrection==0 || leafCorrection==4 );
  49434. szCell[nCell] = szCell[nCell] - leafCorrection;
  49435. if( !pOld->leaf ){
  49436. assert( leafCorrection==0 );
  49437. assert( pOld->hdrOffset==0 );
  49438. /* The right pointer of the child page pOld becomes the left
  49439. ** pointer of the divider cell */
  49440. memcpy(apCell[nCell], &pOld->aData[8], 4);
  49441. }else{
  49442. assert( leafCorrection==4 );
  49443. if( szCell[nCell]<4 ){
  49444. /* Do not allow any cells smaller than 4 bytes. */
  49445. szCell[nCell] = 4;
  49446. }
  49447. }
  49448. nCell++;
  49449. }
  49450. }
  49451. /*
  49452. ** Figure out the number of pages needed to hold all nCell cells.
  49453. ** Store this number in "k". Also compute szNew[] which is the total
  49454. ** size of all cells on the i-th page and cntNew[] which is the index
  49455. ** in apCell[] of the cell that divides page i from page i+1.
  49456. ** cntNew[k] should equal nCell.
  49457. **
  49458. ** Values computed by this block:
  49459. **
  49460. ** k: The total number of sibling pages
  49461. ** szNew[i]: Spaced used on the i-th sibling page.
  49462. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  49463. ** the right of the i-th sibling page.
  49464. ** usableSpace: Number of bytes of space available on each sibling.
  49465. **
  49466. */
  49467. usableSpace = pBt->usableSize - 12 + leafCorrection;
  49468. for(subtotal=k=i=0; i<nCell; i++){
  49469. assert( i<nMaxCells );
  49470. subtotal += szCell[i] + 2;
  49471. if( subtotal > usableSpace ){
  49472. szNew[k] = subtotal - szCell[i];
  49473. cntNew[k] = i;
  49474. if( leafData ){ i--; }
  49475. subtotal = 0;
  49476. k++;
  49477. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  49478. }
  49479. }
  49480. szNew[k] = subtotal;
  49481. cntNew[k] = nCell;
  49482. k++;
  49483. /*
  49484. ** The packing computed by the previous block is biased toward the siblings
  49485. ** on the left side. The left siblings are always nearly full, while the
  49486. ** right-most sibling might be nearly empty. This block of code attempts
  49487. ** to adjust the packing of siblings to get a better balance.
  49488. **
  49489. ** This adjustment is more than an optimization. The packing above might
  49490. ** be so out of balance as to be illegal. For example, the right-most
  49491. ** sibling might be completely empty. This adjustment is not optional.
  49492. */
  49493. for(i=k-1; i>0; i--){
  49494. int szRight = szNew[i]; /* Size of sibling on the right */
  49495. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  49496. int r; /* Index of right-most cell in left sibling */
  49497. int d; /* Index of first cell to the left of right sibling */
  49498. r = cntNew[i-1] - 1;
  49499. d = r + 1 - leafData;
  49500. assert( d<nMaxCells );
  49501. assert( r<nMaxCells );
  49502. while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
  49503. szRight += szCell[d] + 2;
  49504. szLeft -= szCell[r] + 2;
  49505. cntNew[i-1]--;
  49506. r = cntNew[i-1] - 1;
  49507. d = r + 1 - leafData;
  49508. }
  49509. szNew[i] = szRight;
  49510. szNew[i-1] = szLeft;
  49511. }
  49512. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  49513. ** a virtual root page. A virtual root page is when the real root
  49514. ** page is page 1 and we are the only child of that page.
  49515. */
  49516. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  49517. TRACE(("BALANCE: old: %d %d %d ",
  49518. apOld[0]->pgno,
  49519. nOld>=2 ? apOld[1]->pgno : 0,
  49520. nOld>=3 ? apOld[2]->pgno : 0
  49521. ));
  49522. /*
  49523. ** Allocate k new pages. Reuse old pages where possible.
  49524. */
  49525. if( apOld[0]->pgno<=1 ){
  49526. rc = SQLITE_CORRUPT_BKPT;
  49527. goto balance_cleanup;
  49528. }
  49529. pageFlags = apOld[0]->aData[0];
  49530. for(i=0; i<k; i++){
  49531. MemPage *pNew;
  49532. if( i<nOld ){
  49533. pNew = apNew[i] = apOld[i];
  49534. apOld[i] = 0;
  49535. rc = sqlite3PagerWrite(pNew->pDbPage);
  49536. nNew++;
  49537. if( rc ) goto balance_cleanup;
  49538. }else{
  49539. assert( i>0 );
  49540. rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
  49541. if( rc ) goto balance_cleanup;
  49542. apNew[i] = pNew;
  49543. nNew++;
  49544. /* Set the pointer-map entry for the new sibling page. */
  49545. if( ISAUTOVACUUM ){
  49546. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  49547. if( rc!=SQLITE_OK ){
  49548. goto balance_cleanup;
  49549. }
  49550. }
  49551. }
  49552. }
  49553. /* Free any old pages that were not reused as new pages.
  49554. */
  49555. while( i<nOld ){
  49556. freePage(apOld[i], &rc);
  49557. if( rc ) goto balance_cleanup;
  49558. releasePage(apOld[i]);
  49559. apOld[i] = 0;
  49560. i++;
  49561. }
  49562. /*
  49563. ** Put the new pages in accending order. This helps to
  49564. ** keep entries in the disk file in order so that a scan
  49565. ** of the table is a linear scan through the file. That
  49566. ** in turn helps the operating system to deliver pages
  49567. ** from the disk more rapidly.
  49568. **
  49569. ** An O(n^2) insertion sort algorithm is used, but since
  49570. ** n is never more than NB (a small constant), that should
  49571. ** not be a problem.
  49572. **
  49573. ** When NB==3, this one optimization makes the database
  49574. ** about 25% faster for large insertions and deletions.
  49575. */
  49576. for(i=0; i<k-1; i++){
  49577. int minV = apNew[i]->pgno;
  49578. int minI = i;
  49579. for(j=i+1; j<k; j++){
  49580. if( apNew[j]->pgno<(unsigned)minV ){
  49581. minI = j;
  49582. minV = apNew[j]->pgno;
  49583. }
  49584. }
  49585. if( minI>i ){
  49586. MemPage *pT;
  49587. pT = apNew[i];
  49588. apNew[i] = apNew[minI];
  49589. apNew[minI] = pT;
  49590. }
  49591. }
  49592. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  49593. apNew[0]->pgno, szNew[0],
  49594. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  49595. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  49596. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  49597. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  49598. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  49599. put4byte(pRight, apNew[nNew-1]->pgno);
  49600. /*
  49601. ** Evenly distribute the data in apCell[] across the new pages.
  49602. ** Insert divider cells into pParent as necessary.
  49603. */
  49604. j = 0;
  49605. for(i=0; i<nNew; i++){
  49606. /* Assemble the new sibling page. */
  49607. MemPage *pNew = apNew[i];
  49608. assert( j<nMaxCells );
  49609. zeroPage(pNew, pageFlags);
  49610. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  49611. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  49612. assert( pNew->nOverflow==0 );
  49613. j = cntNew[i];
  49614. /* If the sibling page assembled above was not the right-most sibling,
  49615. ** insert a divider cell into the parent page.
  49616. */
  49617. assert( i<nNew-1 || j==nCell );
  49618. if( j<nCell ){
  49619. u8 *pCell;
  49620. u8 *pTemp;
  49621. int sz;
  49622. assert( j<nMaxCells );
  49623. pCell = apCell[j];
  49624. sz = szCell[j] + leafCorrection;
  49625. pTemp = &aOvflSpace[iOvflSpace];
  49626. if( !pNew->leaf ){
  49627. memcpy(&pNew->aData[8], pCell, 4);
  49628. }else if( leafData ){
  49629. /* If the tree is a leaf-data tree, and the siblings are leaves,
  49630. ** then there is no divider cell in apCell[]. Instead, the divider
  49631. ** cell consists of the integer key for the right-most cell of
  49632. ** the sibling-page assembled above only.
  49633. */
  49634. CellInfo info;
  49635. j--;
  49636. btreeParseCellPtr(pNew, apCell[j], &info);
  49637. pCell = pTemp;
  49638. sz = 4 + putVarint(&pCell[4], info.nKey);
  49639. pTemp = 0;
  49640. }else{
  49641. pCell -= 4;
  49642. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  49643. ** previously stored on a leaf node, and its reported size was 4
  49644. ** bytes, then it may actually be smaller than this
  49645. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  49646. ** any cell). But it is important to pass the correct size to
  49647. ** insertCell(), so reparse the cell now.
  49648. **
  49649. ** Note that this can never happen in an SQLite data file, as all
  49650. ** cells are at least 4 bytes. It only happens in b-trees used
  49651. ** to evaluate "IN (SELECT ...)" and similar clauses.
  49652. */
  49653. if( szCell[j]==4 ){
  49654. assert(leafCorrection==4);
  49655. sz = cellSizePtr(pParent, pCell);
  49656. }
  49657. }
  49658. iOvflSpace += sz;
  49659. assert( sz<=pBt->maxLocal+23 );
  49660. assert( iOvflSpace <= (int)pBt->pageSize );
  49661. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  49662. if( rc!=SQLITE_OK ) goto balance_cleanup;
  49663. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  49664. j++;
  49665. nxDiv++;
  49666. }
  49667. }
  49668. assert( j==nCell );
  49669. assert( nOld>0 );
  49670. assert( nNew>0 );
  49671. if( (pageFlags & PTF_LEAF)==0 ){
  49672. u8 *zChild = &apCopy[nOld-1]->aData[8];
  49673. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  49674. }
  49675. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  49676. /* The root page of the b-tree now contains no cells. The only sibling
  49677. ** page is the right-child of the parent. Copy the contents of the
  49678. ** child page into the parent, decreasing the overall height of the
  49679. ** b-tree structure by one. This is described as the "balance-shallower"
  49680. ** sub-algorithm in some documentation.
  49681. **
  49682. ** If this is an auto-vacuum database, the call to copyNodeContent()
  49683. ** sets all pointer-map entries corresponding to database image pages
  49684. ** for which the pointer is stored within the content being copied.
  49685. **
  49686. ** The second assert below verifies that the child page is defragmented
  49687. ** (it must be, as it was just reconstructed using assemblePage()). This
  49688. ** is important if the parent page happens to be page 1 of the database
  49689. ** image. */
  49690. assert( nNew==1 );
  49691. assert( apNew[0]->nFree ==
  49692. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  49693. );
  49694. copyNodeContent(apNew[0], pParent, &rc);
  49695. freePage(apNew[0], &rc);
  49696. }else if( ISAUTOVACUUM ){
  49697. /* Fix the pointer-map entries for all the cells that were shifted around.
  49698. ** There are several different types of pointer-map entries that need to
  49699. ** be dealt with by this routine. Some of these have been set already, but
  49700. ** many have not. The following is a summary:
  49701. **
  49702. ** 1) The entries associated with new sibling pages that were not
  49703. ** siblings when this function was called. These have already
  49704. ** been set. We don't need to worry about old siblings that were
  49705. ** moved to the free-list - the freePage() code has taken care
  49706. ** of those.
  49707. **
  49708. ** 2) The pointer-map entries associated with the first overflow
  49709. ** page in any overflow chains used by new divider cells. These
  49710. ** have also already been taken care of by the insertCell() code.
  49711. **
  49712. ** 3) If the sibling pages are not leaves, then the child pages of
  49713. ** cells stored on the sibling pages may need to be updated.
  49714. **
  49715. ** 4) If the sibling pages are not internal intkey nodes, then any
  49716. ** overflow pages used by these cells may need to be updated
  49717. ** (internal intkey nodes never contain pointers to overflow pages).
  49718. **
  49719. ** 5) If the sibling pages are not leaves, then the pointer-map
  49720. ** entries for the right-child pages of each sibling may need
  49721. ** to be updated.
  49722. **
  49723. ** Cases 1 and 2 are dealt with above by other code. The next
  49724. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  49725. ** setting a pointer map entry is a relatively expensive operation, this
  49726. ** code only sets pointer map entries for child or overflow pages that have
  49727. ** actually moved between pages. */
  49728. MemPage *pNew = apNew[0];
  49729. MemPage *pOld = apCopy[0];
  49730. int nOverflow = pOld->nOverflow;
  49731. int iNextOld = pOld->nCell + nOverflow;
  49732. int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
  49733. j = 0; /* Current 'old' sibling page */
  49734. k = 0; /* Current 'new' sibling page */
  49735. for(i=0; i<nCell; i++){
  49736. int isDivider = 0;
  49737. while( i==iNextOld ){
  49738. /* Cell i is the cell immediately following the last cell on old
  49739. ** sibling page j. If the siblings are not leaf pages of an
  49740. ** intkey b-tree, then cell i was a divider cell. */
  49741. pOld = apCopy[++j];
  49742. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  49743. if( pOld->nOverflow ){
  49744. nOverflow = pOld->nOverflow;
  49745. iOverflow = i + !leafData + pOld->aOvfl[0].idx;
  49746. }
  49747. isDivider = !leafData;
  49748. }
  49749. assert(nOverflow>0 || iOverflow<i );
  49750. assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
  49751. assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
  49752. if( i==iOverflow ){
  49753. isDivider = 1;
  49754. if( (--nOverflow)>0 ){
  49755. iOverflow++;
  49756. }
  49757. }
  49758. if( i==cntNew[k] ){
  49759. /* Cell i is the cell immediately following the last cell on new
  49760. ** sibling page k. If the siblings are not leaf pages of an
  49761. ** intkey b-tree, then cell i is a divider cell. */
  49762. pNew = apNew[++k];
  49763. if( !leafData ) continue;
  49764. }
  49765. assert( j<nOld );
  49766. assert( k<nNew );
  49767. /* If the cell was originally divider cell (and is not now) or
  49768. ** an overflow cell, or if the cell was located on a different sibling
  49769. ** page before the balancing, then the pointer map entries associated
  49770. ** with any child or overflow pages need to be updated. */
  49771. if( isDivider || pOld->pgno!=pNew->pgno ){
  49772. if( !leafCorrection ){
  49773. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  49774. }
  49775. if( szCell[i]>pNew->minLocal ){
  49776. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  49777. }
  49778. }
  49779. }
  49780. if( !leafCorrection ){
  49781. for(i=0; i<nNew; i++){
  49782. u32 key = get4byte(&apNew[i]->aData[8]);
  49783. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  49784. }
  49785. }
  49786. #if 0
  49787. /* The ptrmapCheckPages() contains assert() statements that verify that
  49788. ** all pointer map pages are set correctly. This is helpful while
  49789. ** debugging. This is usually disabled because a corrupt database may
  49790. ** cause an assert() statement to fail. */
  49791. ptrmapCheckPages(apNew, nNew);
  49792. ptrmapCheckPages(&pParent, 1);
  49793. #endif
  49794. }
  49795. assert( pParent->isInit );
  49796. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  49797. nOld, nNew, nCell));
  49798. /*
  49799. ** Cleanup before returning.
  49800. */
  49801. balance_cleanup:
  49802. sqlite3ScratchFree(apCell);
  49803. for(i=0; i<nOld; i++){
  49804. releasePage(apOld[i]);
  49805. }
  49806. for(i=0; i<nNew; i++){
  49807. releasePage(apNew[i]);
  49808. }
  49809. return rc;
  49810. }
  49811. /*
  49812. ** This function is called when the root page of a b-tree structure is
  49813. ** overfull (has one or more overflow pages).
  49814. **
  49815. ** A new child page is allocated and the contents of the current root
  49816. ** page, including overflow cells, are copied into the child. The root
  49817. ** page is then overwritten to make it an empty page with the right-child
  49818. ** pointer pointing to the new page.
  49819. **
  49820. ** Before returning, all pointer-map entries corresponding to pages
  49821. ** that the new child-page now contains pointers to are updated. The
  49822. ** entry corresponding to the new right-child pointer of the root
  49823. ** page is also updated.
  49824. **
  49825. ** If successful, *ppChild is set to contain a reference to the child
  49826. ** page and SQLITE_OK is returned. In this case the caller is required
  49827. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  49828. ** an error code is returned and *ppChild is set to 0.
  49829. */
  49830. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  49831. int rc; /* Return value from subprocedures */
  49832. MemPage *pChild = 0; /* Pointer to a new child page */
  49833. Pgno pgnoChild = 0; /* Page number of the new child page */
  49834. BtShared *pBt = pRoot->pBt; /* The BTree */
  49835. assert( pRoot->nOverflow>0 );
  49836. assert( sqlite3_mutex_held(pBt->mutex) );
  49837. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  49838. ** page that will become the new right-child of pPage. Copy the contents
  49839. ** of the node stored on pRoot into the new child page.
  49840. */
  49841. rc = sqlite3PagerWrite(pRoot->pDbPage);
  49842. if( rc==SQLITE_OK ){
  49843. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  49844. copyNodeContent(pRoot, pChild, &rc);
  49845. if( ISAUTOVACUUM ){
  49846. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  49847. }
  49848. }
  49849. if( rc ){
  49850. *ppChild = 0;
  49851. releasePage(pChild);
  49852. return rc;
  49853. }
  49854. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  49855. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  49856. assert( pChild->nCell==pRoot->nCell );
  49857. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  49858. /* Copy the overflow cells from pRoot to pChild */
  49859. memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
  49860. pChild->nOverflow = pRoot->nOverflow;
  49861. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  49862. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  49863. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  49864. *ppChild = pChild;
  49865. return SQLITE_OK;
  49866. }
  49867. /*
  49868. ** The page that pCur currently points to has just been modified in
  49869. ** some way. This function figures out if this modification means the
  49870. ** tree needs to be balanced, and if so calls the appropriate balancing
  49871. ** routine. Balancing routines are:
  49872. **
  49873. ** balance_quick()
  49874. ** balance_deeper()
  49875. ** balance_nonroot()
  49876. */
  49877. static int balance(BtCursor *pCur){
  49878. int rc = SQLITE_OK;
  49879. const int nMin = pCur->pBt->usableSize * 2 / 3;
  49880. u8 aBalanceQuickSpace[13];
  49881. u8 *pFree = 0;
  49882. TESTONLY( int balance_quick_called = 0 );
  49883. TESTONLY( int balance_deeper_called = 0 );
  49884. do {
  49885. int iPage = pCur->iPage;
  49886. MemPage *pPage = pCur->apPage[iPage];
  49887. if( iPage==0 ){
  49888. if( pPage->nOverflow ){
  49889. /* The root page of the b-tree is overfull. In this case call the
  49890. ** balance_deeper() function to create a new child for the root-page
  49891. ** and copy the current contents of the root-page to it. The
  49892. ** next iteration of the do-loop will balance the child page.
  49893. */
  49894. assert( (balance_deeper_called++)==0 );
  49895. rc = balance_deeper(pPage, &pCur->apPage[1]);
  49896. if( rc==SQLITE_OK ){
  49897. pCur->iPage = 1;
  49898. pCur->aiIdx[0] = 0;
  49899. pCur->aiIdx[1] = 0;
  49900. assert( pCur->apPage[1]->nOverflow );
  49901. }
  49902. }else{
  49903. break;
  49904. }
  49905. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  49906. break;
  49907. }else{
  49908. MemPage * const pParent = pCur->apPage[iPage-1];
  49909. int const iIdx = pCur->aiIdx[iPage-1];
  49910. rc = sqlite3PagerWrite(pParent->pDbPage);
  49911. if( rc==SQLITE_OK ){
  49912. #ifndef SQLITE_OMIT_QUICKBALANCE
  49913. if( pPage->hasData
  49914. && pPage->nOverflow==1
  49915. && pPage->aOvfl[0].idx==pPage->nCell
  49916. && pParent->pgno!=1
  49917. && pParent->nCell==iIdx
  49918. ){
  49919. /* Call balance_quick() to create a new sibling of pPage on which
  49920. ** to store the overflow cell. balance_quick() inserts a new cell
  49921. ** into pParent, which may cause pParent overflow. If this
  49922. ** happens, the next interation of the do-loop will balance pParent
  49923. ** use either balance_nonroot() or balance_deeper(). Until this
  49924. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  49925. ** buffer.
  49926. **
  49927. ** The purpose of the following assert() is to check that only a
  49928. ** single call to balance_quick() is made for each call to this
  49929. ** function. If this were not verified, a subtle bug involving reuse
  49930. ** of the aBalanceQuickSpace[] might sneak in.
  49931. */
  49932. assert( (balance_quick_called++)==0 );
  49933. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  49934. }else
  49935. #endif
  49936. {
  49937. /* In this case, call balance_nonroot() to redistribute cells
  49938. ** between pPage and up to 2 of its sibling pages. This involves
  49939. ** modifying the contents of pParent, which may cause pParent to
  49940. ** become overfull or underfull. The next iteration of the do-loop
  49941. ** will balance the parent page to correct this.
  49942. **
  49943. ** If the parent page becomes overfull, the overflow cell or cells
  49944. ** are stored in the pSpace buffer allocated immediately below.
  49945. ** A subsequent iteration of the do-loop will deal with this by
  49946. ** calling balance_nonroot() (balance_deeper() may be called first,
  49947. ** but it doesn't deal with overflow cells - just moves them to a
  49948. ** different page). Once this subsequent call to balance_nonroot()
  49949. ** has completed, it is safe to release the pSpace buffer used by
  49950. ** the previous call, as the overflow cell data will have been
  49951. ** copied either into the body of a database page or into the new
  49952. ** pSpace buffer passed to the latter call to balance_nonroot().
  49953. */
  49954. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  49955. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
  49956. if( pFree ){
  49957. /* If pFree is not NULL, it points to the pSpace buffer used
  49958. ** by a previous call to balance_nonroot(). Its contents are
  49959. ** now stored either on real database pages or within the
  49960. ** new pSpace buffer, so it may be safely freed here. */
  49961. sqlite3PageFree(pFree);
  49962. }
  49963. /* The pSpace buffer will be freed after the next call to
  49964. ** balance_nonroot(), or just before this function returns, whichever
  49965. ** comes first. */
  49966. pFree = pSpace;
  49967. }
  49968. }
  49969. pPage->nOverflow = 0;
  49970. /* The next iteration of the do-loop balances the parent page. */
  49971. releasePage(pPage);
  49972. pCur->iPage--;
  49973. }
  49974. }while( rc==SQLITE_OK );
  49975. if( pFree ){
  49976. sqlite3PageFree(pFree);
  49977. }
  49978. return rc;
  49979. }
  49980. /*
  49981. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  49982. ** and the data is given by (pData,nData). The cursor is used only to
  49983. ** define what table the record should be inserted into. The cursor
  49984. ** is left pointing at a random location.
  49985. **
  49986. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  49987. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  49988. **
  49989. ** If the seekResult parameter is non-zero, then a successful call to
  49990. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  49991. ** been performed. seekResult is the search result returned (a negative
  49992. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  49993. ** a positive value if pCur points at an etry that is larger than
  49994. ** (pKey, nKey)).
  49995. **
  49996. ** If the seekResult parameter is non-zero, then the caller guarantees that
  49997. ** cursor pCur is pointing at the existing copy of a row that is to be
  49998. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  49999. ** point to any entry or to no entry at all and so this function has to seek
  50000. ** the cursor before the new key can be inserted.
  50001. */
  50002. SQLITE_PRIVATE int sqlite3BtreeInsert(
  50003. BtCursor *pCur, /* Insert data into the table of this cursor */
  50004. const void *pKey, i64 nKey, /* The key of the new record */
  50005. const void *pData, int nData, /* The data of the new record */
  50006. int nZero, /* Number of extra 0 bytes to append to data */
  50007. int appendBias, /* True if this is likely an append */
  50008. int seekResult /* Result of prior MovetoUnpacked() call */
  50009. ){
  50010. int rc;
  50011. int loc = seekResult; /* -1: before desired location +1: after */
  50012. int szNew = 0;
  50013. int idx;
  50014. MemPage *pPage;
  50015. Btree *p = pCur->pBtree;
  50016. BtShared *pBt = p->pBt;
  50017. unsigned char *oldCell;
  50018. unsigned char *newCell = 0;
  50019. if( pCur->eState==CURSOR_FAULT ){
  50020. assert( pCur->skipNext!=SQLITE_OK );
  50021. return pCur->skipNext;
  50022. }
  50023. assert( cursorHoldsMutex(pCur) );
  50024. assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
  50025. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  50026. /* Assert that the caller has been consistent. If this cursor was opened
  50027. ** expecting an index b-tree, then the caller should be inserting blob
  50028. ** keys with no associated data. If the cursor was opened expecting an
  50029. ** intkey table, the caller should be inserting integer keys with a
  50030. ** blob of associated data. */
  50031. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  50032. /* If this is an insert into a table b-tree, invalidate any incrblob
  50033. ** cursors open on the row being replaced (assuming this is a replace
  50034. ** operation - if it is not, the following is a no-op). */
  50035. if( pCur->pKeyInfo==0 ){
  50036. invalidateIncrblobCursors(p, nKey, 0);
  50037. }
  50038. /* Save the positions of any other cursors open on this table.
  50039. **
  50040. ** In some cases, the call to btreeMoveto() below is a no-op. For
  50041. ** example, when inserting data into a table with auto-generated integer
  50042. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  50043. ** integer key to use. It then calls this function to actually insert the
  50044. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  50045. ** that the cursor is already where it needs to be and returns without
  50046. ** doing any work. To avoid thwarting these optimizations, it is important
  50047. ** not to clear the cursor here.
  50048. */
  50049. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  50050. if( rc ) return rc;
  50051. if( !loc ){
  50052. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  50053. if( rc ) return rc;
  50054. }
  50055. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  50056. pPage = pCur->apPage[pCur->iPage];
  50057. assert( pPage->intKey || nKey>=0 );
  50058. assert( pPage->leaf || !pPage->intKey );
  50059. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  50060. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  50061. loc==0 ? "overwrite" : "new entry"));
  50062. assert( pPage->isInit );
  50063. allocateTempSpace(pBt);
  50064. newCell = pBt->pTmpSpace;
  50065. if( newCell==0 ) return SQLITE_NOMEM;
  50066. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  50067. if( rc ) goto end_insert;
  50068. assert( szNew==cellSizePtr(pPage, newCell) );
  50069. assert( szNew <= MX_CELL_SIZE(pBt) );
  50070. idx = pCur->aiIdx[pCur->iPage];
  50071. if( loc==0 ){
  50072. u16 szOld;
  50073. assert( idx<pPage->nCell );
  50074. rc = sqlite3PagerWrite(pPage->pDbPage);
  50075. if( rc ){
  50076. goto end_insert;
  50077. }
  50078. oldCell = findCell(pPage, idx);
  50079. if( !pPage->leaf ){
  50080. memcpy(newCell, oldCell, 4);
  50081. }
  50082. szOld = cellSizePtr(pPage, oldCell);
  50083. rc = clearCell(pPage, oldCell);
  50084. dropCell(pPage, idx, szOld, &rc);
  50085. if( rc ) goto end_insert;
  50086. }else if( loc<0 && pPage->nCell>0 ){
  50087. assert( pPage->leaf );
  50088. idx = ++pCur->aiIdx[pCur->iPage];
  50089. }else{
  50090. assert( pPage->leaf );
  50091. }
  50092. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  50093. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  50094. /* If no error has occured and pPage has an overflow cell, call balance()
  50095. ** to redistribute the cells within the tree. Since balance() may move
  50096. ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  50097. ** variables.
  50098. **
  50099. ** Previous versions of SQLite called moveToRoot() to move the cursor
  50100. ** back to the root page as balance() used to invalidate the contents
  50101. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  50102. ** set the cursor state to "invalid". This makes common insert operations
  50103. ** slightly faster.
  50104. **
  50105. ** There is a subtle but important optimization here too. When inserting
  50106. ** multiple records into an intkey b-tree using a single cursor (as can
  50107. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  50108. ** is advantageous to leave the cursor pointing to the last entry in
  50109. ** the b-tree if possible. If the cursor is left pointing to the last
  50110. ** entry in the table, and the next row inserted has an integer key
  50111. ** larger than the largest existing key, it is possible to insert the
  50112. ** row without seeking the cursor. This can be a big performance boost.
  50113. */
  50114. pCur->info.nSize = 0;
  50115. pCur->validNKey = 0;
  50116. if( rc==SQLITE_OK && pPage->nOverflow ){
  50117. rc = balance(pCur);
  50118. /* Must make sure nOverflow is reset to zero even if the balance()
  50119. ** fails. Internal data structure corruption will result otherwise.
  50120. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  50121. ** from trying to save the current position of the cursor. */
  50122. pCur->apPage[pCur->iPage]->nOverflow = 0;
  50123. pCur->eState = CURSOR_INVALID;
  50124. }
  50125. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  50126. end_insert:
  50127. return rc;
  50128. }
  50129. /*
  50130. ** Delete the entry that the cursor is pointing to. The cursor
  50131. ** is left pointing at a arbitrary location.
  50132. */
  50133. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  50134. Btree *p = pCur->pBtree;
  50135. BtShared *pBt = p->pBt;
  50136. int rc; /* Return code */
  50137. MemPage *pPage; /* Page to delete cell from */
  50138. unsigned char *pCell; /* Pointer to cell to delete */
  50139. int iCellIdx; /* Index of cell to delete */
  50140. int iCellDepth; /* Depth of node containing pCell */
  50141. assert( cursorHoldsMutex(pCur) );
  50142. assert( pBt->inTransaction==TRANS_WRITE );
  50143. assert( !pBt->readOnly );
  50144. assert( pCur->wrFlag );
  50145. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  50146. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  50147. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  50148. || NEVER(pCur->eState!=CURSOR_VALID)
  50149. ){
  50150. return SQLITE_ERROR; /* Something has gone awry. */
  50151. }
  50152. /* If this is a delete operation to remove a row from a table b-tree,
  50153. ** invalidate any incrblob cursors open on the row being deleted. */
  50154. if( pCur->pKeyInfo==0 ){
  50155. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  50156. }
  50157. iCellDepth = pCur->iPage;
  50158. iCellIdx = pCur->aiIdx[iCellDepth];
  50159. pPage = pCur->apPage[iCellDepth];
  50160. pCell = findCell(pPage, iCellIdx);
  50161. /* If the page containing the entry to delete is not a leaf page, move
  50162. ** the cursor to the largest entry in the tree that is smaller than
  50163. ** the entry being deleted. This cell will replace the cell being deleted
  50164. ** from the internal node. The 'previous' entry is used for this instead
  50165. ** of the 'next' entry, as the previous entry is always a part of the
  50166. ** sub-tree headed by the child page of the cell being deleted. This makes
  50167. ** balancing the tree following the delete operation easier. */
  50168. if( !pPage->leaf ){
  50169. int notUsed;
  50170. rc = sqlite3BtreePrevious(pCur, &notUsed);
  50171. if( rc ) return rc;
  50172. }
  50173. /* Save the positions of any other cursors open on this table before
  50174. ** making any modifications. Make the page containing the entry to be
  50175. ** deleted writable. Then free any overflow pages associated with the
  50176. ** entry and finally remove the cell itself from within the page.
  50177. */
  50178. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  50179. if( rc ) return rc;
  50180. rc = sqlite3PagerWrite(pPage->pDbPage);
  50181. if( rc ) return rc;
  50182. rc = clearCell(pPage, pCell);
  50183. dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  50184. if( rc ) return rc;
  50185. /* If the cell deleted was not located on a leaf page, then the cursor
  50186. ** is currently pointing to the largest entry in the sub-tree headed
  50187. ** by the child-page of the cell that was just deleted from an internal
  50188. ** node. The cell from the leaf node needs to be moved to the internal
  50189. ** node to replace the deleted cell. */
  50190. if( !pPage->leaf ){
  50191. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  50192. int nCell;
  50193. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  50194. unsigned char *pTmp;
  50195. pCell = findCell(pLeaf, pLeaf->nCell-1);
  50196. nCell = cellSizePtr(pLeaf, pCell);
  50197. assert( MX_CELL_SIZE(pBt) >= nCell );
  50198. allocateTempSpace(pBt);
  50199. pTmp = pBt->pTmpSpace;
  50200. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  50201. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  50202. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  50203. if( rc ) return rc;
  50204. }
  50205. /* Balance the tree. If the entry deleted was located on a leaf page,
  50206. ** then the cursor still points to that page. In this case the first
  50207. ** call to balance() repairs the tree, and the if(...) condition is
  50208. ** never true.
  50209. **
  50210. ** Otherwise, if the entry deleted was on an internal node page, then
  50211. ** pCur is pointing to the leaf page from which a cell was removed to
  50212. ** replace the cell deleted from the internal node. This is slightly
  50213. ** tricky as the leaf node may be underfull, and the internal node may
  50214. ** be either under or overfull. In this case run the balancing algorithm
  50215. ** on the leaf node first. If the balance proceeds far enough up the
  50216. ** tree that we can be sure that any problem in the internal node has
  50217. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  50218. ** walk the cursor up the tree to the internal node and balance it as
  50219. ** well. */
  50220. rc = balance(pCur);
  50221. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  50222. while( pCur->iPage>iCellDepth ){
  50223. releasePage(pCur->apPage[pCur->iPage--]);
  50224. }
  50225. rc = balance(pCur);
  50226. }
  50227. if( rc==SQLITE_OK ){
  50228. moveToRoot(pCur);
  50229. }
  50230. return rc;
  50231. }
  50232. /*
  50233. ** Create a new BTree table. Write into *piTable the page
  50234. ** number for the root page of the new table.
  50235. **
  50236. ** The type of type is determined by the flags parameter. Only the
  50237. ** following values of flags are currently in use. Other values for
  50238. ** flags might not work:
  50239. **
  50240. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  50241. ** BTREE_ZERODATA Used for SQL indices
  50242. */
  50243. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  50244. BtShared *pBt = p->pBt;
  50245. MemPage *pRoot;
  50246. Pgno pgnoRoot;
  50247. int rc;
  50248. int ptfFlags; /* Page-type flage for the root page of new table */
  50249. assert( sqlite3BtreeHoldsMutex(p) );
  50250. assert( pBt->inTransaction==TRANS_WRITE );
  50251. assert( !pBt->readOnly );
  50252. #ifdef SQLITE_OMIT_AUTOVACUUM
  50253. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  50254. if( rc ){
  50255. return rc;
  50256. }
  50257. #else
  50258. if( pBt->autoVacuum ){
  50259. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  50260. MemPage *pPageMove; /* The page to move to. */
  50261. /* Creating a new table may probably require moving an existing database
  50262. ** to make room for the new tables root page. In case this page turns
  50263. ** out to be an overflow page, delete all overflow page-map caches
  50264. ** held by open cursors.
  50265. */
  50266. invalidateAllOverflowCache(pBt);
  50267. /* Read the value of meta[3] from the database to determine where the
  50268. ** root page of the new table should go. meta[3] is the largest root-page
  50269. ** created so far, so the new root-page is (meta[3]+1).
  50270. */
  50271. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  50272. pgnoRoot++;
  50273. /* The new root-page may not be allocated on a pointer-map page, or the
  50274. ** PENDING_BYTE page.
  50275. */
  50276. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  50277. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  50278. pgnoRoot++;
  50279. }
  50280. assert( pgnoRoot>=3 );
  50281. /* Allocate a page. The page that currently resides at pgnoRoot will
  50282. ** be moved to the allocated page (unless the allocated page happens
  50283. ** to reside at pgnoRoot).
  50284. */
  50285. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
  50286. if( rc!=SQLITE_OK ){
  50287. return rc;
  50288. }
  50289. if( pgnoMove!=pgnoRoot ){
  50290. /* pgnoRoot is the page that will be used for the root-page of
  50291. ** the new table (assuming an error did not occur). But we were
  50292. ** allocated pgnoMove. If required (i.e. if it was not allocated
  50293. ** by extending the file), the current page at position pgnoMove
  50294. ** is already journaled.
  50295. */
  50296. u8 eType = 0;
  50297. Pgno iPtrPage = 0;
  50298. releasePage(pPageMove);
  50299. /* Move the page currently at pgnoRoot to pgnoMove. */
  50300. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  50301. if( rc!=SQLITE_OK ){
  50302. return rc;
  50303. }
  50304. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  50305. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  50306. rc = SQLITE_CORRUPT_BKPT;
  50307. }
  50308. if( rc!=SQLITE_OK ){
  50309. releasePage(pRoot);
  50310. return rc;
  50311. }
  50312. assert( eType!=PTRMAP_ROOTPAGE );
  50313. assert( eType!=PTRMAP_FREEPAGE );
  50314. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  50315. releasePage(pRoot);
  50316. /* Obtain the page at pgnoRoot */
  50317. if( rc!=SQLITE_OK ){
  50318. return rc;
  50319. }
  50320. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  50321. if( rc!=SQLITE_OK ){
  50322. return rc;
  50323. }
  50324. rc = sqlite3PagerWrite(pRoot->pDbPage);
  50325. if( rc!=SQLITE_OK ){
  50326. releasePage(pRoot);
  50327. return rc;
  50328. }
  50329. }else{
  50330. pRoot = pPageMove;
  50331. }
  50332. /* Update the pointer-map and meta-data with the new root-page number. */
  50333. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  50334. if( rc ){
  50335. releasePage(pRoot);
  50336. return rc;
  50337. }
  50338. /* When the new root page was allocated, page 1 was made writable in
  50339. ** order either to increase the database filesize, or to decrement the
  50340. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  50341. */
  50342. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  50343. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  50344. if( NEVER(rc) ){
  50345. releasePage(pRoot);
  50346. return rc;
  50347. }
  50348. }else{
  50349. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  50350. if( rc ) return rc;
  50351. }
  50352. #endif
  50353. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  50354. if( createTabFlags & BTREE_INTKEY ){
  50355. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  50356. }else{
  50357. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  50358. }
  50359. zeroPage(pRoot, ptfFlags);
  50360. sqlite3PagerUnref(pRoot->pDbPage);
  50361. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  50362. *piTable = (int)pgnoRoot;
  50363. return SQLITE_OK;
  50364. }
  50365. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  50366. int rc;
  50367. sqlite3BtreeEnter(p);
  50368. rc = btreeCreateTable(p, piTable, flags);
  50369. sqlite3BtreeLeave(p);
  50370. return rc;
  50371. }
  50372. /*
  50373. ** Erase the given database page and all its children. Return
  50374. ** the page to the freelist.
  50375. */
  50376. static int clearDatabasePage(
  50377. BtShared *pBt, /* The BTree that contains the table */
  50378. Pgno pgno, /* Page number to clear */
  50379. int freePageFlag, /* Deallocate page if true */
  50380. int *pnChange /* Add number of Cells freed to this counter */
  50381. ){
  50382. MemPage *pPage;
  50383. int rc;
  50384. unsigned char *pCell;
  50385. int i;
  50386. assert( sqlite3_mutex_held(pBt->mutex) );
  50387. if( pgno>btreePagecount(pBt) ){
  50388. return SQLITE_CORRUPT_BKPT;
  50389. }
  50390. rc = getAndInitPage(pBt, pgno, &pPage);
  50391. if( rc ) return rc;
  50392. for(i=0; i<pPage->nCell; i++){
  50393. pCell = findCell(pPage, i);
  50394. if( !pPage->leaf ){
  50395. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  50396. if( rc ) goto cleardatabasepage_out;
  50397. }
  50398. rc = clearCell(pPage, pCell);
  50399. if( rc ) goto cleardatabasepage_out;
  50400. }
  50401. if( !pPage->leaf ){
  50402. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  50403. if( rc ) goto cleardatabasepage_out;
  50404. }else if( pnChange ){
  50405. assert( pPage->intKey );
  50406. *pnChange += pPage->nCell;
  50407. }
  50408. if( freePageFlag ){
  50409. freePage(pPage, &rc);
  50410. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  50411. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  50412. }
  50413. cleardatabasepage_out:
  50414. releasePage(pPage);
  50415. return rc;
  50416. }
  50417. /*
  50418. ** Delete all information from a single table in the database. iTable is
  50419. ** the page number of the root of the table. After this routine returns,
  50420. ** the root page is empty, but still exists.
  50421. **
  50422. ** This routine will fail with SQLITE_LOCKED if there are any open
  50423. ** read cursors on the table. Open write cursors are moved to the
  50424. ** root of the table.
  50425. **
  50426. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  50427. ** integer value pointed to by pnChange is incremented by the number of
  50428. ** entries in the table.
  50429. */
  50430. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  50431. int rc;
  50432. BtShared *pBt = p->pBt;
  50433. sqlite3BtreeEnter(p);
  50434. assert( p->inTrans==TRANS_WRITE );
  50435. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  50436. ** is the root of a table b-tree - if it is not, the following call is
  50437. ** a no-op). */
  50438. invalidateIncrblobCursors(p, 0, 1);
  50439. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  50440. if( SQLITE_OK==rc ){
  50441. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  50442. }
  50443. sqlite3BtreeLeave(p);
  50444. return rc;
  50445. }
  50446. /*
  50447. ** Erase all information in a table and add the root of the table to
  50448. ** the freelist. Except, the root of the principle table (the one on
  50449. ** page 1) is never added to the freelist.
  50450. **
  50451. ** This routine will fail with SQLITE_LOCKED if there are any open
  50452. ** cursors on the table.
  50453. **
  50454. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  50455. ** root page in the database file, then the last root page
  50456. ** in the database file is moved into the slot formerly occupied by
  50457. ** iTable and that last slot formerly occupied by the last root page
  50458. ** is added to the freelist instead of iTable. In this say, all
  50459. ** root pages are kept at the beginning of the database file, which
  50460. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  50461. ** page number that used to be the last root page in the file before
  50462. ** the move. If no page gets moved, *piMoved is set to 0.
  50463. ** The last root page is recorded in meta[3] and the value of
  50464. ** meta[3] is updated by this procedure.
  50465. */
  50466. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  50467. int rc;
  50468. MemPage *pPage = 0;
  50469. BtShared *pBt = p->pBt;
  50470. assert( sqlite3BtreeHoldsMutex(p) );
  50471. assert( p->inTrans==TRANS_WRITE );
  50472. /* It is illegal to drop a table if any cursors are open on the
  50473. ** database. This is because in auto-vacuum mode the backend may
  50474. ** need to move another root-page to fill a gap left by the deleted
  50475. ** root page. If an open cursor was using this page a problem would
  50476. ** occur.
  50477. **
  50478. ** This error is caught long before control reaches this point.
  50479. */
  50480. if( NEVER(pBt->pCursor) ){
  50481. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  50482. return SQLITE_LOCKED_SHAREDCACHE;
  50483. }
  50484. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  50485. if( rc ) return rc;
  50486. rc = sqlite3BtreeClearTable(p, iTable, 0);
  50487. if( rc ){
  50488. releasePage(pPage);
  50489. return rc;
  50490. }
  50491. *piMoved = 0;
  50492. if( iTable>1 ){
  50493. #ifdef SQLITE_OMIT_AUTOVACUUM
  50494. freePage(pPage, &rc);
  50495. releasePage(pPage);
  50496. #else
  50497. if( pBt->autoVacuum ){
  50498. Pgno maxRootPgno;
  50499. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  50500. if( iTable==maxRootPgno ){
  50501. /* If the table being dropped is the table with the largest root-page
  50502. ** number in the database, put the root page on the free list.
  50503. */
  50504. freePage(pPage, &rc);
  50505. releasePage(pPage);
  50506. if( rc!=SQLITE_OK ){
  50507. return rc;
  50508. }
  50509. }else{
  50510. /* The table being dropped does not have the largest root-page
  50511. ** number in the database. So move the page that does into the
  50512. ** gap left by the deleted root-page.
  50513. */
  50514. MemPage *pMove;
  50515. releasePage(pPage);
  50516. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  50517. if( rc!=SQLITE_OK ){
  50518. return rc;
  50519. }
  50520. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  50521. releasePage(pMove);
  50522. if( rc!=SQLITE_OK ){
  50523. return rc;
  50524. }
  50525. pMove = 0;
  50526. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  50527. freePage(pMove, &rc);
  50528. releasePage(pMove);
  50529. if( rc!=SQLITE_OK ){
  50530. return rc;
  50531. }
  50532. *piMoved = maxRootPgno;
  50533. }
  50534. /* Set the new 'max-root-page' value in the database header. This
  50535. ** is the old value less one, less one more if that happens to
  50536. ** be a root-page number, less one again if that is the
  50537. ** PENDING_BYTE_PAGE.
  50538. */
  50539. maxRootPgno--;
  50540. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  50541. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  50542. maxRootPgno--;
  50543. }
  50544. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  50545. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  50546. }else{
  50547. freePage(pPage, &rc);
  50548. releasePage(pPage);
  50549. }
  50550. #endif
  50551. }else{
  50552. /* If sqlite3BtreeDropTable was called on page 1.
  50553. ** This really never should happen except in a corrupt
  50554. ** database.
  50555. */
  50556. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  50557. releasePage(pPage);
  50558. }
  50559. return rc;
  50560. }
  50561. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  50562. int rc;
  50563. sqlite3BtreeEnter(p);
  50564. rc = btreeDropTable(p, iTable, piMoved);
  50565. sqlite3BtreeLeave(p);
  50566. return rc;
  50567. }
  50568. /*
  50569. ** This function may only be called if the b-tree connection already
  50570. ** has a read or write transaction open on the database.
  50571. **
  50572. ** Read the meta-information out of a database file. Meta[0]
  50573. ** is the number of free pages currently in the database. Meta[1]
  50574. ** through meta[15] are available for use by higher layers. Meta[0]
  50575. ** is read-only, the others are read/write.
  50576. **
  50577. ** The schema layer numbers meta values differently. At the schema
  50578. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  50579. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  50580. */
  50581. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  50582. BtShared *pBt = p->pBt;
  50583. sqlite3BtreeEnter(p);
  50584. assert( p->inTrans>TRANS_NONE );
  50585. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  50586. assert( pBt->pPage1 );
  50587. assert( idx>=0 && idx<=15 );
  50588. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  50589. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  50590. ** database, mark the database as read-only. */
  50591. #ifdef SQLITE_OMIT_AUTOVACUUM
  50592. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
  50593. #endif
  50594. sqlite3BtreeLeave(p);
  50595. }
  50596. /*
  50597. ** Write meta-information back into the database. Meta[0] is
  50598. ** read-only and may not be written.
  50599. */
  50600. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  50601. BtShared *pBt = p->pBt;
  50602. unsigned char *pP1;
  50603. int rc;
  50604. assert( idx>=1 && idx<=15 );
  50605. sqlite3BtreeEnter(p);
  50606. assert( p->inTrans==TRANS_WRITE );
  50607. assert( pBt->pPage1!=0 );
  50608. pP1 = pBt->pPage1->aData;
  50609. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  50610. if( rc==SQLITE_OK ){
  50611. put4byte(&pP1[36 + idx*4], iMeta);
  50612. #ifndef SQLITE_OMIT_AUTOVACUUM
  50613. if( idx==BTREE_INCR_VACUUM ){
  50614. assert( pBt->autoVacuum || iMeta==0 );
  50615. assert( iMeta==0 || iMeta==1 );
  50616. pBt->incrVacuum = (u8)iMeta;
  50617. }
  50618. #endif
  50619. }
  50620. sqlite3BtreeLeave(p);
  50621. return rc;
  50622. }
  50623. #ifndef SQLITE_OMIT_BTREECOUNT
  50624. /*
  50625. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  50626. ** number of entries in the b-tree and write the result to *pnEntry.
  50627. **
  50628. ** SQLITE_OK is returned if the operation is successfully executed.
  50629. ** Otherwise, if an error is encountered (i.e. an IO error or database
  50630. ** corruption) an SQLite error code is returned.
  50631. */
  50632. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  50633. i64 nEntry = 0; /* Value to return in *pnEntry */
  50634. int rc; /* Return code */
  50635. rc = moveToRoot(pCur);
  50636. /* Unless an error occurs, the following loop runs one iteration for each
  50637. ** page in the B-Tree structure (not including overflow pages).
  50638. */
  50639. while( rc==SQLITE_OK ){
  50640. int iIdx; /* Index of child node in parent */
  50641. MemPage *pPage; /* Current page of the b-tree */
  50642. /* If this is a leaf page or the tree is not an int-key tree, then
  50643. ** this page contains countable entries. Increment the entry counter
  50644. ** accordingly.
  50645. */
  50646. pPage = pCur->apPage[pCur->iPage];
  50647. if( pPage->leaf || !pPage->intKey ){
  50648. nEntry += pPage->nCell;
  50649. }
  50650. /* pPage is a leaf node. This loop navigates the cursor so that it
  50651. ** points to the first interior cell that it points to the parent of
  50652. ** the next page in the tree that has not yet been visited. The
  50653. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  50654. ** of the page, or to the number of cells in the page if the next page
  50655. ** to visit is the right-child of its parent.
  50656. **
  50657. ** If all pages in the tree have been visited, return SQLITE_OK to the
  50658. ** caller.
  50659. */
  50660. if( pPage->leaf ){
  50661. do {
  50662. if( pCur->iPage==0 ){
  50663. /* All pages of the b-tree have been visited. Return successfully. */
  50664. *pnEntry = nEntry;
  50665. return SQLITE_OK;
  50666. }
  50667. moveToParent(pCur);
  50668. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  50669. pCur->aiIdx[pCur->iPage]++;
  50670. pPage = pCur->apPage[pCur->iPage];
  50671. }
  50672. /* Descend to the child node of the cell that the cursor currently
  50673. ** points at. This is the right-child if (iIdx==pPage->nCell).
  50674. */
  50675. iIdx = pCur->aiIdx[pCur->iPage];
  50676. if( iIdx==pPage->nCell ){
  50677. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  50678. }else{
  50679. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  50680. }
  50681. }
  50682. /* An error has occurred. Return an error code. */
  50683. return rc;
  50684. }
  50685. #endif
  50686. /*
  50687. ** Return the pager associated with a BTree. This routine is used for
  50688. ** testing and debugging only.
  50689. */
  50690. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  50691. return p->pBt->pPager;
  50692. }
  50693. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  50694. /*
  50695. ** Append a message to the error message string.
  50696. */
  50697. static void checkAppendMsg(
  50698. IntegrityCk *pCheck,
  50699. char *zMsg1,
  50700. const char *zFormat,
  50701. ...
  50702. ){
  50703. va_list ap;
  50704. if( !pCheck->mxErr ) return;
  50705. pCheck->mxErr--;
  50706. pCheck->nErr++;
  50707. va_start(ap, zFormat);
  50708. if( pCheck->errMsg.nChar ){
  50709. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  50710. }
  50711. if( zMsg1 ){
  50712. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  50713. }
  50714. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  50715. va_end(ap);
  50716. if( pCheck->errMsg.mallocFailed ){
  50717. pCheck->mallocFailed = 1;
  50718. }
  50719. }
  50720. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  50721. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  50722. /*
  50723. ** Add 1 to the reference count for page iPage. If this is the second
  50724. ** reference to the page, add an error message to pCheck->zErrMsg.
  50725. ** Return 1 if there are 2 ore more references to the page and 0 if
  50726. ** if this is the first reference to the page.
  50727. **
  50728. ** Also check that the page number is in bounds.
  50729. */
  50730. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  50731. if( iPage==0 ) return 1;
  50732. if( iPage>pCheck->nPage ){
  50733. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  50734. return 1;
  50735. }
  50736. if( pCheck->anRef[iPage]==1 ){
  50737. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  50738. return 1;
  50739. }
  50740. return (pCheck->anRef[iPage]++)>1;
  50741. }
  50742. #ifndef SQLITE_OMIT_AUTOVACUUM
  50743. /*
  50744. ** Check that the entry in the pointer-map for page iChild maps to
  50745. ** page iParent, pointer type ptrType. If not, append an error message
  50746. ** to pCheck.
  50747. */
  50748. static void checkPtrmap(
  50749. IntegrityCk *pCheck, /* Integrity check context */
  50750. Pgno iChild, /* Child page number */
  50751. u8 eType, /* Expected pointer map type */
  50752. Pgno iParent, /* Expected pointer map parent page number */
  50753. char *zContext /* Context description (used for error msg) */
  50754. ){
  50755. int rc;
  50756. u8 ePtrmapType;
  50757. Pgno iPtrmapParent;
  50758. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  50759. if( rc!=SQLITE_OK ){
  50760. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  50761. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  50762. return;
  50763. }
  50764. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  50765. checkAppendMsg(pCheck, zContext,
  50766. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  50767. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  50768. }
  50769. }
  50770. #endif
  50771. /*
  50772. ** Check the integrity of the freelist or of an overflow page list.
  50773. ** Verify that the number of pages on the list is N.
  50774. */
  50775. static void checkList(
  50776. IntegrityCk *pCheck, /* Integrity checking context */
  50777. int isFreeList, /* True for a freelist. False for overflow page list */
  50778. int iPage, /* Page number for first page in the list */
  50779. int N, /* Expected number of pages in the list */
  50780. char *zContext /* Context for error messages */
  50781. ){
  50782. int i;
  50783. int expected = N;
  50784. int iFirst = iPage;
  50785. while( N-- > 0 && pCheck->mxErr ){
  50786. DbPage *pOvflPage;
  50787. unsigned char *pOvflData;
  50788. if( iPage<1 ){
  50789. checkAppendMsg(pCheck, zContext,
  50790. "%d of %d pages missing from overflow list starting at %d",
  50791. N+1, expected, iFirst);
  50792. break;
  50793. }
  50794. if( checkRef(pCheck, iPage, zContext) ) break;
  50795. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  50796. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  50797. break;
  50798. }
  50799. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  50800. if( isFreeList ){
  50801. int n = get4byte(&pOvflData[4]);
  50802. #ifndef SQLITE_OMIT_AUTOVACUUM
  50803. if( pCheck->pBt->autoVacuum ){
  50804. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  50805. }
  50806. #endif
  50807. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  50808. checkAppendMsg(pCheck, zContext,
  50809. "freelist leaf count too big on page %d", iPage);
  50810. N--;
  50811. }else{
  50812. for(i=0; i<n; i++){
  50813. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  50814. #ifndef SQLITE_OMIT_AUTOVACUUM
  50815. if( pCheck->pBt->autoVacuum ){
  50816. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  50817. }
  50818. #endif
  50819. checkRef(pCheck, iFreePage, zContext);
  50820. }
  50821. N -= n;
  50822. }
  50823. }
  50824. #ifndef SQLITE_OMIT_AUTOVACUUM
  50825. else{
  50826. /* If this database supports auto-vacuum and iPage is not the last
  50827. ** page in this overflow list, check that the pointer-map entry for
  50828. ** the following page matches iPage.
  50829. */
  50830. if( pCheck->pBt->autoVacuum && N>0 ){
  50831. i = get4byte(pOvflData);
  50832. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  50833. }
  50834. }
  50835. #endif
  50836. iPage = get4byte(pOvflData);
  50837. sqlite3PagerUnref(pOvflPage);
  50838. }
  50839. }
  50840. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  50841. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  50842. /*
  50843. ** Do various sanity checks on a single page of a tree. Return
  50844. ** the tree depth. Root pages return 0. Parents of root pages
  50845. ** return 1, and so forth.
  50846. **
  50847. ** These checks are done:
  50848. **
  50849. ** 1. Make sure that cells and freeblocks do not overlap
  50850. ** but combine to completely cover the page.
  50851. ** NO 2. Make sure cell keys are in order.
  50852. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  50853. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  50854. ** 5. Check the integrity of overflow pages.
  50855. ** 6. Recursively call checkTreePage on all children.
  50856. ** 7. Verify that the depth of all children is the same.
  50857. ** 8. Make sure this page is at least 33% full or else it is
  50858. ** the root of the tree.
  50859. */
  50860. static int checkTreePage(
  50861. IntegrityCk *pCheck, /* Context for the sanity check */
  50862. int iPage, /* Page number of the page to check */
  50863. char *zParentContext, /* Parent context */
  50864. i64 *pnParentMinKey,
  50865. i64 *pnParentMaxKey
  50866. ){
  50867. MemPage *pPage;
  50868. int i, rc, depth, d2, pgno, cnt;
  50869. int hdr, cellStart;
  50870. int nCell;
  50871. u8 *data;
  50872. BtShared *pBt;
  50873. int usableSize;
  50874. char zContext[100];
  50875. char *hit = 0;
  50876. i64 nMinKey = 0;
  50877. i64 nMaxKey = 0;
  50878. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  50879. /* Check that the page exists
  50880. */
  50881. pBt = pCheck->pBt;
  50882. usableSize = pBt->usableSize;
  50883. if( iPage==0 ) return 0;
  50884. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  50885. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  50886. checkAppendMsg(pCheck, zContext,
  50887. "unable to get the page. error code=%d", rc);
  50888. return 0;
  50889. }
  50890. /* Clear MemPage.isInit to make sure the corruption detection code in
  50891. ** btreeInitPage() is executed. */
  50892. pPage->isInit = 0;
  50893. if( (rc = btreeInitPage(pPage))!=0 ){
  50894. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  50895. checkAppendMsg(pCheck, zContext,
  50896. "btreeInitPage() returns error code %d", rc);
  50897. releasePage(pPage);
  50898. return 0;
  50899. }
  50900. /* Check out all the cells.
  50901. */
  50902. depth = 0;
  50903. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  50904. u8 *pCell;
  50905. u32 sz;
  50906. CellInfo info;
  50907. /* Check payload overflow pages
  50908. */
  50909. sqlite3_snprintf(sizeof(zContext), zContext,
  50910. "On tree page %d cell %d: ", iPage, i);
  50911. pCell = findCell(pPage,i);
  50912. btreeParseCellPtr(pPage, pCell, &info);
  50913. sz = info.nData;
  50914. if( !pPage->intKey ) sz += (int)info.nKey;
  50915. /* For intKey pages, check that the keys are in order.
  50916. */
  50917. else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  50918. else{
  50919. if( info.nKey <= nMaxKey ){
  50920. checkAppendMsg(pCheck, zContext,
  50921. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  50922. }
  50923. nMaxKey = info.nKey;
  50924. }
  50925. assert( sz==info.nPayload );
  50926. if( (sz>info.nLocal)
  50927. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  50928. ){
  50929. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  50930. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  50931. #ifndef SQLITE_OMIT_AUTOVACUUM
  50932. if( pBt->autoVacuum ){
  50933. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  50934. }
  50935. #endif
  50936. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  50937. }
  50938. /* Check sanity of left child page.
  50939. */
  50940. if( !pPage->leaf ){
  50941. pgno = get4byte(pCell);
  50942. #ifndef SQLITE_OMIT_AUTOVACUUM
  50943. if( pBt->autoVacuum ){
  50944. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  50945. }
  50946. #endif
  50947. d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
  50948. if( i>0 && d2!=depth ){
  50949. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  50950. }
  50951. depth = d2;
  50952. }
  50953. }
  50954. if( !pPage->leaf ){
  50955. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  50956. sqlite3_snprintf(sizeof(zContext), zContext,
  50957. "On page %d at right child: ", iPage);
  50958. #ifndef SQLITE_OMIT_AUTOVACUUM
  50959. if( pBt->autoVacuum ){
  50960. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  50961. }
  50962. #endif
  50963. checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
  50964. }
  50965. /* For intKey leaf pages, check that the min/max keys are in order
  50966. ** with any left/parent/right pages.
  50967. */
  50968. if( pPage->leaf && pPage->intKey ){
  50969. /* if we are a left child page */
  50970. if( pnParentMinKey ){
  50971. /* if we are the left most child page */
  50972. if( !pnParentMaxKey ){
  50973. if( nMaxKey > *pnParentMinKey ){
  50974. checkAppendMsg(pCheck, zContext,
  50975. "Rowid %lld out of order (max larger than parent min of %lld)",
  50976. nMaxKey, *pnParentMinKey);
  50977. }
  50978. }else{
  50979. if( nMinKey <= *pnParentMinKey ){
  50980. checkAppendMsg(pCheck, zContext,
  50981. "Rowid %lld out of order (min less than parent min of %lld)",
  50982. nMinKey, *pnParentMinKey);
  50983. }
  50984. if( nMaxKey > *pnParentMaxKey ){
  50985. checkAppendMsg(pCheck, zContext,
  50986. "Rowid %lld out of order (max larger than parent max of %lld)",
  50987. nMaxKey, *pnParentMaxKey);
  50988. }
  50989. *pnParentMinKey = nMaxKey;
  50990. }
  50991. /* else if we're a right child page */
  50992. } else if( pnParentMaxKey ){
  50993. if( nMinKey <= *pnParentMaxKey ){
  50994. checkAppendMsg(pCheck, zContext,
  50995. "Rowid %lld out of order (min less than parent max of %lld)",
  50996. nMinKey, *pnParentMaxKey);
  50997. }
  50998. }
  50999. }
  51000. /* Check for complete coverage of the page
  51001. */
  51002. data = pPage->aData;
  51003. hdr = pPage->hdrOffset;
  51004. hit = sqlite3PageMalloc( pBt->pageSize );
  51005. if( hit==0 ){
  51006. pCheck->mallocFailed = 1;
  51007. }else{
  51008. int contentOffset = get2byteNotZero(&data[hdr+5]);
  51009. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  51010. memset(hit+contentOffset, 0, usableSize-contentOffset);
  51011. memset(hit, 1, contentOffset);
  51012. nCell = get2byte(&data[hdr+3]);
  51013. cellStart = hdr + 12 - 4*pPage->leaf;
  51014. for(i=0; i<nCell; i++){
  51015. int pc = get2byte(&data[cellStart+i*2]);
  51016. u32 size = 65536;
  51017. int j;
  51018. if( pc<=usableSize-4 ){
  51019. size = cellSizePtr(pPage, &data[pc]);
  51020. }
  51021. if( (int)(pc+size-1)>=usableSize ){
  51022. checkAppendMsg(pCheck, 0,
  51023. "Corruption detected in cell %d on page %d",i,iPage);
  51024. }else{
  51025. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  51026. }
  51027. }
  51028. i = get2byte(&data[hdr+1]);
  51029. while( i>0 ){
  51030. int size, j;
  51031. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  51032. size = get2byte(&data[i+2]);
  51033. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  51034. for(j=i+size-1; j>=i; j--) hit[j]++;
  51035. j = get2byte(&data[i]);
  51036. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  51037. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  51038. i = j;
  51039. }
  51040. for(i=cnt=0; i<usableSize; i++){
  51041. if( hit[i]==0 ){
  51042. cnt++;
  51043. }else if( hit[i]>1 ){
  51044. checkAppendMsg(pCheck, 0,
  51045. "Multiple uses for byte %d of page %d", i, iPage);
  51046. break;
  51047. }
  51048. }
  51049. if( cnt!=data[hdr+7] ){
  51050. checkAppendMsg(pCheck, 0,
  51051. "Fragmentation of %d bytes reported as %d on page %d",
  51052. cnt, data[hdr+7], iPage);
  51053. }
  51054. }
  51055. sqlite3PageFree(hit);
  51056. releasePage(pPage);
  51057. return depth+1;
  51058. }
  51059. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  51060. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  51061. /*
  51062. ** This routine does a complete check of the given BTree file. aRoot[] is
  51063. ** an array of pages numbers were each page number is the root page of
  51064. ** a table. nRoot is the number of entries in aRoot.
  51065. **
  51066. ** A read-only or read-write transaction must be opened before calling
  51067. ** this function.
  51068. **
  51069. ** Write the number of error seen in *pnErr. Except for some memory
  51070. ** allocation errors, an error message held in memory obtained from
  51071. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  51072. ** returned. If a memory allocation error occurs, NULL is returned.
  51073. */
  51074. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  51075. Btree *p, /* The btree to be checked */
  51076. int *aRoot, /* An array of root pages numbers for individual trees */
  51077. int nRoot, /* Number of entries in aRoot[] */
  51078. int mxErr, /* Stop reporting errors after this many */
  51079. int *pnErr /* Write number of errors seen to this variable */
  51080. ){
  51081. Pgno i;
  51082. int nRef;
  51083. IntegrityCk sCheck;
  51084. BtShared *pBt = p->pBt;
  51085. char zErr[100];
  51086. sqlite3BtreeEnter(p);
  51087. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  51088. nRef = sqlite3PagerRefcount(pBt->pPager);
  51089. sCheck.pBt = pBt;
  51090. sCheck.pPager = pBt->pPager;
  51091. sCheck.nPage = btreePagecount(sCheck.pBt);
  51092. sCheck.mxErr = mxErr;
  51093. sCheck.nErr = 0;
  51094. sCheck.mallocFailed = 0;
  51095. *pnErr = 0;
  51096. if( sCheck.nPage==0 ){
  51097. sqlite3BtreeLeave(p);
  51098. return 0;
  51099. }
  51100. sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
  51101. if( !sCheck.anRef ){
  51102. *pnErr = 1;
  51103. sqlite3BtreeLeave(p);
  51104. return 0;
  51105. }
  51106. for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
  51107. i = PENDING_BYTE_PAGE(pBt);
  51108. if( i<=sCheck.nPage ){
  51109. sCheck.anRef[i] = 1;
  51110. }
  51111. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
  51112. sCheck.errMsg.useMalloc = 2;
  51113. /* Check the integrity of the freelist
  51114. */
  51115. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  51116. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  51117. /* Check all the tables.
  51118. */
  51119. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  51120. if( aRoot[i]==0 ) continue;
  51121. #ifndef SQLITE_OMIT_AUTOVACUUM
  51122. if( pBt->autoVacuum && aRoot[i]>1 ){
  51123. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  51124. }
  51125. #endif
  51126. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
  51127. }
  51128. /* Make sure every page in the file is referenced
  51129. */
  51130. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  51131. #ifdef SQLITE_OMIT_AUTOVACUUM
  51132. if( sCheck.anRef[i]==0 ){
  51133. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  51134. }
  51135. #else
  51136. /* If the database supports auto-vacuum, make sure no tables contain
  51137. ** references to pointer-map pages.
  51138. */
  51139. if( sCheck.anRef[i]==0 &&
  51140. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  51141. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  51142. }
  51143. if( sCheck.anRef[i]!=0 &&
  51144. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  51145. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  51146. }
  51147. #endif
  51148. }
  51149. /* Make sure this analysis did not leave any unref() pages.
  51150. ** This is an internal consistency check; an integrity check
  51151. ** of the integrity check.
  51152. */
  51153. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  51154. checkAppendMsg(&sCheck, 0,
  51155. "Outstanding page count goes from %d to %d during this analysis",
  51156. nRef, sqlite3PagerRefcount(pBt->pPager)
  51157. );
  51158. }
  51159. /* Clean up and report errors.
  51160. */
  51161. sqlite3BtreeLeave(p);
  51162. sqlite3_free(sCheck.anRef);
  51163. if( sCheck.mallocFailed ){
  51164. sqlite3StrAccumReset(&sCheck.errMsg);
  51165. *pnErr = sCheck.nErr+1;
  51166. return 0;
  51167. }
  51168. *pnErr = sCheck.nErr;
  51169. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  51170. return sqlite3StrAccumFinish(&sCheck.errMsg);
  51171. }
  51172. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  51173. /*
  51174. ** Return the full pathname of the underlying database file.
  51175. **
  51176. ** The pager filename is invariant as long as the pager is
  51177. ** open so it is safe to access without the BtShared mutex.
  51178. */
  51179. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  51180. assert( p->pBt->pPager!=0 );
  51181. return sqlite3PagerFilename(p->pBt->pPager);
  51182. }
  51183. /*
  51184. ** Return the pathname of the journal file for this database. The return
  51185. ** value of this routine is the same regardless of whether the journal file
  51186. ** has been created or not.
  51187. **
  51188. ** The pager journal filename is invariant as long as the pager is
  51189. ** open so it is safe to access without the BtShared mutex.
  51190. */
  51191. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  51192. assert( p->pBt->pPager!=0 );
  51193. return sqlite3PagerJournalname(p->pBt->pPager);
  51194. }
  51195. /*
  51196. ** Return non-zero if a transaction is active.
  51197. */
  51198. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  51199. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  51200. return (p && (p->inTrans==TRANS_WRITE));
  51201. }
  51202. #ifndef SQLITE_OMIT_WAL
  51203. /*
  51204. ** Run a checkpoint on the Btree passed as the first argument.
  51205. **
  51206. ** Return SQLITE_LOCKED if this or any other connection has an open
  51207. ** transaction on the shared-cache the argument Btree is connected to.
  51208. **
  51209. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  51210. */
  51211. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  51212. int rc = SQLITE_OK;
  51213. if( p ){
  51214. BtShared *pBt = p->pBt;
  51215. sqlite3BtreeEnter(p);
  51216. if( pBt->inTransaction!=TRANS_NONE ){
  51217. rc = SQLITE_LOCKED;
  51218. }else{
  51219. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  51220. }
  51221. sqlite3BtreeLeave(p);
  51222. }
  51223. return rc;
  51224. }
  51225. #endif
  51226. /*
  51227. ** Return non-zero if a read (or write) transaction is active.
  51228. */
  51229. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  51230. assert( p );
  51231. assert( sqlite3_mutex_held(p->db->mutex) );
  51232. return p->inTrans!=TRANS_NONE;
  51233. }
  51234. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  51235. assert( p );
  51236. assert( sqlite3_mutex_held(p->db->mutex) );
  51237. return p->nBackup!=0;
  51238. }
  51239. /*
  51240. ** This function returns a pointer to a blob of memory associated with
  51241. ** a single shared-btree. The memory is used by client code for its own
  51242. ** purposes (for example, to store a high-level schema associated with
  51243. ** the shared-btree). The btree layer manages reference counting issues.
  51244. **
  51245. ** The first time this is called on a shared-btree, nBytes bytes of memory
  51246. ** are allocated, zeroed, and returned to the caller. For each subsequent
  51247. ** call the nBytes parameter is ignored and a pointer to the same blob
  51248. ** of memory returned.
  51249. **
  51250. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  51251. ** allocated, a null pointer is returned. If the blob has already been
  51252. ** allocated, it is returned as normal.
  51253. **
  51254. ** Just before the shared-btree is closed, the function passed as the
  51255. ** xFree argument when the memory allocation was made is invoked on the
  51256. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  51257. ** on the memory, the btree layer does that.
  51258. */
  51259. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  51260. BtShared *pBt = p->pBt;
  51261. sqlite3BtreeEnter(p);
  51262. if( !pBt->pSchema && nBytes ){
  51263. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  51264. pBt->xFreeSchema = xFree;
  51265. }
  51266. sqlite3BtreeLeave(p);
  51267. return pBt->pSchema;
  51268. }
  51269. /*
  51270. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  51271. ** btree as the argument handle holds an exclusive lock on the
  51272. ** sqlite_master table. Otherwise SQLITE_OK.
  51273. */
  51274. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  51275. int rc;
  51276. assert( sqlite3_mutex_held(p->db->mutex) );
  51277. sqlite3BtreeEnter(p);
  51278. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  51279. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  51280. sqlite3BtreeLeave(p);
  51281. return rc;
  51282. }
  51283. #ifndef SQLITE_OMIT_SHARED_CACHE
  51284. /*
  51285. ** Obtain a lock on the table whose root page is iTab. The
  51286. ** lock is a write lock if isWritelock is true or a read lock
  51287. ** if it is false.
  51288. */
  51289. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  51290. int rc = SQLITE_OK;
  51291. assert( p->inTrans!=TRANS_NONE );
  51292. if( p->sharable ){
  51293. u8 lockType = READ_LOCK + isWriteLock;
  51294. assert( READ_LOCK+1==WRITE_LOCK );
  51295. assert( isWriteLock==0 || isWriteLock==1 );
  51296. sqlite3BtreeEnter(p);
  51297. rc = querySharedCacheTableLock(p, iTab, lockType);
  51298. if( rc==SQLITE_OK ){
  51299. rc = setSharedCacheTableLock(p, iTab, lockType);
  51300. }
  51301. sqlite3BtreeLeave(p);
  51302. }
  51303. return rc;
  51304. }
  51305. #endif
  51306. #ifndef SQLITE_OMIT_INCRBLOB
  51307. /*
  51308. ** Argument pCsr must be a cursor opened for writing on an
  51309. ** INTKEY table currently pointing at a valid table entry.
  51310. ** This function modifies the data stored as part of that entry.
  51311. **
  51312. ** Only the data content may only be modified, it is not possible to
  51313. ** change the length of the data stored. If this function is called with
  51314. ** parameters that attempt to write past the end of the existing data,
  51315. ** no modifications are made and SQLITE_CORRUPT is returned.
  51316. */
  51317. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  51318. int rc;
  51319. assert( cursorHoldsMutex(pCsr) );
  51320. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  51321. assert( pCsr->isIncrblobHandle );
  51322. rc = restoreCursorPosition(pCsr);
  51323. if( rc!=SQLITE_OK ){
  51324. return rc;
  51325. }
  51326. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  51327. if( pCsr->eState!=CURSOR_VALID ){
  51328. return SQLITE_ABORT;
  51329. }
  51330. /* Check some assumptions:
  51331. ** (a) the cursor is open for writing,
  51332. ** (b) there is a read/write transaction open,
  51333. ** (c) the connection holds a write-lock on the table (if required),
  51334. ** (d) there are no conflicting read-locks, and
  51335. ** (e) the cursor points at a valid row of an intKey table.
  51336. */
  51337. if( !pCsr->wrFlag ){
  51338. return SQLITE_READONLY;
  51339. }
  51340. assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
  51341. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  51342. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  51343. assert( pCsr->apPage[pCsr->iPage]->intKey );
  51344. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  51345. }
  51346. /*
  51347. ** Set a flag on this cursor to cache the locations of pages from the
  51348. ** overflow list for the current row. This is used by cursors opened
  51349. ** for incremental blob IO only.
  51350. **
  51351. ** This function sets a flag only. The actual page location cache
  51352. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  51353. ** accessPayload() (the worker function for sqlite3BtreeData() and
  51354. ** sqlite3BtreePutData()).
  51355. */
  51356. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  51357. assert( cursorHoldsMutex(pCur) );
  51358. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  51359. invalidateOverflowCache(pCur);
  51360. pCur->isIncrblobHandle = 1;
  51361. }
  51362. #endif
  51363. /*
  51364. ** Set both the "read version" (single byte at byte offset 18) and
  51365. ** "write version" (single byte at byte offset 19) fields in the database
  51366. ** header to iVersion.
  51367. */
  51368. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  51369. BtShared *pBt = pBtree->pBt;
  51370. int rc; /* Return code */
  51371. assert( pBtree->inTrans==TRANS_NONE );
  51372. assert( iVersion==1 || iVersion==2 );
  51373. /* If setting the version fields to 1, do not automatically open the
  51374. ** WAL connection, even if the version fields are currently set to 2.
  51375. */
  51376. pBt->doNotUseWAL = (u8)(iVersion==1);
  51377. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  51378. if( rc==SQLITE_OK ){
  51379. u8 *aData = pBt->pPage1->aData;
  51380. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  51381. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  51382. if( rc==SQLITE_OK ){
  51383. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  51384. if( rc==SQLITE_OK ){
  51385. aData[18] = (u8)iVersion;
  51386. aData[19] = (u8)iVersion;
  51387. }
  51388. }
  51389. }
  51390. }
  51391. pBt->doNotUseWAL = 0;
  51392. return rc;
  51393. }
  51394. /************** End of btree.c ***********************************************/
  51395. /************** Begin file backup.c ******************************************/
  51396. /*
  51397. ** 2009 January 28
  51398. **
  51399. ** The author disclaims copyright to this source code. In place of
  51400. ** a legal notice, here is a blessing:
  51401. **
  51402. ** May you do good and not evil.
  51403. ** May you find forgiveness for yourself and forgive others.
  51404. ** May you share freely, never taking more than you give.
  51405. **
  51406. *************************************************************************
  51407. ** This file contains the implementation of the sqlite3_backup_XXX()
  51408. ** API functions and the related features.
  51409. */
  51410. /* Macro to find the minimum of two numeric values.
  51411. */
  51412. #ifndef MIN
  51413. # define MIN(x,y) ((x)<(y)?(x):(y))
  51414. #endif
  51415. /*
  51416. ** Structure allocated for each backup operation.
  51417. */
  51418. struct sqlite3_backup {
  51419. sqlite3* pDestDb; /* Destination database handle */
  51420. Btree *pDest; /* Destination b-tree file */
  51421. u32 iDestSchema; /* Original schema cookie in destination */
  51422. int bDestLocked; /* True once a write-transaction is open on pDest */
  51423. Pgno iNext; /* Page number of the next source page to copy */
  51424. sqlite3* pSrcDb; /* Source database handle */
  51425. Btree *pSrc; /* Source b-tree file */
  51426. int rc; /* Backup process error code */
  51427. /* These two variables are set by every call to backup_step(). They are
  51428. ** read by calls to backup_remaining() and backup_pagecount().
  51429. */
  51430. Pgno nRemaining; /* Number of pages left to copy */
  51431. Pgno nPagecount; /* Total number of pages to copy */
  51432. int isAttached; /* True once backup has been registered with pager */
  51433. sqlite3_backup *pNext; /* Next backup associated with source pager */
  51434. };
  51435. /*
  51436. ** THREAD SAFETY NOTES:
  51437. **
  51438. ** Once it has been created using backup_init(), a single sqlite3_backup
  51439. ** structure may be accessed via two groups of thread-safe entry points:
  51440. **
  51441. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  51442. ** backup_finish(). Both these functions obtain the source database
  51443. ** handle mutex and the mutex associated with the source BtShared
  51444. ** structure, in that order.
  51445. **
  51446. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  51447. ** invoked by the pager layer to report various state changes in
  51448. ** the page cache associated with the source database. The mutex
  51449. ** associated with the source database BtShared structure will always
  51450. ** be held when either of these functions are invoked.
  51451. **
  51452. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  51453. ** backup_pagecount() are not thread-safe functions. If they are called
  51454. ** while some other thread is calling backup_step() or backup_finish(),
  51455. ** the values returned may be invalid. There is no way for a call to
  51456. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  51457. ** or backup_pagecount().
  51458. **
  51459. ** Depending on the SQLite configuration, the database handles and/or
  51460. ** the Btree objects may have their own mutexes that require locking.
  51461. ** Non-sharable Btrees (in-memory databases for example), do not have
  51462. ** associated mutexes.
  51463. */
  51464. /*
  51465. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  51466. ** in connection handle pDb. If such a database cannot be found, return
  51467. ** a NULL pointer and write an error message to pErrorDb.
  51468. **
  51469. ** If the "temp" database is requested, it may need to be opened by this
  51470. ** function. If an error occurs while doing so, return 0 and write an
  51471. ** error message to pErrorDb.
  51472. */
  51473. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  51474. int i = sqlite3FindDbName(pDb, zDb);
  51475. if( i==1 ){
  51476. Parse *pParse;
  51477. int rc = 0;
  51478. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  51479. if( pParse==0 ){
  51480. sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
  51481. rc = SQLITE_NOMEM;
  51482. }else{
  51483. pParse->db = pDb;
  51484. if( sqlite3OpenTempDatabase(pParse) ){
  51485. sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  51486. rc = SQLITE_ERROR;
  51487. }
  51488. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  51489. sqlite3StackFree(pErrorDb, pParse);
  51490. }
  51491. if( rc ){
  51492. return 0;
  51493. }
  51494. }
  51495. if( i<0 ){
  51496. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  51497. return 0;
  51498. }
  51499. return pDb->aDb[i].pBt;
  51500. }
  51501. /*
  51502. ** Attempt to set the page size of the destination to match the page size
  51503. ** of the source.
  51504. */
  51505. static int setDestPgsz(sqlite3_backup *p){
  51506. int rc;
  51507. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  51508. return rc;
  51509. }
  51510. /*
  51511. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  51512. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  51513. ** a pointer to the new sqlite3_backup object.
  51514. **
  51515. ** If an error occurs, NULL is returned and an error code and error message
  51516. ** stored in database handle pDestDb.
  51517. */
  51518. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  51519. sqlite3* pDestDb, /* Database to write to */
  51520. const char *zDestDb, /* Name of database within pDestDb */
  51521. sqlite3* pSrcDb, /* Database connection to read from */
  51522. const char *zSrcDb /* Name of database within pSrcDb */
  51523. ){
  51524. sqlite3_backup *p; /* Value to return */
  51525. /* Lock the source database handle. The destination database
  51526. ** handle is not locked in this routine, but it is locked in
  51527. ** sqlite3_backup_step(). The user is required to ensure that no
  51528. ** other thread accesses the destination handle for the duration
  51529. ** of the backup operation. Any attempt to use the destination
  51530. ** database connection while a backup is in progress may cause
  51531. ** a malfunction or a deadlock.
  51532. */
  51533. sqlite3_mutex_enter(pSrcDb->mutex);
  51534. sqlite3_mutex_enter(pDestDb->mutex);
  51535. if( pSrcDb==pDestDb ){
  51536. sqlite3Error(
  51537. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  51538. );
  51539. p = 0;
  51540. }else {
  51541. /* Allocate space for a new sqlite3_backup object...
  51542. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  51543. ** call to sqlite3_backup_init() and is destroyed by a call to
  51544. ** sqlite3_backup_finish(). */
  51545. p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
  51546. if( !p ){
  51547. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  51548. }
  51549. }
  51550. /* If the allocation succeeded, populate the new object. */
  51551. if( p ){
  51552. memset(p, 0, sizeof(sqlite3_backup));
  51553. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  51554. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  51555. p->pDestDb = pDestDb;
  51556. p->pSrcDb = pSrcDb;
  51557. p->iNext = 1;
  51558. p->isAttached = 0;
  51559. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  51560. /* One (or both) of the named databases did not exist or an OOM
  51561. ** error was hit. The error has already been written into the
  51562. ** pDestDb handle. All that is left to do here is free the
  51563. ** sqlite3_backup structure.
  51564. */
  51565. sqlite3_free(p);
  51566. p = 0;
  51567. }
  51568. }
  51569. if( p ){
  51570. p->pSrc->nBackup++;
  51571. }
  51572. sqlite3_mutex_leave(pDestDb->mutex);
  51573. sqlite3_mutex_leave(pSrcDb->mutex);
  51574. return p;
  51575. }
  51576. /*
  51577. ** Argument rc is an SQLite error code. Return true if this error is
  51578. ** considered fatal if encountered during a backup operation. All errors
  51579. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  51580. */
  51581. static int isFatalError(int rc){
  51582. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  51583. }
  51584. /*
  51585. ** Parameter zSrcData points to a buffer containing the data for
  51586. ** page iSrcPg from the source database. Copy this data into the
  51587. ** destination database.
  51588. */
  51589. static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
  51590. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  51591. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  51592. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  51593. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  51594. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  51595. #ifdef SQLITE_HAS_CODEC
  51596. int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
  51597. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  51598. #endif
  51599. int rc = SQLITE_OK;
  51600. i64 iOff;
  51601. assert( p->bDestLocked );
  51602. assert( !isFatalError(p->rc) );
  51603. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  51604. assert( zSrcData );
  51605. /* Catch the case where the destination is an in-memory database and the
  51606. ** page sizes of the source and destination differ.
  51607. */
  51608. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  51609. rc = SQLITE_READONLY;
  51610. }
  51611. #ifdef SQLITE_HAS_CODEC
  51612. /* Backup is not possible if the page size of the destination is changing
  51613. ** and a codec is in use.
  51614. */
  51615. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  51616. rc = SQLITE_READONLY;
  51617. }
  51618. /* Backup is not possible if the number of bytes of reserve space differ
  51619. ** between source and destination. If there is a difference, try to
  51620. ** fix the destination to agree with the source. If that is not possible,
  51621. ** then the backup cannot proceed.
  51622. */
  51623. if( nSrcReserve!=nDestReserve ){
  51624. u32 newPgsz = nSrcPgsz;
  51625. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  51626. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  51627. }
  51628. #endif
  51629. /* This loop runs once for each destination page spanned by the source
  51630. ** page. For each iteration, variable iOff is set to the byte offset
  51631. ** of the destination page.
  51632. */
  51633. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  51634. DbPage *pDestPg = 0;
  51635. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  51636. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  51637. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  51638. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  51639. ){
  51640. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  51641. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  51642. u8 *zOut = &zDestData[iOff%nDestPgsz];
  51643. /* Copy the data from the source page into the destination page.
  51644. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  51645. ** and the pager code use this trick (clearing the first byte
  51646. ** of the page 'extra' space to invalidate the Btree layers
  51647. ** cached parse of the page). MemPage.isInit is marked
  51648. ** "MUST BE FIRST" for this purpose.
  51649. */
  51650. memcpy(zOut, zIn, nCopy);
  51651. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  51652. }
  51653. sqlite3PagerUnref(pDestPg);
  51654. }
  51655. return rc;
  51656. }
  51657. /*
  51658. ** If pFile is currently larger than iSize bytes, then truncate it to
  51659. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  51660. ** this function is a no-op.
  51661. **
  51662. ** Return SQLITE_OK if everything is successful, or an SQLite error
  51663. ** code if an error occurs.
  51664. */
  51665. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  51666. i64 iCurrent;
  51667. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  51668. if( rc==SQLITE_OK && iCurrent>iSize ){
  51669. rc = sqlite3OsTruncate(pFile, iSize);
  51670. }
  51671. return rc;
  51672. }
  51673. /*
  51674. ** Register this backup object with the associated source pager for
  51675. ** callbacks when pages are changed or the cache invalidated.
  51676. */
  51677. static void attachBackupObject(sqlite3_backup *p){
  51678. sqlite3_backup **pp;
  51679. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  51680. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  51681. p->pNext = *pp;
  51682. *pp = p;
  51683. p->isAttached = 1;
  51684. }
  51685. /*
  51686. ** Copy nPage pages from the source b-tree to the destination.
  51687. */
  51688. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  51689. int rc;
  51690. int destMode; /* Destination journal mode */
  51691. int pgszSrc = 0; /* Source page size */
  51692. int pgszDest = 0; /* Destination page size */
  51693. sqlite3_mutex_enter(p->pSrcDb->mutex);
  51694. sqlite3BtreeEnter(p->pSrc);
  51695. if( p->pDestDb ){
  51696. sqlite3_mutex_enter(p->pDestDb->mutex);
  51697. }
  51698. rc = p->rc;
  51699. if( !isFatalError(rc) ){
  51700. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  51701. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  51702. int ii; /* Iterator variable */
  51703. int nSrcPage = -1; /* Size of source db in pages */
  51704. int bCloseTrans = 0; /* True if src db requires unlocking */
  51705. /* If the source pager is currently in a write-transaction, return
  51706. ** SQLITE_BUSY immediately.
  51707. */
  51708. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  51709. rc = SQLITE_BUSY;
  51710. }else{
  51711. rc = SQLITE_OK;
  51712. }
  51713. /* Lock the destination database, if it is not locked already. */
  51714. if( SQLITE_OK==rc && p->bDestLocked==0
  51715. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  51716. ){
  51717. p->bDestLocked = 1;
  51718. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  51719. }
  51720. /* If there is no open read-transaction on the source database, open
  51721. ** one now. If a transaction is opened here, then it will be closed
  51722. ** before this function exits.
  51723. */
  51724. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  51725. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  51726. bCloseTrans = 1;
  51727. }
  51728. /* Do not allow backup if the destination database is in WAL mode
  51729. ** and the page sizes are different between source and destination */
  51730. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  51731. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  51732. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  51733. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  51734. rc = SQLITE_READONLY;
  51735. }
  51736. /* Now that there is a read-lock on the source database, query the
  51737. ** source pager for the number of pages in the database.
  51738. */
  51739. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  51740. assert( nSrcPage>=0 );
  51741. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  51742. const Pgno iSrcPg = p->iNext; /* Source page number */
  51743. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  51744. DbPage *pSrcPg; /* Source page object */
  51745. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  51746. if( rc==SQLITE_OK ){
  51747. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
  51748. sqlite3PagerUnref(pSrcPg);
  51749. }
  51750. }
  51751. p->iNext++;
  51752. }
  51753. if( rc==SQLITE_OK ){
  51754. p->nPagecount = nSrcPage;
  51755. p->nRemaining = nSrcPage+1-p->iNext;
  51756. if( p->iNext>(Pgno)nSrcPage ){
  51757. rc = SQLITE_DONE;
  51758. }else if( !p->isAttached ){
  51759. attachBackupObject(p);
  51760. }
  51761. }
  51762. /* Update the schema version field in the destination database. This
  51763. ** is to make sure that the schema-version really does change in
  51764. ** the case where the source and destination databases have the
  51765. ** same schema version.
  51766. */
  51767. if( rc==SQLITE_DONE
  51768. && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
  51769. ){
  51770. int nDestTruncate;
  51771. if( p->pDestDb ){
  51772. sqlite3ResetInternalSchema(p->pDestDb, -1);
  51773. }
  51774. /* Set nDestTruncate to the final number of pages in the destination
  51775. ** database. The complication here is that the destination page
  51776. ** size may be different to the source page size.
  51777. **
  51778. ** If the source page size is smaller than the destination page size,
  51779. ** round up. In this case the call to sqlite3OsTruncate() below will
  51780. ** fix the size of the file. However it is important to call
  51781. ** sqlite3PagerTruncateImage() here so that any pages in the
  51782. ** destination file that lie beyond the nDestTruncate page mark are
  51783. ** journalled by PagerCommitPhaseOne() before they are destroyed
  51784. ** by the file truncation.
  51785. */
  51786. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  51787. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  51788. if( pgszSrc<pgszDest ){
  51789. int ratio = pgszDest/pgszSrc;
  51790. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  51791. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  51792. nDestTruncate--;
  51793. }
  51794. }else{
  51795. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  51796. }
  51797. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  51798. if( pgszSrc<pgszDest ){
  51799. /* If the source page-size is smaller than the destination page-size,
  51800. ** two extra things may need to happen:
  51801. **
  51802. ** * The destination may need to be truncated, and
  51803. **
  51804. ** * Data stored on the pages immediately following the
  51805. ** pending-byte page in the source database may need to be
  51806. ** copied into the destination database.
  51807. */
  51808. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  51809. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  51810. i64 iOff;
  51811. i64 iEnd;
  51812. assert( pFile );
  51813. assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  51814. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  51815. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  51816. ));
  51817. /* This call ensures that all data required to recreate the original
  51818. ** database has been stored in the journal for pDestPager and the
  51819. ** journal synced to disk. So at this point we may safely modify
  51820. ** the database file in any way, knowing that if a power failure
  51821. ** occurs, the original database will be reconstructed from the
  51822. ** journal file. */
  51823. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  51824. /* Write the extra pages and truncate the database file as required. */
  51825. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  51826. for(
  51827. iOff=PENDING_BYTE+pgszSrc;
  51828. rc==SQLITE_OK && iOff<iEnd;
  51829. iOff+=pgszSrc
  51830. ){
  51831. PgHdr *pSrcPg = 0;
  51832. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  51833. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  51834. if( rc==SQLITE_OK ){
  51835. u8 *zData = sqlite3PagerGetData(pSrcPg);
  51836. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  51837. }
  51838. sqlite3PagerUnref(pSrcPg);
  51839. }
  51840. if( rc==SQLITE_OK ){
  51841. rc = backupTruncateFile(pFile, iSize);
  51842. }
  51843. /* Sync the database file to disk. */
  51844. if( rc==SQLITE_OK ){
  51845. rc = sqlite3PagerSync(pDestPager);
  51846. }
  51847. }else{
  51848. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  51849. }
  51850. /* Finish committing the transaction to the destination database. */
  51851. if( SQLITE_OK==rc
  51852. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  51853. ){
  51854. rc = SQLITE_DONE;
  51855. }
  51856. }
  51857. /* If bCloseTrans is true, then this function opened a read transaction
  51858. ** on the source database. Close the read transaction here. There is
  51859. ** no need to check the return values of the btree methods here, as
  51860. ** "committing" a read-only transaction cannot fail.
  51861. */
  51862. if( bCloseTrans ){
  51863. TESTONLY( int rc2 );
  51864. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  51865. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  51866. assert( rc2==SQLITE_OK );
  51867. }
  51868. if( rc==SQLITE_IOERR_NOMEM ){
  51869. rc = SQLITE_NOMEM;
  51870. }
  51871. p->rc = rc;
  51872. }
  51873. if( p->pDestDb ){
  51874. sqlite3_mutex_leave(p->pDestDb->mutex);
  51875. }
  51876. sqlite3BtreeLeave(p->pSrc);
  51877. sqlite3_mutex_leave(p->pSrcDb->mutex);
  51878. return rc;
  51879. }
  51880. /*
  51881. ** Release all resources associated with an sqlite3_backup* handle.
  51882. */
  51883. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  51884. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  51885. sqlite3_mutex *mutex; /* Mutex to protect source database */
  51886. int rc; /* Value to return */
  51887. /* Enter the mutexes */
  51888. if( p==0 ) return SQLITE_OK;
  51889. sqlite3_mutex_enter(p->pSrcDb->mutex);
  51890. sqlite3BtreeEnter(p->pSrc);
  51891. mutex = p->pSrcDb->mutex;
  51892. if( p->pDestDb ){
  51893. sqlite3_mutex_enter(p->pDestDb->mutex);
  51894. }
  51895. /* Detach this backup from the source pager. */
  51896. if( p->pDestDb ){
  51897. p->pSrc->nBackup--;
  51898. }
  51899. if( p->isAttached ){
  51900. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  51901. while( *pp!=p ){
  51902. pp = &(*pp)->pNext;
  51903. }
  51904. *pp = p->pNext;
  51905. }
  51906. /* If a transaction is still open on the Btree, roll it back. */
  51907. sqlite3BtreeRollback(p->pDest);
  51908. /* Set the error code of the destination database handle. */
  51909. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  51910. sqlite3Error(p->pDestDb, rc, 0);
  51911. /* Exit the mutexes and free the backup context structure. */
  51912. if( p->pDestDb ){
  51913. sqlite3_mutex_leave(p->pDestDb->mutex);
  51914. }
  51915. sqlite3BtreeLeave(p->pSrc);
  51916. if( p->pDestDb ){
  51917. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  51918. ** call to sqlite3_backup_init() and is destroyed by a call to
  51919. ** sqlite3_backup_finish(). */
  51920. sqlite3_free(p);
  51921. }
  51922. sqlite3_mutex_leave(mutex);
  51923. return rc;
  51924. }
  51925. /*
  51926. ** Return the number of pages still to be backed up as of the most recent
  51927. ** call to sqlite3_backup_step().
  51928. */
  51929. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  51930. return p->nRemaining;
  51931. }
  51932. /*
  51933. ** Return the total number of pages in the source database as of the most
  51934. ** recent call to sqlite3_backup_step().
  51935. */
  51936. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  51937. return p->nPagecount;
  51938. }
  51939. /*
  51940. ** This function is called after the contents of page iPage of the
  51941. ** source database have been modified. If page iPage has already been
  51942. ** copied into the destination database, then the data written to the
  51943. ** destination is now invalidated. The destination copy of iPage needs
  51944. ** to be updated with the new data before the backup operation is
  51945. ** complete.
  51946. **
  51947. ** It is assumed that the mutex associated with the BtShared object
  51948. ** corresponding to the source database is held when this function is
  51949. ** called.
  51950. */
  51951. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  51952. sqlite3_backup *p; /* Iterator variable */
  51953. for(p=pBackup; p; p=p->pNext){
  51954. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  51955. if( !isFatalError(p->rc) && iPage<p->iNext ){
  51956. /* The backup process p has already copied page iPage. But now it
  51957. ** has been modified by a transaction on the source pager. Copy
  51958. ** the new data into the backup.
  51959. */
  51960. int rc;
  51961. assert( p->pDestDb );
  51962. sqlite3_mutex_enter(p->pDestDb->mutex);
  51963. rc = backupOnePage(p, iPage, aData);
  51964. sqlite3_mutex_leave(p->pDestDb->mutex);
  51965. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  51966. if( rc!=SQLITE_OK ){
  51967. p->rc = rc;
  51968. }
  51969. }
  51970. }
  51971. }
  51972. /*
  51973. ** Restart the backup process. This is called when the pager layer
  51974. ** detects that the database has been modified by an external database
  51975. ** connection. In this case there is no way of knowing which of the
  51976. ** pages that have been copied into the destination database are still
  51977. ** valid and which are not, so the entire process needs to be restarted.
  51978. **
  51979. ** It is assumed that the mutex associated with the BtShared object
  51980. ** corresponding to the source database is held when this function is
  51981. ** called.
  51982. */
  51983. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  51984. sqlite3_backup *p; /* Iterator variable */
  51985. for(p=pBackup; p; p=p->pNext){
  51986. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  51987. p->iNext = 1;
  51988. }
  51989. }
  51990. #ifndef SQLITE_OMIT_VACUUM
  51991. /*
  51992. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  51993. ** must be active for both files.
  51994. **
  51995. ** The size of file pTo may be reduced by this operation. If anything
  51996. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  51997. ** transaction is committed before returning.
  51998. */
  51999. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  52000. int rc;
  52001. sqlite3_backup b;
  52002. sqlite3BtreeEnter(pTo);
  52003. sqlite3BtreeEnter(pFrom);
  52004. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  52005. ** to 0. This is used by the implementations of sqlite3_backup_step()
  52006. ** and sqlite3_backup_finish() to detect that they are being called
  52007. ** from this function, not directly by the user.
  52008. */
  52009. memset(&b, 0, sizeof(b));
  52010. b.pSrcDb = pFrom->db;
  52011. b.pSrc = pFrom;
  52012. b.pDest = pTo;
  52013. b.iNext = 1;
  52014. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  52015. ** file. By passing this as the number of pages to copy to
  52016. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  52017. ** within a single call (unless an error occurs). The assert() statement
  52018. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  52019. ** or an error code.
  52020. */
  52021. sqlite3_backup_step(&b, 0x7FFFFFFF);
  52022. assert( b.rc!=SQLITE_OK );
  52023. rc = sqlite3_backup_finish(&b);
  52024. if( rc==SQLITE_OK ){
  52025. pTo->pBt->pageSizeFixed = 0;
  52026. }
  52027. sqlite3BtreeLeave(pFrom);
  52028. sqlite3BtreeLeave(pTo);
  52029. return rc;
  52030. }
  52031. #endif /* SQLITE_OMIT_VACUUM */
  52032. /************** End of backup.c **********************************************/
  52033. /************** Begin file vdbemem.c *****************************************/
  52034. /*
  52035. ** 2004 May 26
  52036. **
  52037. ** The author disclaims copyright to this source code. In place of
  52038. ** a legal notice, here is a blessing:
  52039. **
  52040. ** May you do good and not evil.
  52041. ** May you find forgiveness for yourself and forgive others.
  52042. ** May you share freely, never taking more than you give.
  52043. **
  52044. *************************************************************************
  52045. **
  52046. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  52047. ** stores a single value in the VDBE. Mem is an opaque structure visible
  52048. ** only within the VDBE. Interface routines refer to a Mem using the
  52049. ** name sqlite_value
  52050. */
  52051. /*
  52052. ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
  52053. ** P if required.
  52054. */
  52055. #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  52056. /*
  52057. ** If pMem is an object with a valid string representation, this routine
  52058. ** ensures the internal encoding for the string representation is
  52059. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  52060. **
  52061. ** If pMem is not a string object, or the encoding of the string
  52062. ** representation is already stored using the requested encoding, then this
  52063. ** routine is a no-op.
  52064. **
  52065. ** SQLITE_OK is returned if the conversion is successful (or not required).
  52066. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  52067. ** between formats.
  52068. */
  52069. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  52070. int rc;
  52071. assert( (pMem->flags&MEM_RowSet)==0 );
  52072. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  52073. || desiredEnc==SQLITE_UTF16BE );
  52074. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  52075. return SQLITE_OK;
  52076. }
  52077. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52078. #ifdef SQLITE_OMIT_UTF16
  52079. return SQLITE_ERROR;
  52080. #else
  52081. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  52082. ** then the encoding of the value may not have changed.
  52083. */
  52084. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  52085. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  52086. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  52087. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  52088. return rc;
  52089. #endif
  52090. }
  52091. /*
  52092. ** Make sure pMem->z points to a writable allocation of at least
  52093. ** n bytes.
  52094. **
  52095. ** If the memory cell currently contains string or blob data
  52096. ** and the third argument passed to this function is true, the
  52097. ** current content of the cell is preserved. Otherwise, it may
  52098. ** be discarded.
  52099. **
  52100. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  52101. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  52102. ** not set, Mem.n is zeroed.
  52103. */
  52104. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  52105. assert( 1 >=
  52106. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  52107. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  52108. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  52109. ((pMem->flags&MEM_Static) ? 1 : 0)
  52110. );
  52111. assert( (pMem->flags&MEM_RowSet)==0 );
  52112. if( n<32 ) n = 32;
  52113. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  52114. if( preserve && pMem->z==pMem->zMalloc ){
  52115. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  52116. preserve = 0;
  52117. }else{
  52118. sqlite3DbFree(pMem->db, pMem->zMalloc);
  52119. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  52120. }
  52121. }
  52122. if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  52123. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  52124. }
  52125. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  52126. pMem->xDel((void *)(pMem->z));
  52127. }
  52128. pMem->z = pMem->zMalloc;
  52129. if( pMem->z==0 ){
  52130. pMem->flags = MEM_Null;
  52131. }else{
  52132. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  52133. }
  52134. pMem->xDel = 0;
  52135. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  52136. }
  52137. /*
  52138. ** Make the given Mem object MEM_Dyn. In other words, make it so
  52139. ** that any TEXT or BLOB content is stored in memory obtained from
  52140. ** malloc(). In this way, we know that the memory is safe to be
  52141. ** overwritten or altered.
  52142. **
  52143. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  52144. */
  52145. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  52146. int f;
  52147. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52148. assert( (pMem->flags&MEM_RowSet)==0 );
  52149. expandBlob(pMem);
  52150. f = pMem->flags;
  52151. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  52152. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  52153. return SQLITE_NOMEM;
  52154. }
  52155. pMem->z[pMem->n] = 0;
  52156. pMem->z[pMem->n+1] = 0;
  52157. pMem->flags |= MEM_Term;
  52158. #ifdef SQLITE_DEBUG
  52159. pMem->pScopyFrom = 0;
  52160. #endif
  52161. }
  52162. return SQLITE_OK;
  52163. }
  52164. /*
  52165. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  52166. ** blob stored in dynamically allocated space.
  52167. */
  52168. #ifndef SQLITE_OMIT_INCRBLOB
  52169. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  52170. if( pMem->flags & MEM_Zero ){
  52171. int nByte;
  52172. assert( pMem->flags&MEM_Blob );
  52173. assert( (pMem->flags&MEM_RowSet)==0 );
  52174. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52175. /* Set nByte to the number of bytes required to store the expanded blob. */
  52176. nByte = pMem->n + pMem->u.nZero;
  52177. if( nByte<=0 ){
  52178. nByte = 1;
  52179. }
  52180. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  52181. return SQLITE_NOMEM;
  52182. }
  52183. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  52184. pMem->n += pMem->u.nZero;
  52185. pMem->flags &= ~(MEM_Zero|MEM_Term);
  52186. }
  52187. return SQLITE_OK;
  52188. }
  52189. #endif
  52190. /*
  52191. ** Make sure the given Mem is \u0000 terminated.
  52192. */
  52193. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  52194. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52195. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  52196. return SQLITE_OK; /* Nothing to do */
  52197. }
  52198. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  52199. return SQLITE_NOMEM;
  52200. }
  52201. pMem->z[pMem->n] = 0;
  52202. pMem->z[pMem->n+1] = 0;
  52203. pMem->flags |= MEM_Term;
  52204. return SQLITE_OK;
  52205. }
  52206. /*
  52207. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  52208. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  52209. ** is a no-op.
  52210. **
  52211. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  52212. **
  52213. ** A MEM_Null value will never be passed to this function. This function is
  52214. ** used for converting values to text for returning to the user (i.e. via
  52215. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  52216. ** keys are strings. In the former case a NULL pointer is returned the
  52217. ** user and the later is an internal programming error.
  52218. */
  52219. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  52220. int rc = SQLITE_OK;
  52221. int fg = pMem->flags;
  52222. const int nByte = 32;
  52223. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52224. assert( !(fg&MEM_Zero) );
  52225. assert( !(fg&(MEM_Str|MEM_Blob)) );
  52226. assert( fg&(MEM_Int|MEM_Real) );
  52227. assert( (pMem->flags&MEM_RowSet)==0 );
  52228. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  52229. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  52230. return SQLITE_NOMEM;
  52231. }
  52232. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  52233. ** string representation of the value. Then, if the required encoding
  52234. ** is UTF-16le or UTF-16be do a translation.
  52235. **
  52236. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  52237. */
  52238. if( fg & MEM_Int ){
  52239. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  52240. }else{
  52241. assert( fg & MEM_Real );
  52242. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  52243. }
  52244. pMem->n = sqlite3Strlen30(pMem->z);
  52245. pMem->enc = SQLITE_UTF8;
  52246. pMem->flags |= MEM_Str|MEM_Term;
  52247. sqlite3VdbeChangeEncoding(pMem, enc);
  52248. return rc;
  52249. }
  52250. /*
  52251. ** Memory cell pMem contains the context of an aggregate function.
  52252. ** This routine calls the finalize method for that function. The
  52253. ** result of the aggregate is stored back into pMem.
  52254. **
  52255. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  52256. ** otherwise.
  52257. */
  52258. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  52259. int rc = SQLITE_OK;
  52260. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  52261. sqlite3_context ctx;
  52262. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  52263. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52264. memset(&ctx, 0, sizeof(ctx));
  52265. ctx.s.flags = MEM_Null;
  52266. ctx.s.db = pMem->db;
  52267. ctx.pMem = pMem;
  52268. ctx.pFunc = pFunc;
  52269. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  52270. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  52271. sqlite3DbFree(pMem->db, pMem->zMalloc);
  52272. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  52273. rc = ctx.isError;
  52274. }
  52275. return rc;
  52276. }
  52277. /*
  52278. ** If the memory cell contains a string value that must be freed by
  52279. ** invoking an external callback, free it now. Calling this function
  52280. ** does not free any Mem.zMalloc buffer.
  52281. */
  52282. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  52283. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  52284. testcase( p->flags & MEM_Agg );
  52285. testcase( p->flags & MEM_Dyn );
  52286. testcase( p->flags & MEM_RowSet );
  52287. testcase( p->flags & MEM_Frame );
  52288. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
  52289. if( p->flags&MEM_Agg ){
  52290. sqlite3VdbeMemFinalize(p, p->u.pDef);
  52291. assert( (p->flags & MEM_Agg)==0 );
  52292. sqlite3VdbeMemRelease(p);
  52293. }else if( p->flags&MEM_Dyn && p->xDel ){
  52294. assert( (p->flags&MEM_RowSet)==0 );
  52295. p->xDel((void *)p->z);
  52296. p->xDel = 0;
  52297. }else if( p->flags&MEM_RowSet ){
  52298. sqlite3RowSetClear(p->u.pRowSet);
  52299. }else if( p->flags&MEM_Frame ){
  52300. sqlite3VdbeMemSetNull(p);
  52301. }
  52302. }
  52303. }
  52304. /*
  52305. ** Release any memory held by the Mem. This may leave the Mem in an
  52306. ** inconsistent state, for example with (Mem.z==0) and
  52307. ** (Mem.type==SQLITE_TEXT).
  52308. */
  52309. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  52310. sqlite3VdbeMemReleaseExternal(p);
  52311. sqlite3DbFree(p->db, p->zMalloc);
  52312. p->z = 0;
  52313. p->zMalloc = 0;
  52314. p->xDel = 0;
  52315. }
  52316. /*
  52317. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  52318. ** If the double is too large, return 0x8000000000000000.
  52319. **
  52320. ** Most systems appear to do this simply by assigning
  52321. ** variables and without the extra range tests. But
  52322. ** there are reports that windows throws an expection
  52323. ** if the floating point value is out of range. (See ticket #2880.)
  52324. ** Because we do not completely understand the problem, we will
  52325. ** take the conservative approach and always do range tests
  52326. ** before attempting the conversion.
  52327. */
  52328. static i64 doubleToInt64(double r){
  52329. #ifdef SQLITE_OMIT_FLOATING_POINT
  52330. /* When floating-point is omitted, double and int64 are the same thing */
  52331. return r;
  52332. #else
  52333. /*
  52334. ** Many compilers we encounter do not define constants for the
  52335. ** minimum and maximum 64-bit integers, or they define them
  52336. ** inconsistently. And many do not understand the "LL" notation.
  52337. ** So we define our own static constants here using nothing
  52338. ** larger than a 32-bit integer constant.
  52339. */
  52340. static const i64 maxInt = LARGEST_INT64;
  52341. static const i64 minInt = SMALLEST_INT64;
  52342. if( r<(double)minInt ){
  52343. return minInt;
  52344. }else if( r>(double)maxInt ){
  52345. /* minInt is correct here - not maxInt. It turns out that assigning
  52346. ** a very large positive number to an integer results in a very large
  52347. ** negative integer. This makes no sense, but it is what x86 hardware
  52348. ** does so for compatibility we will do the same in software. */
  52349. return minInt;
  52350. }else{
  52351. return (i64)r;
  52352. }
  52353. #endif
  52354. }
  52355. /*
  52356. ** Return some kind of integer value which is the best we can do
  52357. ** at representing the value that *pMem describes as an integer.
  52358. ** If pMem is an integer, then the value is exact. If pMem is
  52359. ** a floating-point then the value returned is the integer part.
  52360. ** If pMem is a string or blob, then we make an attempt to convert
  52361. ** it into a integer and return that. If pMem represents an
  52362. ** an SQL-NULL value, return 0.
  52363. **
  52364. ** If pMem represents a string value, its encoding might be changed.
  52365. */
  52366. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  52367. int flags;
  52368. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52369. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  52370. flags = pMem->flags;
  52371. if( flags & MEM_Int ){
  52372. return pMem->u.i;
  52373. }else if( flags & MEM_Real ){
  52374. return doubleToInt64(pMem->r);
  52375. }else if( flags & (MEM_Str|MEM_Blob) ){
  52376. i64 value = 0;
  52377. assert( pMem->z || pMem->n==0 );
  52378. testcase( pMem->z==0 );
  52379. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  52380. return value;
  52381. }else{
  52382. return 0;
  52383. }
  52384. }
  52385. /*
  52386. ** Return the best representation of pMem that we can get into a
  52387. ** double. If pMem is already a double or an integer, return its
  52388. ** value. If it is a string or blob, try to convert it to a double.
  52389. ** If it is a NULL, return 0.0.
  52390. */
  52391. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  52392. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52393. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  52394. if( pMem->flags & MEM_Real ){
  52395. return pMem->r;
  52396. }else if( pMem->flags & MEM_Int ){
  52397. return (double)pMem->u.i;
  52398. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  52399. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  52400. double val = (double)0;
  52401. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  52402. return val;
  52403. }else{
  52404. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  52405. return (double)0;
  52406. }
  52407. }
  52408. /*
  52409. ** The MEM structure is already a MEM_Real. Try to also make it a
  52410. ** MEM_Int if we can.
  52411. */
  52412. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  52413. assert( pMem->flags & MEM_Real );
  52414. assert( (pMem->flags & MEM_RowSet)==0 );
  52415. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52416. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  52417. pMem->u.i = doubleToInt64(pMem->r);
  52418. /* Only mark the value as an integer if
  52419. **
  52420. ** (1) the round-trip conversion real->int->real is a no-op, and
  52421. ** (2) The integer is neither the largest nor the smallest
  52422. ** possible integer (ticket #3922)
  52423. **
  52424. ** The second and third terms in the following conditional enforces
  52425. ** the second condition under the assumption that addition overflow causes
  52426. ** values to wrap around. On x86 hardware, the third term is always
  52427. ** true and could be omitted. But we leave it in because other
  52428. ** architectures might behave differently.
  52429. */
  52430. if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
  52431. && ALWAYS(pMem->u.i<LARGEST_INT64) ){
  52432. pMem->flags |= MEM_Int;
  52433. }
  52434. }
  52435. /*
  52436. ** Convert pMem to type integer. Invalidate any prior representations.
  52437. */
  52438. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  52439. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52440. assert( (pMem->flags & MEM_RowSet)==0 );
  52441. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  52442. pMem->u.i = sqlite3VdbeIntValue(pMem);
  52443. MemSetTypeFlag(pMem, MEM_Int);
  52444. return SQLITE_OK;
  52445. }
  52446. /*
  52447. ** Convert pMem so that it is of type MEM_Real.
  52448. ** Invalidate any prior representations.
  52449. */
  52450. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  52451. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52452. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  52453. pMem->r = sqlite3VdbeRealValue(pMem);
  52454. MemSetTypeFlag(pMem, MEM_Real);
  52455. return SQLITE_OK;
  52456. }
  52457. /*
  52458. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  52459. ** Invalidate any prior representations.
  52460. **
  52461. ** Every effort is made to force the conversion, even if the input
  52462. ** is a string that does not look completely like a number. Convert
  52463. ** as much of the string as we can and ignore the rest.
  52464. */
  52465. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  52466. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  52467. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  52468. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52469. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  52470. MemSetTypeFlag(pMem, MEM_Int);
  52471. }else{
  52472. pMem->r = sqlite3VdbeRealValue(pMem);
  52473. MemSetTypeFlag(pMem, MEM_Real);
  52474. sqlite3VdbeIntegerAffinity(pMem);
  52475. }
  52476. }
  52477. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  52478. pMem->flags &= ~(MEM_Str|MEM_Blob);
  52479. return SQLITE_OK;
  52480. }
  52481. /*
  52482. ** Delete any previous value and set the value stored in *pMem to NULL.
  52483. */
  52484. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  52485. if( pMem->flags & MEM_Frame ){
  52486. VdbeFrame *pFrame = pMem->u.pFrame;
  52487. pFrame->pParent = pFrame->v->pDelFrame;
  52488. pFrame->v->pDelFrame = pFrame;
  52489. }
  52490. if( pMem->flags & MEM_RowSet ){
  52491. sqlite3RowSetClear(pMem->u.pRowSet);
  52492. }
  52493. MemSetTypeFlag(pMem, MEM_Null);
  52494. pMem->type = SQLITE_NULL;
  52495. }
  52496. /*
  52497. ** Delete any previous value and set the value to be a BLOB of length
  52498. ** n containing all zeros.
  52499. */
  52500. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  52501. sqlite3VdbeMemRelease(pMem);
  52502. pMem->flags = MEM_Blob|MEM_Zero;
  52503. pMem->type = SQLITE_BLOB;
  52504. pMem->n = 0;
  52505. if( n<0 ) n = 0;
  52506. pMem->u.nZero = n;
  52507. pMem->enc = SQLITE_UTF8;
  52508. #ifdef SQLITE_OMIT_INCRBLOB
  52509. sqlite3VdbeMemGrow(pMem, n, 0);
  52510. if( pMem->z ){
  52511. pMem->n = n;
  52512. memset(pMem->z, 0, n);
  52513. }
  52514. #endif
  52515. }
  52516. /*
  52517. ** Delete any previous value and set the value stored in *pMem to val,
  52518. ** manifest type INTEGER.
  52519. */
  52520. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  52521. sqlite3VdbeMemRelease(pMem);
  52522. pMem->u.i = val;
  52523. pMem->flags = MEM_Int;
  52524. pMem->type = SQLITE_INTEGER;
  52525. }
  52526. #ifndef SQLITE_OMIT_FLOATING_POINT
  52527. /*
  52528. ** Delete any previous value and set the value stored in *pMem to val,
  52529. ** manifest type REAL.
  52530. */
  52531. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  52532. if( sqlite3IsNaN(val) ){
  52533. sqlite3VdbeMemSetNull(pMem);
  52534. }else{
  52535. sqlite3VdbeMemRelease(pMem);
  52536. pMem->r = val;
  52537. pMem->flags = MEM_Real;
  52538. pMem->type = SQLITE_FLOAT;
  52539. }
  52540. }
  52541. #endif
  52542. /*
  52543. ** Delete any previous value and set the value of pMem to be an
  52544. ** empty boolean index.
  52545. */
  52546. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  52547. sqlite3 *db = pMem->db;
  52548. assert( db!=0 );
  52549. assert( (pMem->flags & MEM_RowSet)==0 );
  52550. sqlite3VdbeMemRelease(pMem);
  52551. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  52552. if( db->mallocFailed ){
  52553. pMem->flags = MEM_Null;
  52554. }else{
  52555. assert( pMem->zMalloc );
  52556. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  52557. sqlite3DbMallocSize(db, pMem->zMalloc));
  52558. assert( pMem->u.pRowSet!=0 );
  52559. pMem->flags = MEM_RowSet;
  52560. }
  52561. }
  52562. /*
  52563. ** Return true if the Mem object contains a TEXT or BLOB that is
  52564. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  52565. */
  52566. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  52567. assert( p->db!=0 );
  52568. if( p->flags & (MEM_Str|MEM_Blob) ){
  52569. int n = p->n;
  52570. if( p->flags & MEM_Zero ){
  52571. n += p->u.nZero;
  52572. }
  52573. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  52574. }
  52575. return 0;
  52576. }
  52577. #ifdef SQLITE_DEBUG
  52578. /*
  52579. ** This routine prepares a memory cell for modication by breaking
  52580. ** its link to a shallow copy and by marking any current shallow
  52581. ** copies of this cell as invalid.
  52582. **
  52583. ** This is used for testing and debugging only - to make sure shallow
  52584. ** copies are not misused.
  52585. */
  52586. SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
  52587. int i;
  52588. Mem *pX;
  52589. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  52590. if( pX->pScopyFrom==pMem ){
  52591. pX->flags |= MEM_Invalid;
  52592. pX->pScopyFrom = 0;
  52593. }
  52594. }
  52595. pMem->pScopyFrom = 0;
  52596. }
  52597. #endif /* SQLITE_DEBUG */
  52598. /*
  52599. ** Size of struct Mem not including the Mem.zMalloc member.
  52600. */
  52601. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  52602. /*
  52603. ** Make an shallow copy of pFrom into pTo. Prior contents of
  52604. ** pTo are freed. The pFrom->z field is not duplicated. If
  52605. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  52606. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  52607. */
  52608. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  52609. assert( (pFrom->flags & MEM_RowSet)==0 );
  52610. sqlite3VdbeMemReleaseExternal(pTo);
  52611. memcpy(pTo, pFrom, MEMCELLSIZE);
  52612. pTo->xDel = 0;
  52613. if( (pFrom->flags&MEM_Static)==0 ){
  52614. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  52615. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  52616. pTo->flags |= srcType;
  52617. }
  52618. }
  52619. /*
  52620. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  52621. ** freed before the copy is made.
  52622. */
  52623. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  52624. int rc = SQLITE_OK;
  52625. assert( (pFrom->flags & MEM_RowSet)==0 );
  52626. sqlite3VdbeMemReleaseExternal(pTo);
  52627. memcpy(pTo, pFrom, MEMCELLSIZE);
  52628. pTo->flags &= ~MEM_Dyn;
  52629. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  52630. if( 0==(pFrom->flags&MEM_Static) ){
  52631. pTo->flags |= MEM_Ephem;
  52632. rc = sqlite3VdbeMemMakeWriteable(pTo);
  52633. }
  52634. }
  52635. return rc;
  52636. }
  52637. /*
  52638. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  52639. ** freed. If pFrom contains ephemeral data, a copy is made.
  52640. **
  52641. ** pFrom contains an SQL NULL when this routine returns.
  52642. */
  52643. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  52644. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  52645. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  52646. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  52647. sqlite3VdbeMemRelease(pTo);
  52648. memcpy(pTo, pFrom, sizeof(Mem));
  52649. pFrom->flags = MEM_Null;
  52650. pFrom->xDel = 0;
  52651. pFrom->zMalloc = 0;
  52652. }
  52653. /*
  52654. ** Change the value of a Mem to be a string or a BLOB.
  52655. **
  52656. ** The memory management strategy depends on the value of the xDel
  52657. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  52658. ** string is copied into a (possibly existing) buffer managed by the
  52659. ** Mem structure. Otherwise, any existing buffer is freed and the
  52660. ** pointer copied.
  52661. **
  52662. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  52663. ** size limit) then no memory allocation occurs. If the string can be
  52664. ** stored without allocating memory, then it is. If a memory allocation
  52665. ** is required to store the string, then value of pMem is unchanged. In
  52666. ** either case, SQLITE_TOOBIG is returned.
  52667. */
  52668. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  52669. Mem *pMem, /* Memory cell to set to string value */
  52670. const char *z, /* String pointer */
  52671. int n, /* Bytes in string, or negative */
  52672. u8 enc, /* Encoding of z. 0 for BLOBs */
  52673. void (*xDel)(void*) /* Destructor function */
  52674. ){
  52675. int nByte = n; /* New value for pMem->n */
  52676. int iLimit; /* Maximum allowed string or blob size */
  52677. u16 flags = 0; /* New value for pMem->flags */
  52678. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  52679. assert( (pMem->flags & MEM_RowSet)==0 );
  52680. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  52681. if( !z ){
  52682. sqlite3VdbeMemSetNull(pMem);
  52683. return SQLITE_OK;
  52684. }
  52685. if( pMem->db ){
  52686. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  52687. }else{
  52688. iLimit = SQLITE_MAX_LENGTH;
  52689. }
  52690. flags = (enc==0?MEM_Blob:MEM_Str);
  52691. if( nByte<0 ){
  52692. assert( enc!=0 );
  52693. if( enc==SQLITE_UTF8 ){
  52694. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  52695. }else{
  52696. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  52697. }
  52698. flags |= MEM_Term;
  52699. }
  52700. /* The following block sets the new values of Mem.z and Mem.xDel. It
  52701. ** also sets a flag in local variable "flags" to indicate the memory
  52702. ** management (one of MEM_Dyn or MEM_Static).
  52703. */
  52704. if( xDel==SQLITE_TRANSIENT ){
  52705. int nAlloc = nByte;
  52706. if( flags&MEM_Term ){
  52707. nAlloc += (enc==SQLITE_UTF8?1:2);
  52708. }
  52709. if( nByte>iLimit ){
  52710. return SQLITE_TOOBIG;
  52711. }
  52712. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  52713. return SQLITE_NOMEM;
  52714. }
  52715. memcpy(pMem->z, z, nAlloc);
  52716. }else if( xDel==SQLITE_DYNAMIC ){
  52717. sqlite3VdbeMemRelease(pMem);
  52718. pMem->zMalloc = pMem->z = (char *)z;
  52719. pMem->xDel = 0;
  52720. }else{
  52721. sqlite3VdbeMemRelease(pMem);
  52722. pMem->z = (char *)z;
  52723. pMem->xDel = xDel;
  52724. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  52725. }
  52726. pMem->n = nByte;
  52727. pMem->flags = flags;
  52728. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  52729. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  52730. #ifndef SQLITE_OMIT_UTF16
  52731. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  52732. return SQLITE_NOMEM;
  52733. }
  52734. #endif
  52735. if( nByte>iLimit ){
  52736. return SQLITE_TOOBIG;
  52737. }
  52738. return SQLITE_OK;
  52739. }
  52740. /*
  52741. ** Compare the values contained by the two memory cells, returning
  52742. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  52743. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  52744. ** and reals) sorted numerically, followed by text ordered by the collating
  52745. ** sequence pColl and finally blob's ordered by memcmp().
  52746. **
  52747. ** Two NULL values are considered equal by this function.
  52748. */
  52749. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  52750. int rc;
  52751. int f1, f2;
  52752. int combined_flags;
  52753. f1 = pMem1->flags;
  52754. f2 = pMem2->flags;
  52755. combined_flags = f1|f2;
  52756. assert( (combined_flags & MEM_RowSet)==0 );
  52757. /* If one value is NULL, it is less than the other. If both values
  52758. ** are NULL, return 0.
  52759. */
  52760. if( combined_flags&MEM_Null ){
  52761. return (f2&MEM_Null) - (f1&MEM_Null);
  52762. }
  52763. /* If one value is a number and the other is not, the number is less.
  52764. ** If both are numbers, compare as reals if one is a real, or as integers
  52765. ** if both values are integers.
  52766. */
  52767. if( combined_flags&(MEM_Int|MEM_Real) ){
  52768. if( !(f1&(MEM_Int|MEM_Real)) ){
  52769. return 1;
  52770. }
  52771. if( !(f2&(MEM_Int|MEM_Real)) ){
  52772. return -1;
  52773. }
  52774. if( (f1 & f2 & MEM_Int)==0 ){
  52775. double r1, r2;
  52776. if( (f1&MEM_Real)==0 ){
  52777. r1 = (double)pMem1->u.i;
  52778. }else{
  52779. r1 = pMem1->r;
  52780. }
  52781. if( (f2&MEM_Real)==0 ){
  52782. r2 = (double)pMem2->u.i;
  52783. }else{
  52784. r2 = pMem2->r;
  52785. }
  52786. if( r1<r2 ) return -1;
  52787. if( r1>r2 ) return 1;
  52788. return 0;
  52789. }else{
  52790. assert( f1&MEM_Int );
  52791. assert( f2&MEM_Int );
  52792. if( pMem1->u.i < pMem2->u.i ) return -1;
  52793. if( pMem1->u.i > pMem2->u.i ) return 1;
  52794. return 0;
  52795. }
  52796. }
  52797. /* If one value is a string and the other is a blob, the string is less.
  52798. ** If both are strings, compare using the collating functions.
  52799. */
  52800. if( combined_flags&MEM_Str ){
  52801. if( (f1 & MEM_Str)==0 ){
  52802. return 1;
  52803. }
  52804. if( (f2 & MEM_Str)==0 ){
  52805. return -1;
  52806. }
  52807. assert( pMem1->enc==pMem2->enc );
  52808. assert( pMem1->enc==SQLITE_UTF8 ||
  52809. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  52810. /* The collation sequence must be defined at this point, even if
  52811. ** the user deletes the collation sequence after the vdbe program is
  52812. ** compiled (this was not always the case).
  52813. */
  52814. assert( !pColl || pColl->xCmp );
  52815. if( pColl ){
  52816. if( pMem1->enc==pColl->enc ){
  52817. /* The strings are already in the correct encoding. Call the
  52818. ** comparison function directly */
  52819. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  52820. }else{
  52821. const void *v1, *v2;
  52822. int n1, n2;
  52823. Mem c1;
  52824. Mem c2;
  52825. memset(&c1, 0, sizeof(c1));
  52826. memset(&c2, 0, sizeof(c2));
  52827. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  52828. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  52829. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  52830. n1 = v1==0 ? 0 : c1.n;
  52831. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  52832. n2 = v2==0 ? 0 : c2.n;
  52833. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  52834. sqlite3VdbeMemRelease(&c1);
  52835. sqlite3VdbeMemRelease(&c2);
  52836. return rc;
  52837. }
  52838. }
  52839. /* If a NULL pointer was passed as the collate function, fall through
  52840. ** to the blob case and use memcmp(). */
  52841. }
  52842. /* Both values must be blobs. Compare using memcmp(). */
  52843. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  52844. if( rc==0 ){
  52845. rc = pMem1->n - pMem2->n;
  52846. }
  52847. return rc;
  52848. }
  52849. /*
  52850. ** Move data out of a btree key or data field and into a Mem structure.
  52851. ** The data or key is taken from the entry that pCur is currently pointing
  52852. ** to. offset and amt determine what portion of the data or key to retrieve.
  52853. ** key is true to get the key or false to get data. The result is written
  52854. ** into the pMem element.
  52855. **
  52856. ** The pMem structure is assumed to be uninitialized. Any prior content
  52857. ** is overwritten without being freed.
  52858. **
  52859. ** If this routine fails for any reason (malloc returns NULL or unable
  52860. ** to read from the disk) then the pMem is left in an inconsistent state.
  52861. */
  52862. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  52863. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  52864. int offset, /* Offset from the start of data to return bytes from. */
  52865. int amt, /* Number of bytes to return. */
  52866. int key, /* If true, retrieve from the btree key, not data. */
  52867. Mem *pMem /* OUT: Return data in this Mem structure. */
  52868. ){
  52869. char *zData; /* Data from the btree layer */
  52870. int available = 0; /* Number of bytes available on the local btree page */
  52871. int rc = SQLITE_OK; /* Return code */
  52872. assert( sqlite3BtreeCursorIsValid(pCur) );
  52873. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  52874. ** that both the BtShared and database handle mutexes are held. */
  52875. assert( (pMem->flags & MEM_RowSet)==0 );
  52876. if( key ){
  52877. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  52878. }else{
  52879. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  52880. }
  52881. assert( zData!=0 );
  52882. if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
  52883. sqlite3VdbeMemRelease(pMem);
  52884. pMem->z = &zData[offset];
  52885. pMem->flags = MEM_Blob|MEM_Ephem;
  52886. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  52887. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  52888. pMem->enc = 0;
  52889. pMem->type = SQLITE_BLOB;
  52890. if( key ){
  52891. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  52892. }else{
  52893. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  52894. }
  52895. pMem->z[amt] = 0;
  52896. pMem->z[amt+1] = 0;
  52897. if( rc!=SQLITE_OK ){
  52898. sqlite3VdbeMemRelease(pMem);
  52899. }
  52900. }
  52901. pMem->n = amt;
  52902. return rc;
  52903. }
  52904. /* This function is only available internally, it is not part of the
  52905. ** external API. It works in a similar way to sqlite3_value_text(),
  52906. ** except the data returned is in the encoding specified by the second
  52907. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  52908. ** SQLITE_UTF8.
  52909. **
  52910. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  52911. ** If that is the case, then the result must be aligned on an even byte
  52912. ** boundary.
  52913. */
  52914. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  52915. if( !pVal ) return 0;
  52916. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  52917. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  52918. assert( (pVal->flags & MEM_RowSet)==0 );
  52919. if( pVal->flags&MEM_Null ){
  52920. return 0;
  52921. }
  52922. assert( (MEM_Blob>>3) == MEM_Str );
  52923. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  52924. expandBlob(pVal);
  52925. if( pVal->flags&MEM_Str ){
  52926. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  52927. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  52928. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  52929. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  52930. return 0;
  52931. }
  52932. }
  52933. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
  52934. }else{
  52935. assert( (pVal->flags&MEM_Blob)==0 );
  52936. sqlite3VdbeMemStringify(pVal, enc);
  52937. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  52938. }
  52939. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  52940. || pVal->db->mallocFailed );
  52941. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  52942. return pVal->z;
  52943. }else{
  52944. return 0;
  52945. }
  52946. }
  52947. /*
  52948. ** Create a new sqlite3_value object.
  52949. */
  52950. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  52951. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  52952. if( p ){
  52953. p->flags = MEM_Null;
  52954. p->type = SQLITE_NULL;
  52955. p->db = db;
  52956. }
  52957. return p;
  52958. }
  52959. /*
  52960. ** Create a new sqlite3_value object, containing the value of pExpr.
  52961. **
  52962. ** This only works for very simple expressions that consist of one constant
  52963. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  52964. ** be converted directly into a value, then the value is allocated and
  52965. ** a pointer written to *ppVal. The caller is responsible for deallocating
  52966. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  52967. ** cannot be converted to a value, then *ppVal is set to NULL.
  52968. */
  52969. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  52970. sqlite3 *db, /* The database connection */
  52971. Expr *pExpr, /* The expression to evaluate */
  52972. u8 enc, /* Encoding to use */
  52973. u8 affinity, /* Affinity to use */
  52974. sqlite3_value **ppVal /* Write the new value here */
  52975. ){
  52976. int op;
  52977. char *zVal = 0;
  52978. sqlite3_value *pVal = 0;
  52979. int negInt = 1;
  52980. const char *zNeg = "";
  52981. if( !pExpr ){
  52982. *ppVal = 0;
  52983. return SQLITE_OK;
  52984. }
  52985. op = pExpr->op;
  52986. /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
  52987. ** The ifdef here is to enable us to achieve 100% branch test coverage even
  52988. ** when SQLITE_ENABLE_STAT2 is omitted.
  52989. */
  52990. #ifdef SQLITE_ENABLE_STAT2
  52991. if( op==TK_REGISTER ) op = pExpr->op2;
  52992. #else
  52993. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  52994. #endif
  52995. /* Handle negative integers in a single step. This is needed in the
  52996. ** case when the value is -9223372036854775808.
  52997. */
  52998. if( op==TK_UMINUS
  52999. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  53000. pExpr = pExpr->pLeft;
  53001. op = pExpr->op;
  53002. negInt = -1;
  53003. zNeg = "-";
  53004. }
  53005. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  53006. pVal = sqlite3ValueNew(db);
  53007. if( pVal==0 ) goto no_mem;
  53008. if( ExprHasProperty(pExpr, EP_IntValue) ){
  53009. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  53010. }else{
  53011. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  53012. if( zVal==0 ) goto no_mem;
  53013. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  53014. if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
  53015. }
  53016. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  53017. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  53018. }else{
  53019. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  53020. }
  53021. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  53022. if( enc!=SQLITE_UTF8 ){
  53023. sqlite3VdbeChangeEncoding(pVal, enc);
  53024. }
  53025. }else if( op==TK_UMINUS ) {
  53026. /* This branch happens for multiple negative signs. Ex: -(-5) */
  53027. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
  53028. sqlite3VdbeMemNumerify(pVal);
  53029. if( pVal->u.i==SMALLEST_INT64 ){
  53030. pVal->flags &= MEM_Int;
  53031. pVal->flags |= MEM_Real;
  53032. pVal->r = (double)LARGEST_INT64;
  53033. }else{
  53034. pVal->u.i = -pVal->u.i;
  53035. }
  53036. pVal->r = -pVal->r;
  53037. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  53038. }
  53039. }else if( op==TK_NULL ){
  53040. pVal = sqlite3ValueNew(db);
  53041. if( pVal==0 ) goto no_mem;
  53042. }
  53043. #ifndef SQLITE_OMIT_BLOB_LITERAL
  53044. else if( op==TK_BLOB ){
  53045. int nVal;
  53046. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  53047. assert( pExpr->u.zToken[1]=='\'' );
  53048. pVal = sqlite3ValueNew(db);
  53049. if( !pVal ) goto no_mem;
  53050. zVal = &pExpr->u.zToken[2];
  53051. nVal = sqlite3Strlen30(zVal)-1;
  53052. assert( zVal[nVal]=='\'' );
  53053. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  53054. 0, SQLITE_DYNAMIC);
  53055. }
  53056. #endif
  53057. if( pVal ){
  53058. sqlite3VdbeMemStoreType(pVal);
  53059. }
  53060. *ppVal = pVal;
  53061. return SQLITE_OK;
  53062. no_mem:
  53063. db->mallocFailed = 1;
  53064. sqlite3DbFree(db, zVal);
  53065. sqlite3ValueFree(pVal);
  53066. *ppVal = 0;
  53067. return SQLITE_NOMEM;
  53068. }
  53069. /*
  53070. ** Change the string value of an sqlite3_value object
  53071. */
  53072. SQLITE_PRIVATE void sqlite3ValueSetStr(
  53073. sqlite3_value *v, /* Value to be set */
  53074. int n, /* Length of string z */
  53075. const void *z, /* Text of the new string */
  53076. u8 enc, /* Encoding to use */
  53077. void (*xDel)(void*) /* Destructor for the string */
  53078. ){
  53079. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  53080. }
  53081. /*
  53082. ** Free an sqlite3_value object
  53083. */
  53084. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  53085. if( !v ) return;
  53086. sqlite3VdbeMemRelease((Mem *)v);
  53087. sqlite3DbFree(((Mem*)v)->db, v);
  53088. }
  53089. /*
  53090. ** Return the number of bytes in the sqlite3_value object assuming
  53091. ** that it uses the encoding "enc"
  53092. */
  53093. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  53094. Mem *p = (Mem*)pVal;
  53095. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  53096. if( p->flags & MEM_Zero ){
  53097. return p->n + p->u.nZero;
  53098. }else{
  53099. return p->n;
  53100. }
  53101. }
  53102. return 0;
  53103. }
  53104. /************** End of vdbemem.c *********************************************/
  53105. /************** Begin file vdbeaux.c *****************************************/
  53106. /*
  53107. ** 2003 September 6
  53108. **
  53109. ** The author disclaims copyright to this source code. In place of
  53110. ** a legal notice, here is a blessing:
  53111. **
  53112. ** May you do good and not evil.
  53113. ** May you find forgiveness for yourself and forgive others.
  53114. ** May you share freely, never taking more than you give.
  53115. **
  53116. *************************************************************************
  53117. ** This file contains code used for creating, destroying, and populating
  53118. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  53119. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  53120. ** But that file was getting too big so this subroutines were split out.
  53121. */
  53122. /*
  53123. ** When debugging the code generator in a symbolic debugger, one can
  53124. ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
  53125. ** as they are added to the instruction stream.
  53126. */
  53127. #ifdef SQLITE_DEBUG
  53128. SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
  53129. #endif
  53130. /*
  53131. ** Create a new virtual database engine.
  53132. */
  53133. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  53134. Vdbe *p;
  53135. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  53136. if( p==0 ) return 0;
  53137. p->db = db;
  53138. if( db->pVdbe ){
  53139. db->pVdbe->pPrev = p;
  53140. }
  53141. p->pNext = db->pVdbe;
  53142. p->pPrev = 0;
  53143. db->pVdbe = p;
  53144. p->magic = VDBE_MAGIC_INIT;
  53145. return p;
  53146. }
  53147. /*
  53148. ** Remember the SQL string for a prepared statement.
  53149. */
  53150. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  53151. assert( isPrepareV2==1 || isPrepareV2==0 );
  53152. if( p==0 ) return;
  53153. #ifdef SQLITE_OMIT_TRACE
  53154. if( !isPrepareV2 ) return;
  53155. #endif
  53156. assert( p->zSql==0 );
  53157. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  53158. p->isPrepareV2 = (u8)isPrepareV2;
  53159. }
  53160. /*
  53161. ** Return the SQL associated with a prepared statement
  53162. */
  53163. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  53164. Vdbe *p = (Vdbe *)pStmt;
  53165. return (p && p->isPrepareV2) ? p->zSql : 0;
  53166. }
  53167. /*
  53168. ** Swap all content between two VDBE structures.
  53169. */
  53170. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  53171. Vdbe tmp, *pTmp;
  53172. char *zTmp;
  53173. tmp = *pA;
  53174. *pA = *pB;
  53175. *pB = tmp;
  53176. pTmp = pA->pNext;
  53177. pA->pNext = pB->pNext;
  53178. pB->pNext = pTmp;
  53179. pTmp = pA->pPrev;
  53180. pA->pPrev = pB->pPrev;
  53181. pB->pPrev = pTmp;
  53182. zTmp = pA->zSql;
  53183. pA->zSql = pB->zSql;
  53184. pB->zSql = zTmp;
  53185. pB->isPrepareV2 = pA->isPrepareV2;
  53186. }
  53187. #ifdef SQLITE_DEBUG
  53188. /*
  53189. ** Turn tracing on or off
  53190. */
  53191. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  53192. p->trace = trace;
  53193. }
  53194. #endif
  53195. /*
  53196. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  53197. ** it was.
  53198. **
  53199. ** If an out-of-memory error occurs while resizing the array, return
  53200. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  53201. ** unchanged (this is so that any opcodes already allocated can be
  53202. ** correctly deallocated along with the rest of the Vdbe).
  53203. */
  53204. static int growOpArray(Vdbe *p){
  53205. VdbeOp *pNew;
  53206. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  53207. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  53208. if( pNew ){
  53209. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  53210. p->aOp = pNew;
  53211. }
  53212. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  53213. }
  53214. /*
  53215. ** Add a new instruction to the list of instructions current in the
  53216. ** VDBE. Return the address of the new instruction.
  53217. **
  53218. ** Parameters:
  53219. **
  53220. ** p Pointer to the VDBE
  53221. **
  53222. ** op The opcode for this instruction
  53223. **
  53224. ** p1, p2, p3 Operands
  53225. **
  53226. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  53227. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  53228. ** operand.
  53229. */
  53230. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  53231. int i;
  53232. VdbeOp *pOp;
  53233. i = p->nOp;
  53234. assert( p->magic==VDBE_MAGIC_INIT );
  53235. assert( op>0 && op<0xff );
  53236. if( p->nOpAlloc<=i ){
  53237. if( growOpArray(p) ){
  53238. return 1;
  53239. }
  53240. }
  53241. p->nOp++;
  53242. pOp = &p->aOp[i];
  53243. pOp->opcode = (u8)op;
  53244. pOp->p5 = 0;
  53245. pOp->p1 = p1;
  53246. pOp->p2 = p2;
  53247. pOp->p3 = p3;
  53248. pOp->p4.p = 0;
  53249. pOp->p4type = P4_NOTUSED;
  53250. p->expired = 0;
  53251. if( op==OP_ParseSchema ){
  53252. /* Any program that uses the OP_ParseSchema opcode needs to lock
  53253. ** all btrees. */
  53254. int j;
  53255. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  53256. }
  53257. #ifdef SQLITE_DEBUG
  53258. pOp->zComment = 0;
  53259. if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  53260. #endif
  53261. #ifdef VDBE_PROFILE
  53262. pOp->cycles = 0;
  53263. pOp->cnt = 0;
  53264. #endif
  53265. return i;
  53266. }
  53267. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  53268. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  53269. }
  53270. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  53271. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  53272. }
  53273. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  53274. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  53275. }
  53276. /*
  53277. ** Add an opcode that includes the p4 value as a pointer.
  53278. */
  53279. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  53280. Vdbe *p, /* Add the opcode to this VM */
  53281. int op, /* The new opcode */
  53282. int p1, /* The P1 operand */
  53283. int p2, /* The P2 operand */
  53284. int p3, /* The P3 operand */
  53285. const char *zP4, /* The P4 operand */
  53286. int p4type /* P4 operand type */
  53287. ){
  53288. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  53289. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  53290. return addr;
  53291. }
  53292. /*
  53293. ** Add an opcode that includes the p4 value as an integer.
  53294. */
  53295. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  53296. Vdbe *p, /* Add the opcode to this VM */
  53297. int op, /* The new opcode */
  53298. int p1, /* The P1 operand */
  53299. int p2, /* The P2 operand */
  53300. int p3, /* The P3 operand */
  53301. int p4 /* The P4 operand as an integer */
  53302. ){
  53303. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  53304. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  53305. return addr;
  53306. }
  53307. /*
  53308. ** Create a new symbolic label for an instruction that has yet to be
  53309. ** coded. The symbolic label is really just a negative number. The
  53310. ** label can be used as the P2 value of an operation. Later, when
  53311. ** the label is resolved to a specific address, the VDBE will scan
  53312. ** through its operation list and change all values of P2 which match
  53313. ** the label into the resolved address.
  53314. **
  53315. ** The VDBE knows that a P2 value is a label because labels are
  53316. ** always negative and P2 values are suppose to be non-negative.
  53317. ** Hence, a negative P2 value is a label that has yet to be resolved.
  53318. **
  53319. ** Zero is returned if a malloc() fails.
  53320. */
  53321. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  53322. int i;
  53323. i = p->nLabel++;
  53324. assert( p->magic==VDBE_MAGIC_INIT );
  53325. if( i>=p->nLabelAlloc ){
  53326. int n = p->nLabelAlloc*2 + 5;
  53327. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  53328. n*sizeof(p->aLabel[0]));
  53329. p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
  53330. }
  53331. if( p->aLabel ){
  53332. p->aLabel[i] = -1;
  53333. }
  53334. return -1-i;
  53335. }
  53336. /*
  53337. ** Resolve label "x" to be the address of the next instruction to
  53338. ** be inserted. The parameter "x" must have been obtained from
  53339. ** a prior call to sqlite3VdbeMakeLabel().
  53340. */
  53341. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  53342. int j = -1-x;
  53343. assert( p->magic==VDBE_MAGIC_INIT );
  53344. assert( j>=0 && j<p->nLabel );
  53345. if( p->aLabel ){
  53346. p->aLabel[j] = p->nOp;
  53347. }
  53348. }
  53349. /*
  53350. ** Mark the VDBE as one that can only be run one time.
  53351. */
  53352. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  53353. p->runOnlyOnce = 1;
  53354. }
  53355. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  53356. /*
  53357. ** The following type and function are used to iterate through all opcodes
  53358. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  53359. ** invoke directly or indirectly. It should be used as follows:
  53360. **
  53361. ** Op *pOp;
  53362. ** VdbeOpIter sIter;
  53363. **
  53364. ** memset(&sIter, 0, sizeof(sIter));
  53365. ** sIter.v = v; // v is of type Vdbe*
  53366. ** while( (pOp = opIterNext(&sIter)) ){
  53367. ** // Do something with pOp
  53368. ** }
  53369. ** sqlite3DbFree(v->db, sIter.apSub);
  53370. **
  53371. */
  53372. typedef struct VdbeOpIter VdbeOpIter;
  53373. struct VdbeOpIter {
  53374. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  53375. SubProgram **apSub; /* Array of subprograms */
  53376. int nSub; /* Number of entries in apSub */
  53377. int iAddr; /* Address of next instruction to return */
  53378. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  53379. };
  53380. static Op *opIterNext(VdbeOpIter *p){
  53381. Vdbe *v = p->v;
  53382. Op *pRet = 0;
  53383. Op *aOp;
  53384. int nOp;
  53385. if( p->iSub<=p->nSub ){
  53386. if( p->iSub==0 ){
  53387. aOp = v->aOp;
  53388. nOp = v->nOp;
  53389. }else{
  53390. aOp = p->apSub[p->iSub-1]->aOp;
  53391. nOp = p->apSub[p->iSub-1]->nOp;
  53392. }
  53393. assert( p->iAddr<nOp );
  53394. pRet = &aOp[p->iAddr];
  53395. p->iAddr++;
  53396. if( p->iAddr==nOp ){
  53397. p->iSub++;
  53398. p->iAddr = 0;
  53399. }
  53400. if( pRet->p4type==P4_SUBPROGRAM ){
  53401. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  53402. int j;
  53403. for(j=0; j<p->nSub; j++){
  53404. if( p->apSub[j]==pRet->p4.pProgram ) break;
  53405. }
  53406. if( j==p->nSub ){
  53407. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  53408. if( !p->apSub ){
  53409. pRet = 0;
  53410. }else{
  53411. p->apSub[p->nSub++] = pRet->p4.pProgram;
  53412. }
  53413. }
  53414. }
  53415. }
  53416. return pRet;
  53417. }
  53418. /*
  53419. ** Check if the program stored in the VM associated with pParse may
  53420. ** throw an ABORT exception (causing the statement, but not entire transaction
  53421. ** to be rolled back). This condition is true if the main program or any
  53422. ** sub-programs contains any of the following:
  53423. **
  53424. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  53425. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  53426. ** * OP_Destroy
  53427. ** * OP_VUpdate
  53428. ** * OP_VRename
  53429. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  53430. **
  53431. ** Then check that the value of Parse.mayAbort is true if an
  53432. ** ABORT may be thrown, or false otherwise. Return true if it does
  53433. ** match, or false otherwise. This function is intended to be used as
  53434. ** part of an assert statement in the compiler. Similar to:
  53435. **
  53436. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  53437. */
  53438. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  53439. int hasAbort = 0;
  53440. Op *pOp;
  53441. VdbeOpIter sIter;
  53442. memset(&sIter, 0, sizeof(sIter));
  53443. sIter.v = v;
  53444. while( (pOp = opIterNext(&sIter))!=0 ){
  53445. int opcode = pOp->opcode;
  53446. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  53447. #ifndef SQLITE_OMIT_FOREIGN_KEY
  53448. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  53449. #endif
  53450. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  53451. && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  53452. ){
  53453. hasAbort = 1;
  53454. break;
  53455. }
  53456. }
  53457. sqlite3DbFree(v->db, sIter.apSub);
  53458. /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
  53459. ** If malloc failed, then the while() loop above may not have iterated
  53460. ** through all opcodes and hasAbort may be set incorrectly. Return
  53461. ** true for this case to prevent the assert() in the callers frame
  53462. ** from failing. */
  53463. return ( v->db->mallocFailed || hasAbort==mayAbort );
  53464. }
  53465. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  53466. /*
  53467. ** Loop through the program looking for P2 values that are negative
  53468. ** on jump instructions. Each such value is a label. Resolve the
  53469. ** label by setting the P2 value to its correct non-zero value.
  53470. **
  53471. ** This routine is called once after all opcodes have been inserted.
  53472. **
  53473. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  53474. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  53475. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  53476. **
  53477. ** The Op.opflags field is set on all opcodes.
  53478. */
  53479. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  53480. int i;
  53481. int nMaxArgs = *pMaxFuncArgs;
  53482. Op *pOp;
  53483. int *aLabel = p->aLabel;
  53484. p->readOnly = 1;
  53485. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  53486. u8 opcode = pOp->opcode;
  53487. pOp->opflags = sqlite3OpcodeProperty[opcode];
  53488. if( opcode==OP_Function || opcode==OP_AggStep ){
  53489. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  53490. }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
  53491. p->readOnly = 0;
  53492. #ifndef SQLITE_OMIT_VIRTUALTABLE
  53493. }else if( opcode==OP_VUpdate ){
  53494. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  53495. }else if( opcode==OP_VFilter ){
  53496. int n;
  53497. assert( p->nOp - i >= 3 );
  53498. assert( pOp[-1].opcode==OP_Integer );
  53499. n = pOp[-1].p1;
  53500. if( n>nMaxArgs ) nMaxArgs = n;
  53501. #endif
  53502. }
  53503. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  53504. assert( -1-pOp->p2<p->nLabel );
  53505. pOp->p2 = aLabel[-1-pOp->p2];
  53506. }
  53507. }
  53508. sqlite3DbFree(p->db, p->aLabel);
  53509. p->aLabel = 0;
  53510. *pMaxFuncArgs = nMaxArgs;
  53511. }
  53512. /*
  53513. ** Return the address of the next instruction to be inserted.
  53514. */
  53515. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  53516. assert( p->magic==VDBE_MAGIC_INIT );
  53517. return p->nOp;
  53518. }
  53519. /*
  53520. ** This function returns a pointer to the array of opcodes associated with
  53521. ** the Vdbe passed as the first argument. It is the callers responsibility
  53522. ** to arrange for the returned array to be eventually freed using the
  53523. ** vdbeFreeOpArray() function.
  53524. **
  53525. ** Before returning, *pnOp is set to the number of entries in the returned
  53526. ** array. Also, *pnMaxArg is set to the larger of its current value and
  53527. ** the number of entries in the Vdbe.apArg[] array required to execute the
  53528. ** returned program.
  53529. */
  53530. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  53531. VdbeOp *aOp = p->aOp;
  53532. assert( aOp && !p->db->mallocFailed );
  53533. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  53534. assert( p->btreeMask==0 );
  53535. resolveP2Values(p, pnMaxArg);
  53536. *pnOp = p->nOp;
  53537. p->aOp = 0;
  53538. return aOp;
  53539. }
  53540. /*
  53541. ** Add a whole list of operations to the operation stack. Return the
  53542. ** address of the first operation added.
  53543. */
  53544. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  53545. int addr;
  53546. assert( p->magic==VDBE_MAGIC_INIT );
  53547. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  53548. return 0;
  53549. }
  53550. addr = p->nOp;
  53551. if( ALWAYS(nOp>0) ){
  53552. int i;
  53553. VdbeOpList const *pIn = aOp;
  53554. for(i=0; i<nOp; i++, pIn++){
  53555. int p2 = pIn->p2;
  53556. VdbeOp *pOut = &p->aOp[i+addr];
  53557. pOut->opcode = pIn->opcode;
  53558. pOut->p1 = pIn->p1;
  53559. if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
  53560. pOut->p2 = addr + ADDR(p2);
  53561. }else{
  53562. pOut->p2 = p2;
  53563. }
  53564. pOut->p3 = pIn->p3;
  53565. pOut->p4type = P4_NOTUSED;
  53566. pOut->p4.p = 0;
  53567. pOut->p5 = 0;
  53568. #ifdef SQLITE_DEBUG
  53569. pOut->zComment = 0;
  53570. if( sqlite3VdbeAddopTrace ){
  53571. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  53572. }
  53573. #endif
  53574. }
  53575. p->nOp += nOp;
  53576. }
  53577. return addr;
  53578. }
  53579. /*
  53580. ** Change the value of the P1 operand for a specific instruction.
  53581. ** This routine is useful when a large program is loaded from a
  53582. ** static array using sqlite3VdbeAddOpList but we want to make a
  53583. ** few minor changes to the program.
  53584. */
  53585. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
  53586. assert( p!=0 );
  53587. assert( addr>=0 );
  53588. if( p->nOp>addr ){
  53589. p->aOp[addr].p1 = val;
  53590. }
  53591. }
  53592. /*
  53593. ** Change the value of the P2 operand for a specific instruction.
  53594. ** This routine is useful for setting a jump destination.
  53595. */
  53596. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
  53597. assert( p!=0 );
  53598. assert( addr>=0 );
  53599. if( p->nOp>addr ){
  53600. p->aOp[addr].p2 = val;
  53601. }
  53602. }
  53603. /*
  53604. ** Change the value of the P3 operand for a specific instruction.
  53605. */
  53606. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
  53607. assert( p!=0 );
  53608. assert( addr>=0 );
  53609. if( p->nOp>addr ){
  53610. p->aOp[addr].p3 = val;
  53611. }
  53612. }
  53613. /*
  53614. ** Change the value of the P5 operand for the most recently
  53615. ** added operation.
  53616. */
  53617. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  53618. assert( p!=0 );
  53619. if( p->aOp ){
  53620. assert( p->nOp>0 );
  53621. p->aOp[p->nOp-1].p5 = val;
  53622. }
  53623. }
  53624. /*
  53625. ** Change the P2 operand of instruction addr so that it points to
  53626. ** the address of the next instruction to be coded.
  53627. */
  53628. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  53629. assert( addr>=0 );
  53630. sqlite3VdbeChangeP2(p, addr, p->nOp);
  53631. }
  53632. /*
  53633. ** If the input FuncDef structure is ephemeral, then free it. If
  53634. ** the FuncDef is not ephermal, then do nothing.
  53635. */
  53636. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  53637. if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
  53638. sqlite3DbFree(db, pDef);
  53639. }
  53640. }
  53641. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  53642. /*
  53643. ** Delete a P4 value if necessary.
  53644. */
  53645. static void freeP4(sqlite3 *db, int p4type, void *p4){
  53646. if( p4 ){
  53647. assert( db );
  53648. switch( p4type ){
  53649. case P4_REAL:
  53650. case P4_INT64:
  53651. case P4_DYNAMIC:
  53652. case P4_KEYINFO:
  53653. case P4_INTARRAY:
  53654. case P4_KEYINFO_HANDOFF: {
  53655. sqlite3DbFree(db, p4);
  53656. break;
  53657. }
  53658. case P4_MPRINTF: {
  53659. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  53660. break;
  53661. }
  53662. case P4_VDBEFUNC: {
  53663. VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
  53664. freeEphemeralFunction(db, pVdbeFunc->pFunc);
  53665. if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
  53666. sqlite3DbFree(db, pVdbeFunc);
  53667. break;
  53668. }
  53669. case P4_FUNCDEF: {
  53670. freeEphemeralFunction(db, (FuncDef*)p4);
  53671. break;
  53672. }
  53673. case P4_MEM: {
  53674. if( db->pnBytesFreed==0 ){
  53675. sqlite3ValueFree((sqlite3_value*)p4);
  53676. }else{
  53677. Mem *p = (Mem*)p4;
  53678. sqlite3DbFree(db, p->zMalloc);
  53679. sqlite3DbFree(db, p);
  53680. }
  53681. break;
  53682. }
  53683. case P4_VTAB : {
  53684. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  53685. break;
  53686. }
  53687. }
  53688. }
  53689. }
  53690. /*
  53691. ** Free the space allocated for aOp and any p4 values allocated for the
  53692. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  53693. ** nOp entries.
  53694. */
  53695. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  53696. if( aOp ){
  53697. Op *pOp;
  53698. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  53699. freeP4(db, pOp->p4type, pOp->p4.p);
  53700. #ifdef SQLITE_DEBUG
  53701. sqlite3DbFree(db, pOp->zComment);
  53702. #endif
  53703. }
  53704. }
  53705. sqlite3DbFree(db, aOp);
  53706. }
  53707. /*
  53708. ** Link the SubProgram object passed as the second argument into the linked
  53709. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  53710. ** objects when the VM is no longer required.
  53711. */
  53712. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  53713. p->pNext = pVdbe->pProgram;
  53714. pVdbe->pProgram = p;
  53715. }
  53716. /*
  53717. ** Change N opcodes starting at addr to No-ops.
  53718. */
  53719. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
  53720. if( p->aOp ){
  53721. VdbeOp *pOp = &p->aOp[addr];
  53722. sqlite3 *db = p->db;
  53723. while( N-- ){
  53724. freeP4(db, pOp->p4type, pOp->p4.p);
  53725. memset(pOp, 0, sizeof(pOp[0]));
  53726. pOp->opcode = OP_Noop;
  53727. pOp++;
  53728. }
  53729. }
  53730. }
  53731. /*
  53732. ** Change the value of the P4 operand for a specific instruction.
  53733. ** This routine is useful when a large program is loaded from a
  53734. ** static array using sqlite3VdbeAddOpList but we want to make a
  53735. ** few minor changes to the program.
  53736. **
  53737. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  53738. ** the string is made into memory obtained from sqlite3_malloc().
  53739. ** A value of n==0 means copy bytes of zP4 up to and including the
  53740. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  53741. **
  53742. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  53743. ** A copy is made of the KeyInfo structure into memory obtained from
  53744. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  53745. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  53746. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  53747. ** caller should not free the allocation, it will be freed when the Vdbe is
  53748. ** finalized.
  53749. **
  53750. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  53751. ** to a string or structure that is guaranteed to exist for the lifetime of
  53752. ** the Vdbe. In these cases we can just copy the pointer.
  53753. **
  53754. ** If addr<0 then change P4 on the most recently inserted instruction.
  53755. */
  53756. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  53757. Op *pOp;
  53758. sqlite3 *db;
  53759. assert( p!=0 );
  53760. db = p->db;
  53761. assert( p->magic==VDBE_MAGIC_INIT );
  53762. if( p->aOp==0 || db->mallocFailed ){
  53763. if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
  53764. freeP4(db, n, (void*)*(char**)&zP4);
  53765. }
  53766. return;
  53767. }
  53768. assert( p->nOp>0 );
  53769. assert( addr<p->nOp );
  53770. if( addr<0 ){
  53771. addr = p->nOp - 1;
  53772. }
  53773. pOp = &p->aOp[addr];
  53774. freeP4(db, pOp->p4type, pOp->p4.p);
  53775. pOp->p4.p = 0;
  53776. if( n==P4_INT32 ){
  53777. /* Note: this cast is safe, because the origin data point was an int
  53778. ** that was cast to a (const char *). */
  53779. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  53780. pOp->p4type = P4_INT32;
  53781. }else if( zP4==0 ){
  53782. pOp->p4.p = 0;
  53783. pOp->p4type = P4_NOTUSED;
  53784. }else if( n==P4_KEYINFO ){
  53785. KeyInfo *pKeyInfo;
  53786. int nField, nByte;
  53787. nField = ((KeyInfo*)zP4)->nField;
  53788. nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
  53789. pKeyInfo = sqlite3DbMallocRaw(0, nByte);
  53790. pOp->p4.pKeyInfo = pKeyInfo;
  53791. if( pKeyInfo ){
  53792. u8 *aSortOrder;
  53793. memcpy((char*)pKeyInfo, zP4, nByte - nField);
  53794. aSortOrder = pKeyInfo->aSortOrder;
  53795. if( aSortOrder ){
  53796. pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
  53797. memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
  53798. }
  53799. pOp->p4type = P4_KEYINFO;
  53800. }else{
  53801. p->db->mallocFailed = 1;
  53802. pOp->p4type = P4_NOTUSED;
  53803. }
  53804. }else if( n==P4_KEYINFO_HANDOFF ){
  53805. pOp->p4.p = (void*)zP4;
  53806. pOp->p4type = P4_KEYINFO;
  53807. }else if( n==P4_VTAB ){
  53808. pOp->p4.p = (void*)zP4;
  53809. pOp->p4type = P4_VTAB;
  53810. sqlite3VtabLock((VTable *)zP4);
  53811. assert( ((VTable *)zP4)->db==p->db );
  53812. }else if( n<0 ){
  53813. pOp->p4.p = (void*)zP4;
  53814. pOp->p4type = (signed char)n;
  53815. }else{
  53816. if( n==0 ) n = sqlite3Strlen30(zP4);
  53817. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  53818. pOp->p4type = P4_DYNAMIC;
  53819. }
  53820. }
  53821. #ifndef NDEBUG
  53822. /*
  53823. ** Change the comment on the the most recently coded instruction. Or
  53824. ** insert a No-op and add the comment to that new instruction. This
  53825. ** makes the code easier to read during debugging. None of this happens
  53826. ** in a production build.
  53827. */
  53828. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  53829. va_list ap;
  53830. if( !p ) return;
  53831. assert( p->nOp>0 || p->aOp==0 );
  53832. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  53833. if( p->nOp ){
  53834. char **pz = &p->aOp[p->nOp-1].zComment;
  53835. va_start(ap, zFormat);
  53836. sqlite3DbFree(p->db, *pz);
  53837. *pz = sqlite3VMPrintf(p->db, zFormat, ap);
  53838. va_end(ap);
  53839. }
  53840. }
  53841. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  53842. va_list ap;
  53843. if( !p ) return;
  53844. sqlite3VdbeAddOp0(p, OP_Noop);
  53845. assert( p->nOp>0 || p->aOp==0 );
  53846. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  53847. if( p->nOp ){
  53848. char **pz = &p->aOp[p->nOp-1].zComment;
  53849. va_start(ap, zFormat);
  53850. sqlite3DbFree(p->db, *pz);
  53851. *pz = sqlite3VMPrintf(p->db, zFormat, ap);
  53852. va_end(ap);
  53853. }
  53854. }
  53855. #endif /* NDEBUG */
  53856. /*
  53857. ** Return the opcode for a given address. If the address is -1, then
  53858. ** return the most recently inserted opcode.
  53859. **
  53860. ** If a memory allocation error has occurred prior to the calling of this
  53861. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  53862. ** is readable but not writable, though it is cast to a writable value.
  53863. ** The return of a dummy opcode allows the call to continue functioning
  53864. ** after a OOM fault without having to check to see if the return from
  53865. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  53866. ** dummy will never be written to. This is verified by code inspection and
  53867. ** by running with Valgrind.
  53868. **
  53869. ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
  53870. ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
  53871. ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
  53872. ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
  53873. ** having to double-check to make sure that the result is non-negative. But
  53874. ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
  53875. ** check the value of p->nOp-1 before continuing.
  53876. */
  53877. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  53878. /* C89 specifies that the constant "dummy" will be initialized to all
  53879. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  53880. static const VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  53881. assert( p->magic==VDBE_MAGIC_INIT );
  53882. if( addr<0 ){
  53883. #ifdef SQLITE_OMIT_TRACE
  53884. if( p->nOp==0 ) return (VdbeOp*)&dummy;
  53885. #endif
  53886. addr = p->nOp - 1;
  53887. }
  53888. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  53889. if( p->db->mallocFailed ){
  53890. return (VdbeOp*)&dummy;
  53891. }else{
  53892. return &p->aOp[addr];
  53893. }
  53894. }
  53895. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  53896. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  53897. /*
  53898. ** Compute a string that describes the P4 parameter for an opcode.
  53899. ** Use zTemp for any required temporary buffer space.
  53900. */
  53901. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  53902. char *zP4 = zTemp;
  53903. assert( nTemp>=20 );
  53904. switch( pOp->p4type ){
  53905. case P4_KEYINFO_STATIC:
  53906. case P4_KEYINFO: {
  53907. int i, j;
  53908. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  53909. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  53910. i = sqlite3Strlen30(zTemp);
  53911. for(j=0; j<pKeyInfo->nField; j++){
  53912. CollSeq *pColl = pKeyInfo->aColl[j];
  53913. if( pColl ){
  53914. int n = sqlite3Strlen30(pColl->zName);
  53915. if( i+n>nTemp-6 ){
  53916. memcpy(&zTemp[i],",...",4);
  53917. break;
  53918. }
  53919. zTemp[i++] = ',';
  53920. if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
  53921. zTemp[i++] = '-';
  53922. }
  53923. memcpy(&zTemp[i], pColl->zName,n+1);
  53924. i += n;
  53925. }else if( i+4<nTemp-6 ){
  53926. memcpy(&zTemp[i],",nil",4);
  53927. i += 4;
  53928. }
  53929. }
  53930. zTemp[i++] = ')';
  53931. zTemp[i] = 0;
  53932. assert( i<nTemp );
  53933. break;
  53934. }
  53935. case P4_COLLSEQ: {
  53936. CollSeq *pColl = pOp->p4.pColl;
  53937. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  53938. break;
  53939. }
  53940. case P4_FUNCDEF: {
  53941. FuncDef *pDef = pOp->p4.pFunc;
  53942. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  53943. break;
  53944. }
  53945. case P4_INT64: {
  53946. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  53947. break;
  53948. }
  53949. case P4_INT32: {
  53950. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  53951. break;
  53952. }
  53953. case P4_REAL: {
  53954. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  53955. break;
  53956. }
  53957. case P4_MEM: {
  53958. Mem *pMem = pOp->p4.pMem;
  53959. assert( (pMem->flags & MEM_Null)==0 );
  53960. if( pMem->flags & MEM_Str ){
  53961. zP4 = pMem->z;
  53962. }else if( pMem->flags & MEM_Int ){
  53963. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  53964. }else if( pMem->flags & MEM_Real ){
  53965. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  53966. }else{
  53967. assert( pMem->flags & MEM_Blob );
  53968. zP4 = "(blob)";
  53969. }
  53970. break;
  53971. }
  53972. #ifndef SQLITE_OMIT_VIRTUALTABLE
  53973. case P4_VTAB: {
  53974. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  53975. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  53976. break;
  53977. }
  53978. #endif
  53979. case P4_INTARRAY: {
  53980. sqlite3_snprintf(nTemp, zTemp, "intarray");
  53981. break;
  53982. }
  53983. case P4_SUBPROGRAM: {
  53984. sqlite3_snprintf(nTemp, zTemp, "program");
  53985. break;
  53986. }
  53987. default: {
  53988. zP4 = pOp->p4.z;
  53989. if( zP4==0 ){
  53990. zP4 = zTemp;
  53991. zTemp[0] = 0;
  53992. }
  53993. }
  53994. }
  53995. assert( zP4!=0 );
  53996. return zP4;
  53997. }
  53998. #endif
  53999. /*
  54000. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  54001. **
  54002. ** The prepared statements need to know in advance the complete set of
  54003. ** attached databases that they will be using. A mask of these databases
  54004. ** is maintained in p->btreeMask and is used for locking and other purposes.
  54005. */
  54006. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  54007. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  54008. assert( i<(int)sizeof(p->btreeMask)*8 );
  54009. p->btreeMask |= ((yDbMask)1)<<i;
  54010. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  54011. p->lockMask |= ((yDbMask)1)<<i;
  54012. }
  54013. }
  54014. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  54015. /*
  54016. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  54017. ** this routine obtains the mutex associated with each BtShared structure
  54018. ** that may be accessed by the VM passed as an argument. In doing so it also
  54019. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  54020. ** that the correct busy-handler callback is invoked if required.
  54021. **
  54022. ** If SQLite is not threadsafe but does support shared-cache mode, then
  54023. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  54024. ** of all of BtShared structures accessible via the database handle
  54025. ** associated with the VM.
  54026. **
  54027. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  54028. ** function is a no-op.
  54029. **
  54030. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  54031. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  54032. ** corresponding to btrees that use shared cache. Then the runtime of
  54033. ** this routine is N*N. But as N is rarely more than 1, this should not
  54034. ** be a problem.
  54035. */
  54036. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  54037. int i;
  54038. yDbMask mask;
  54039. sqlite3 *db;
  54040. Db *aDb;
  54041. int nDb;
  54042. if( p->lockMask==0 ) return; /* The common case */
  54043. db = p->db;
  54044. aDb = db->aDb;
  54045. nDb = db->nDb;
  54046. for(i=0, mask=1; i<nDb; i++, mask += mask){
  54047. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  54048. sqlite3BtreeEnter(aDb[i].pBt);
  54049. }
  54050. }
  54051. }
  54052. #endif
  54053. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  54054. /*
  54055. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  54056. */
  54057. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  54058. int i;
  54059. yDbMask mask;
  54060. sqlite3 *db;
  54061. Db *aDb;
  54062. int nDb;
  54063. if( p->lockMask==0 ) return; /* The common case */
  54064. db = p->db;
  54065. aDb = db->aDb;
  54066. nDb = db->nDb;
  54067. for(i=0, mask=1; i<nDb; i++, mask += mask){
  54068. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  54069. sqlite3BtreeLeave(aDb[i].pBt);
  54070. }
  54071. }
  54072. }
  54073. #endif
  54074. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  54075. /*
  54076. ** Print a single opcode. This routine is used for debugging only.
  54077. */
  54078. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  54079. char *zP4;
  54080. char zPtr[50];
  54081. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  54082. if( pOut==0 ) pOut = stdout;
  54083. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  54084. fprintf(pOut, zFormat1, pc,
  54085. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  54086. #ifdef SQLITE_DEBUG
  54087. pOp->zComment ? pOp->zComment : ""
  54088. #else
  54089. ""
  54090. #endif
  54091. );
  54092. fflush(pOut);
  54093. }
  54094. #endif
  54095. /*
  54096. ** Release an array of N Mem elements
  54097. */
  54098. static void releaseMemArray(Mem *p, int N){
  54099. if( p && N ){
  54100. Mem *pEnd;
  54101. sqlite3 *db = p->db;
  54102. u8 malloc_failed = db->mallocFailed;
  54103. if( db->pnBytesFreed ){
  54104. for(pEnd=&p[N]; p<pEnd; p++){
  54105. sqlite3DbFree(db, p->zMalloc);
  54106. }
  54107. return;
  54108. }
  54109. for(pEnd=&p[N]; p<pEnd; p++){
  54110. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  54111. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  54112. ** that takes advantage of the fact that the memory cell value is
  54113. ** being set to NULL after releasing any dynamic resources.
  54114. **
  54115. ** The justification for duplicating code is that according to
  54116. ** callgrind, this causes a certain test case to hit the CPU 4.7
  54117. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  54118. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  54119. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  54120. ** with no indexes using a single prepared INSERT statement, bind()
  54121. ** and reset(). Inserts are grouped into a transaction.
  54122. */
  54123. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  54124. sqlite3VdbeMemRelease(p);
  54125. }else if( p->zMalloc ){
  54126. sqlite3DbFree(db, p->zMalloc);
  54127. p->zMalloc = 0;
  54128. }
  54129. p->flags = MEM_Null;
  54130. }
  54131. db->mallocFailed = malloc_failed;
  54132. }
  54133. }
  54134. /*
  54135. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  54136. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  54137. */
  54138. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  54139. int i;
  54140. Mem *aMem = VdbeFrameMem(p);
  54141. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  54142. for(i=0; i<p->nChildCsr; i++){
  54143. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  54144. }
  54145. releaseMemArray(aMem, p->nChildMem);
  54146. sqlite3DbFree(p->v->db, p);
  54147. }
  54148. #ifndef SQLITE_OMIT_EXPLAIN
  54149. /*
  54150. ** Give a listing of the program in the virtual machine.
  54151. **
  54152. ** The interface is the same as sqlite3VdbeExec(). But instead of
  54153. ** running the code, it invokes the callback once for each instruction.
  54154. ** This feature is used to implement "EXPLAIN".
  54155. **
  54156. ** When p->explain==1, each instruction is listed. When
  54157. ** p->explain==2, only OP_Explain instructions are listed and these
  54158. ** are shown in a different format. p->explain==2 is used to implement
  54159. ** EXPLAIN QUERY PLAN.
  54160. **
  54161. ** When p->explain==1, first the main program is listed, then each of
  54162. ** the trigger subprograms are listed one by one.
  54163. */
  54164. SQLITE_PRIVATE int sqlite3VdbeList(
  54165. Vdbe *p /* The VDBE */
  54166. ){
  54167. int nRow; /* Stop when row count reaches this */
  54168. int nSub = 0; /* Number of sub-vdbes seen so far */
  54169. SubProgram **apSub = 0; /* Array of sub-vdbes */
  54170. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  54171. sqlite3 *db = p->db; /* The database connection */
  54172. int i; /* Loop counter */
  54173. int rc = SQLITE_OK; /* Return code */
  54174. Mem *pMem = p->pResultSet = &p->aMem[1]; /* First Mem of result set */
  54175. assert( p->explain );
  54176. assert( p->magic==VDBE_MAGIC_RUN );
  54177. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  54178. /* Even though this opcode does not use dynamic strings for
  54179. ** the result, result columns may become dynamic if the user calls
  54180. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  54181. */
  54182. releaseMemArray(pMem, 8);
  54183. if( p->rc==SQLITE_NOMEM ){
  54184. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  54185. ** sqlite3_column_text16() failed. */
  54186. db->mallocFailed = 1;
  54187. return SQLITE_ERROR;
  54188. }
  54189. /* When the number of output rows reaches nRow, that means the
  54190. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  54191. ** nRow is the sum of the number of rows in the main program, plus
  54192. ** the sum of the number of rows in all trigger subprograms encountered
  54193. ** so far. The nRow value will increase as new trigger subprograms are
  54194. ** encountered, but p->pc will eventually catch up to nRow.
  54195. */
  54196. nRow = p->nOp;
  54197. if( p->explain==1 ){
  54198. /* The first 8 memory cells are used for the result set. So we will
  54199. ** commandeer the 9th cell to use as storage for an array of pointers
  54200. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  54201. ** cells. */
  54202. assert( p->nMem>9 );
  54203. pSub = &p->aMem[9];
  54204. if( pSub->flags&MEM_Blob ){
  54205. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  54206. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  54207. nSub = pSub->n/sizeof(Vdbe*);
  54208. apSub = (SubProgram **)pSub->z;
  54209. }
  54210. for(i=0; i<nSub; i++){
  54211. nRow += apSub[i]->nOp;
  54212. }
  54213. }
  54214. do{
  54215. i = p->pc++;
  54216. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  54217. if( i>=nRow ){
  54218. p->rc = SQLITE_OK;
  54219. rc = SQLITE_DONE;
  54220. }else if( db->u1.isInterrupted ){
  54221. p->rc = SQLITE_INTERRUPT;
  54222. rc = SQLITE_ERROR;
  54223. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  54224. }else{
  54225. char *z;
  54226. Op *pOp;
  54227. if( i<p->nOp ){
  54228. /* The output line number is small enough that we are still in the
  54229. ** main program. */
  54230. pOp = &p->aOp[i];
  54231. }else{
  54232. /* We are currently listing subprograms. Figure out which one and
  54233. ** pick up the appropriate opcode. */
  54234. int j;
  54235. i -= p->nOp;
  54236. for(j=0; i>=apSub[j]->nOp; j++){
  54237. i -= apSub[j]->nOp;
  54238. }
  54239. pOp = &apSub[j]->aOp[i];
  54240. }
  54241. if( p->explain==1 ){
  54242. pMem->flags = MEM_Int;
  54243. pMem->type = SQLITE_INTEGER;
  54244. pMem->u.i = i; /* Program counter */
  54245. pMem++;
  54246. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  54247. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  54248. assert( pMem->z!=0 );
  54249. pMem->n = sqlite3Strlen30(pMem->z);
  54250. pMem->type = SQLITE_TEXT;
  54251. pMem->enc = SQLITE_UTF8;
  54252. pMem++;
  54253. /* When an OP_Program opcode is encounter (the only opcode that has
  54254. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  54255. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  54256. ** has not already been seen.
  54257. */
  54258. if( pOp->p4type==P4_SUBPROGRAM ){
  54259. int nByte = (nSub+1)*sizeof(SubProgram*);
  54260. int j;
  54261. for(j=0; j<nSub; j++){
  54262. if( apSub[j]==pOp->p4.pProgram ) break;
  54263. }
  54264. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
  54265. apSub = (SubProgram **)pSub->z;
  54266. apSub[nSub++] = pOp->p4.pProgram;
  54267. pSub->flags |= MEM_Blob;
  54268. pSub->n = nSub*sizeof(SubProgram*);
  54269. }
  54270. }
  54271. }
  54272. pMem->flags = MEM_Int;
  54273. pMem->u.i = pOp->p1; /* P1 */
  54274. pMem->type = SQLITE_INTEGER;
  54275. pMem++;
  54276. pMem->flags = MEM_Int;
  54277. pMem->u.i = pOp->p2; /* P2 */
  54278. pMem->type = SQLITE_INTEGER;
  54279. pMem++;
  54280. pMem->flags = MEM_Int;
  54281. pMem->u.i = pOp->p3; /* P3 */
  54282. pMem->type = SQLITE_INTEGER;
  54283. pMem++;
  54284. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  54285. assert( p->db->mallocFailed );
  54286. return SQLITE_ERROR;
  54287. }
  54288. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  54289. z = displayP4(pOp, pMem->z, 32);
  54290. if( z!=pMem->z ){
  54291. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  54292. }else{
  54293. assert( pMem->z!=0 );
  54294. pMem->n = sqlite3Strlen30(pMem->z);
  54295. pMem->enc = SQLITE_UTF8;
  54296. }
  54297. pMem->type = SQLITE_TEXT;
  54298. pMem++;
  54299. if( p->explain==1 ){
  54300. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  54301. assert( p->db->mallocFailed );
  54302. return SQLITE_ERROR;
  54303. }
  54304. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  54305. pMem->n = 2;
  54306. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  54307. pMem->type = SQLITE_TEXT;
  54308. pMem->enc = SQLITE_UTF8;
  54309. pMem++;
  54310. #ifdef SQLITE_DEBUG
  54311. if( pOp->zComment ){
  54312. pMem->flags = MEM_Str|MEM_Term;
  54313. pMem->z = pOp->zComment;
  54314. pMem->n = sqlite3Strlen30(pMem->z);
  54315. pMem->enc = SQLITE_UTF8;
  54316. pMem->type = SQLITE_TEXT;
  54317. }else
  54318. #endif
  54319. {
  54320. pMem->flags = MEM_Null; /* Comment */
  54321. pMem->type = SQLITE_NULL;
  54322. }
  54323. }
  54324. p->nResColumn = 8 - 4*(p->explain-1);
  54325. p->rc = SQLITE_OK;
  54326. rc = SQLITE_ROW;
  54327. }
  54328. return rc;
  54329. }
  54330. #endif /* SQLITE_OMIT_EXPLAIN */
  54331. #ifdef SQLITE_DEBUG
  54332. /*
  54333. ** Print the SQL that was used to generate a VDBE program.
  54334. */
  54335. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  54336. int nOp = p->nOp;
  54337. VdbeOp *pOp;
  54338. if( nOp<1 ) return;
  54339. pOp = &p->aOp[0];
  54340. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  54341. const char *z = pOp->p4.z;
  54342. while( sqlite3Isspace(*z) ) z++;
  54343. printf("SQL: [%s]\n", z);
  54344. }
  54345. }
  54346. #endif
  54347. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  54348. /*
  54349. ** Print an IOTRACE message showing SQL content.
  54350. */
  54351. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  54352. int nOp = p->nOp;
  54353. VdbeOp *pOp;
  54354. if( sqlite3IoTrace==0 ) return;
  54355. if( nOp<1 ) return;
  54356. pOp = &p->aOp[0];
  54357. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  54358. int i, j;
  54359. char z[1000];
  54360. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  54361. for(i=0; sqlite3Isspace(z[i]); i++){}
  54362. for(j=0; z[i]; i++){
  54363. if( sqlite3Isspace(z[i]) ){
  54364. if( z[i-1]!=' ' ){
  54365. z[j++] = ' ';
  54366. }
  54367. }else{
  54368. z[j++] = z[i];
  54369. }
  54370. }
  54371. z[j] = 0;
  54372. sqlite3IoTrace("SQL %s\n", z);
  54373. }
  54374. }
  54375. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  54376. /*
  54377. ** Allocate space from a fixed size buffer and return a pointer to
  54378. ** that space. If insufficient space is available, return NULL.
  54379. **
  54380. ** The pBuf parameter is the initial value of a pointer which will
  54381. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  54382. ** NULL, it means that memory space has already been allocated and that
  54383. ** this routine should not allocate any new memory. When pBuf is not
  54384. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  54385. ** is NULL.
  54386. **
  54387. ** nByte is the number of bytes of space needed.
  54388. **
  54389. ** *ppFrom points to available space and pEnd points to the end of the
  54390. ** available space. When space is allocated, *ppFrom is advanced past
  54391. ** the end of the allocated space.
  54392. **
  54393. ** *pnByte is a counter of the number of bytes of space that have failed
  54394. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  54395. ** request, then increment *pnByte by the amount of the request.
  54396. */
  54397. static void *allocSpace(
  54398. void *pBuf, /* Where return pointer will be stored */
  54399. int nByte, /* Number of bytes to allocate */
  54400. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  54401. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  54402. int *pnByte /* If allocation cannot be made, increment *pnByte */
  54403. ){
  54404. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  54405. if( pBuf ) return pBuf;
  54406. nByte = ROUND8(nByte);
  54407. if( &(*ppFrom)[nByte] <= pEnd ){
  54408. pBuf = (void*)*ppFrom;
  54409. *ppFrom += nByte;
  54410. }else{
  54411. *pnByte += nByte;
  54412. }
  54413. return pBuf;
  54414. }
  54415. /*
  54416. ** Prepare a virtual machine for execution. This involves things such
  54417. ** as allocating stack space and initializing the program counter.
  54418. ** After the VDBE has be prepped, it can be executed by one or more
  54419. ** calls to sqlite3VdbeExec().
  54420. **
  54421. ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
  54422. ** VDBE_MAGIC_RUN.
  54423. **
  54424. ** This function may be called more than once on a single virtual machine.
  54425. ** The first call is made while compiling the SQL statement. Subsequent
  54426. ** calls are made as part of the process of resetting a statement to be
  54427. ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
  54428. ** and isExplain parameters are only passed correct values the first time
  54429. ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
  54430. ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
  54431. */
  54432. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  54433. Vdbe *p, /* The VDBE */
  54434. int nVar, /* Number of '?' see in the SQL statement */
  54435. int nMem, /* Number of memory cells to allocate */
  54436. int nCursor, /* Number of cursors to allocate */
  54437. int nArg, /* Maximum number of args in SubPrograms */
  54438. int isExplain, /* True if the EXPLAIN keywords is present */
  54439. int usesStmtJournal /* True to set Vdbe.usesStmtJournal */
  54440. ){
  54441. int n;
  54442. sqlite3 *db = p->db;
  54443. assert( p!=0 );
  54444. assert( p->magic==VDBE_MAGIC_INIT );
  54445. /* There should be at least one opcode.
  54446. */
  54447. assert( p->nOp>0 );
  54448. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  54449. p->magic = VDBE_MAGIC_RUN;
  54450. /* For each cursor required, also allocate a memory cell. Memory
  54451. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  54452. ** the vdbe program. Instead they are used to allocate space for
  54453. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  54454. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  54455. ** stores the blob of memory associated with cursor 1, etc.
  54456. **
  54457. ** See also: allocateCursor().
  54458. */
  54459. nMem += nCursor;
  54460. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  54461. ** an array to marshal SQL function arguments in. This is only done the
  54462. ** first time this function is called for a given VDBE, not when it is
  54463. ** being called from sqlite3_reset() to reset the virtual machine.
  54464. */
  54465. if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
  54466. u8 *zCsr = (u8 *)&p->aOp[p->nOp]; /* Memory avaliable for alloation */
  54467. u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc]; /* First byte past available mem */
  54468. int nByte; /* How much extra memory needed */
  54469. resolveP2Values(p, &nArg);
  54470. p->usesStmtJournal = (u8)usesStmtJournal;
  54471. if( isExplain && nMem<10 ){
  54472. nMem = 10;
  54473. }
  54474. memset(zCsr, 0, zEnd-zCsr);
  54475. zCsr += (zCsr - (u8*)0)&7;
  54476. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  54477. /* Memory for registers, parameters, cursor, etc, is allocated in two
  54478. ** passes. On the first pass, we try to reuse unused space at the
  54479. ** end of the opcode array. If we are unable to satisfy all memory
  54480. ** requirements by reusing the opcode array tail, then the second
  54481. ** pass will fill in the rest using a fresh allocation.
  54482. **
  54483. ** This two-pass approach that reuses as much memory as possible from
  54484. ** the leftover space at the end of the opcode array can significantly
  54485. ** reduce the amount of memory held by a prepared statement.
  54486. */
  54487. do {
  54488. nByte = 0;
  54489. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  54490. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  54491. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  54492. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  54493. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  54494. &zCsr, zEnd, &nByte);
  54495. if( nByte ){
  54496. p->pFree = sqlite3DbMallocZero(db, nByte);
  54497. }
  54498. zCsr = p->pFree;
  54499. zEnd = &zCsr[nByte];
  54500. }while( nByte && !db->mallocFailed );
  54501. p->nCursor = (u16)nCursor;
  54502. if( p->aVar ){
  54503. p->nVar = (ynVar)nVar;
  54504. for(n=0; n<nVar; n++){
  54505. p->aVar[n].flags = MEM_Null;
  54506. p->aVar[n].db = db;
  54507. }
  54508. }
  54509. if( p->aMem ){
  54510. p->aMem--; /* aMem[] goes from 1..nMem */
  54511. p->nMem = nMem; /* not from 0..nMem-1 */
  54512. for(n=1; n<=nMem; n++){
  54513. p->aMem[n].flags = MEM_Null;
  54514. p->aMem[n].db = db;
  54515. }
  54516. }
  54517. }
  54518. #ifdef SQLITE_DEBUG
  54519. for(n=1; n<p->nMem; n++){
  54520. assert( p->aMem[n].db==db );
  54521. }
  54522. #endif
  54523. p->pc = -1;
  54524. p->rc = SQLITE_OK;
  54525. p->errorAction = OE_Abort;
  54526. p->explain |= isExplain;
  54527. p->magic = VDBE_MAGIC_RUN;
  54528. p->nChange = 0;
  54529. p->cacheCtr = 1;
  54530. p->minWriteFileFormat = 255;
  54531. p->iStatement = 0;
  54532. p->nFkConstraint = 0;
  54533. #ifdef VDBE_PROFILE
  54534. {
  54535. int i;
  54536. for(i=0; i<p->nOp; i++){
  54537. p->aOp[i].cnt = 0;
  54538. p->aOp[i].cycles = 0;
  54539. }
  54540. }
  54541. #endif
  54542. }
  54543. /*
  54544. ** Close a VDBE cursor and release all the resources that cursor
  54545. ** happens to hold.
  54546. */
  54547. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  54548. if( pCx==0 ){
  54549. return;
  54550. }
  54551. if( pCx->pBt ){
  54552. sqlite3BtreeClose(pCx->pBt);
  54553. /* The pCx->pCursor will be close automatically, if it exists, by
  54554. ** the call above. */
  54555. }else if( pCx->pCursor ){
  54556. sqlite3BtreeCloseCursor(pCx->pCursor);
  54557. }
  54558. #ifndef SQLITE_OMIT_VIRTUALTABLE
  54559. if( pCx->pVtabCursor ){
  54560. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  54561. const sqlite3_module *pModule = pCx->pModule;
  54562. p->inVtabMethod = 1;
  54563. pModule->xClose(pVtabCursor);
  54564. p->inVtabMethod = 0;
  54565. }
  54566. #endif
  54567. }
  54568. /*
  54569. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  54570. ** is used, for example, when a trigger sub-program is halted to restore
  54571. ** control to the main program.
  54572. */
  54573. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  54574. Vdbe *v = pFrame->v;
  54575. v->aOp = pFrame->aOp;
  54576. v->nOp = pFrame->nOp;
  54577. v->aMem = pFrame->aMem;
  54578. v->nMem = pFrame->nMem;
  54579. v->apCsr = pFrame->apCsr;
  54580. v->nCursor = pFrame->nCursor;
  54581. v->db->lastRowid = pFrame->lastRowid;
  54582. v->nChange = pFrame->nChange;
  54583. return pFrame->pc;
  54584. }
  54585. /*
  54586. ** Close all cursors.
  54587. **
  54588. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  54589. ** cell array. This is necessary as the memory cell array may contain
  54590. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  54591. ** open cursors.
  54592. */
  54593. static void closeAllCursors(Vdbe *p){
  54594. if( p->pFrame ){
  54595. VdbeFrame *pFrame;
  54596. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  54597. sqlite3VdbeFrameRestore(pFrame);
  54598. }
  54599. p->pFrame = 0;
  54600. p->nFrame = 0;
  54601. if( p->apCsr ){
  54602. int i;
  54603. for(i=0; i<p->nCursor; i++){
  54604. VdbeCursor *pC = p->apCsr[i];
  54605. if( pC ){
  54606. sqlite3VdbeFreeCursor(p, pC);
  54607. p->apCsr[i] = 0;
  54608. }
  54609. }
  54610. }
  54611. if( p->aMem ){
  54612. releaseMemArray(&p->aMem[1], p->nMem);
  54613. }
  54614. while( p->pDelFrame ){
  54615. VdbeFrame *pDel = p->pDelFrame;
  54616. p->pDelFrame = pDel->pParent;
  54617. sqlite3VdbeFrameDelete(pDel);
  54618. }
  54619. }
  54620. /*
  54621. ** Clean up the VM after execution.
  54622. **
  54623. ** This routine will automatically close any cursors, lists, and/or
  54624. ** sorters that were left open. It also deletes the values of
  54625. ** variables in the aVar[] array.
  54626. */
  54627. static void Cleanup(Vdbe *p){
  54628. sqlite3 *db = p->db;
  54629. #ifdef SQLITE_DEBUG
  54630. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  54631. ** Vdbe.aMem[] arrays have already been cleaned up. */
  54632. int i;
  54633. for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
  54634. for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
  54635. #endif
  54636. sqlite3DbFree(db, p->zErrMsg);
  54637. p->zErrMsg = 0;
  54638. p->pResultSet = 0;
  54639. }
  54640. /*
  54641. ** Set the number of result columns that will be returned by this SQL
  54642. ** statement. This is now set at compile time, rather than during
  54643. ** execution of the vdbe program so that sqlite3_column_count() can
  54644. ** be called on an SQL statement before sqlite3_step().
  54645. */
  54646. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  54647. Mem *pColName;
  54648. int n;
  54649. sqlite3 *db = p->db;
  54650. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  54651. sqlite3DbFree(db, p->aColName);
  54652. n = nResColumn*COLNAME_N;
  54653. p->nResColumn = (u16)nResColumn;
  54654. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  54655. if( p->aColName==0 ) return;
  54656. while( n-- > 0 ){
  54657. pColName->flags = MEM_Null;
  54658. pColName->db = p->db;
  54659. pColName++;
  54660. }
  54661. }
  54662. /*
  54663. ** Set the name of the idx'th column to be returned by the SQL statement.
  54664. ** zName must be a pointer to a nul terminated string.
  54665. **
  54666. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  54667. **
  54668. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  54669. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  54670. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  54671. */
  54672. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  54673. Vdbe *p, /* Vdbe being configured */
  54674. int idx, /* Index of column zName applies to */
  54675. int var, /* One of the COLNAME_* constants */
  54676. const char *zName, /* Pointer to buffer containing name */
  54677. void (*xDel)(void*) /* Memory management strategy for zName */
  54678. ){
  54679. int rc;
  54680. Mem *pColName;
  54681. assert( idx<p->nResColumn );
  54682. assert( var<COLNAME_N );
  54683. if( p->db->mallocFailed ){
  54684. assert( !zName || xDel!=SQLITE_DYNAMIC );
  54685. return SQLITE_NOMEM;
  54686. }
  54687. assert( p->aColName!=0 );
  54688. pColName = &(p->aColName[idx+var*p->nResColumn]);
  54689. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  54690. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  54691. return rc;
  54692. }
  54693. /*
  54694. ** A read or write transaction may or may not be active on database handle
  54695. ** db. If a transaction is active, commit it. If there is a
  54696. ** write-transaction spanning more than one database file, this routine
  54697. ** takes care of the master journal trickery.
  54698. */
  54699. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  54700. int i;
  54701. int nTrans = 0; /* Number of databases with an active write-transaction */
  54702. int rc = SQLITE_OK;
  54703. int needXcommit = 0;
  54704. #ifdef SQLITE_OMIT_VIRTUALTABLE
  54705. /* With this option, sqlite3VtabSync() is defined to be simply
  54706. ** SQLITE_OK so p is not used.
  54707. */
  54708. UNUSED_PARAMETER(p);
  54709. #endif
  54710. /* Before doing anything else, call the xSync() callback for any
  54711. ** virtual module tables written in this transaction. This has to
  54712. ** be done before determining whether a master journal file is
  54713. ** required, as an xSync() callback may add an attached database
  54714. ** to the transaction.
  54715. */
  54716. rc = sqlite3VtabSync(db, &p->zErrMsg);
  54717. /* This loop determines (a) if the commit hook should be invoked and
  54718. ** (b) how many database files have open write transactions, not
  54719. ** including the temp database. (b) is important because if more than
  54720. ** one database file has an open write transaction, a master journal
  54721. ** file is required for an atomic commit.
  54722. */
  54723. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  54724. Btree *pBt = db->aDb[i].pBt;
  54725. if( sqlite3BtreeIsInTrans(pBt) ){
  54726. needXcommit = 1;
  54727. if( i!=1 ) nTrans++;
  54728. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  54729. }
  54730. }
  54731. if( rc!=SQLITE_OK ){
  54732. return rc;
  54733. }
  54734. /* If there are any write-transactions at all, invoke the commit hook */
  54735. if( needXcommit && db->xCommitCallback ){
  54736. rc = db->xCommitCallback(db->pCommitArg);
  54737. if( rc ){
  54738. return SQLITE_CONSTRAINT;
  54739. }
  54740. }
  54741. /* The simple case - no more than one database file (not counting the
  54742. ** TEMP database) has a transaction active. There is no need for the
  54743. ** master-journal.
  54744. **
  54745. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  54746. ** string, it means the main database is :memory: or a temp file. In
  54747. ** that case we do not support atomic multi-file commits, so use the
  54748. ** simple case then too.
  54749. */
  54750. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  54751. || nTrans<=1
  54752. ){
  54753. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  54754. Btree *pBt = db->aDb[i].pBt;
  54755. if( pBt ){
  54756. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  54757. }
  54758. }
  54759. /* Do the commit only if all databases successfully complete phase 1.
  54760. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  54761. ** IO error while deleting or truncating a journal file. It is unlikely,
  54762. ** but could happen. In this case abandon processing and return the error.
  54763. */
  54764. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  54765. Btree *pBt = db->aDb[i].pBt;
  54766. if( pBt ){
  54767. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  54768. }
  54769. }
  54770. if( rc==SQLITE_OK ){
  54771. sqlite3VtabCommit(db);
  54772. }
  54773. }
  54774. /* The complex case - There is a multi-file write-transaction active.
  54775. ** This requires a master journal file to ensure the transaction is
  54776. ** committed atomicly.
  54777. */
  54778. #ifndef SQLITE_OMIT_DISKIO
  54779. else{
  54780. sqlite3_vfs *pVfs = db->pVfs;
  54781. int needSync = 0;
  54782. char *zMaster = 0; /* File-name for the master journal */
  54783. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  54784. sqlite3_file *pMaster = 0;
  54785. i64 offset = 0;
  54786. int res;
  54787. /* Select a master journal file name */
  54788. do {
  54789. u32 iRandom;
  54790. sqlite3DbFree(db, zMaster);
  54791. sqlite3_randomness(sizeof(iRandom), &iRandom);
  54792. zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
  54793. if( !zMaster ){
  54794. return SQLITE_NOMEM;
  54795. }
  54796. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  54797. }while( rc==SQLITE_OK && res );
  54798. if( rc==SQLITE_OK ){
  54799. /* Open the master journal. */
  54800. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  54801. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  54802. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  54803. );
  54804. }
  54805. if( rc!=SQLITE_OK ){
  54806. sqlite3DbFree(db, zMaster);
  54807. return rc;
  54808. }
  54809. /* Write the name of each database file in the transaction into the new
  54810. ** master journal file. If an error occurs at this point close
  54811. ** and delete the master journal file. All the individual journal files
  54812. ** still have 'null' as the master journal pointer, so they will roll
  54813. ** back independently if a failure occurs.
  54814. */
  54815. for(i=0; i<db->nDb; i++){
  54816. Btree *pBt = db->aDb[i].pBt;
  54817. if( sqlite3BtreeIsInTrans(pBt) ){
  54818. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  54819. if( zFile==0 ){
  54820. continue; /* Ignore TEMP and :memory: databases */
  54821. }
  54822. assert( zFile[0]!=0 );
  54823. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  54824. needSync = 1;
  54825. }
  54826. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  54827. offset += sqlite3Strlen30(zFile)+1;
  54828. if( rc!=SQLITE_OK ){
  54829. sqlite3OsCloseFree(pMaster);
  54830. sqlite3OsDelete(pVfs, zMaster, 0);
  54831. sqlite3DbFree(db, zMaster);
  54832. return rc;
  54833. }
  54834. }
  54835. }
  54836. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  54837. ** flag is set this is not required.
  54838. */
  54839. if( needSync
  54840. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  54841. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  54842. ){
  54843. sqlite3OsCloseFree(pMaster);
  54844. sqlite3OsDelete(pVfs, zMaster, 0);
  54845. sqlite3DbFree(db, zMaster);
  54846. return rc;
  54847. }
  54848. /* Sync all the db files involved in the transaction. The same call
  54849. ** sets the master journal pointer in each individual journal. If
  54850. ** an error occurs here, do not delete the master journal file.
  54851. **
  54852. ** If the error occurs during the first call to
  54853. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  54854. ** master journal file will be orphaned. But we cannot delete it,
  54855. ** in case the master journal file name was written into the journal
  54856. ** file before the failure occurred.
  54857. */
  54858. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  54859. Btree *pBt = db->aDb[i].pBt;
  54860. if( pBt ){
  54861. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  54862. }
  54863. }
  54864. sqlite3OsCloseFree(pMaster);
  54865. assert( rc!=SQLITE_BUSY );
  54866. if( rc!=SQLITE_OK ){
  54867. sqlite3DbFree(db, zMaster);
  54868. return rc;
  54869. }
  54870. /* Delete the master journal file. This commits the transaction. After
  54871. ** doing this the directory is synced again before any individual
  54872. ** transaction files are deleted.
  54873. */
  54874. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  54875. sqlite3DbFree(db, zMaster);
  54876. zMaster = 0;
  54877. if( rc ){
  54878. return rc;
  54879. }
  54880. /* All files and directories have already been synced, so the following
  54881. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  54882. ** deleting or truncating journals. If something goes wrong while
  54883. ** this is happening we don't really care. The integrity of the
  54884. ** transaction is already guaranteed, but some stray 'cold' journals
  54885. ** may be lying around. Returning an error code won't help matters.
  54886. */
  54887. disable_simulated_io_errors();
  54888. sqlite3BeginBenignMalloc();
  54889. for(i=0; i<db->nDb; i++){
  54890. Btree *pBt = db->aDb[i].pBt;
  54891. if( pBt ){
  54892. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  54893. }
  54894. }
  54895. sqlite3EndBenignMalloc();
  54896. enable_simulated_io_errors();
  54897. sqlite3VtabCommit(db);
  54898. }
  54899. #endif
  54900. return rc;
  54901. }
  54902. /*
  54903. ** This routine checks that the sqlite3.activeVdbeCnt count variable
  54904. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  54905. ** currently active. An assertion fails if the two counts do not match.
  54906. ** This is an internal self-check only - it is not an essential processing
  54907. ** step.
  54908. **
  54909. ** This is a no-op if NDEBUG is defined.
  54910. */
  54911. #ifndef NDEBUG
  54912. static void checkActiveVdbeCnt(sqlite3 *db){
  54913. Vdbe *p;
  54914. int cnt = 0;
  54915. int nWrite = 0;
  54916. p = db->pVdbe;
  54917. while( p ){
  54918. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  54919. cnt++;
  54920. if( p->readOnly==0 ) nWrite++;
  54921. }
  54922. p = p->pNext;
  54923. }
  54924. assert( cnt==db->activeVdbeCnt );
  54925. assert( nWrite==db->writeVdbeCnt );
  54926. }
  54927. #else
  54928. #define checkActiveVdbeCnt(x)
  54929. #endif
  54930. /*
  54931. ** For every Btree that in database connection db which
  54932. ** has been modified, "trip" or invalidate each cursor in
  54933. ** that Btree might have been modified so that the cursor
  54934. ** can never be used again. This happens when a rollback
  54935. *** occurs. We have to trip all the other cursors, even
  54936. ** cursor from other VMs in different database connections,
  54937. ** so that none of them try to use the data at which they
  54938. ** were pointing and which now may have been changed due
  54939. ** to the rollback.
  54940. **
  54941. ** Remember that a rollback can delete tables complete and
  54942. ** reorder rootpages. So it is not sufficient just to save
  54943. ** the state of the cursor. We have to invalidate the cursor
  54944. ** so that it is never used again.
  54945. */
  54946. static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
  54947. int i;
  54948. for(i=0; i<db->nDb; i++){
  54949. Btree *p = db->aDb[i].pBt;
  54950. if( p && sqlite3BtreeIsInTrans(p) ){
  54951. sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
  54952. }
  54953. }
  54954. }
  54955. /*
  54956. ** If the Vdbe passed as the first argument opened a statement-transaction,
  54957. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  54958. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  54959. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  54960. ** statement transaction is commtted.
  54961. **
  54962. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  54963. ** Otherwise SQLITE_OK.
  54964. */
  54965. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  54966. sqlite3 *const db = p->db;
  54967. int rc = SQLITE_OK;
  54968. /* If p->iStatement is greater than zero, then this Vdbe opened a
  54969. ** statement transaction that should be closed here. The only exception
  54970. ** is that an IO error may have occured, causing an emergency rollback.
  54971. ** In this case (db->nStatement==0), and there is nothing to do.
  54972. */
  54973. if( db->nStatement && p->iStatement ){
  54974. int i;
  54975. const int iSavepoint = p->iStatement-1;
  54976. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  54977. assert( db->nStatement>0 );
  54978. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  54979. for(i=0; i<db->nDb; i++){
  54980. int rc2 = SQLITE_OK;
  54981. Btree *pBt = db->aDb[i].pBt;
  54982. if( pBt ){
  54983. if( eOp==SAVEPOINT_ROLLBACK ){
  54984. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  54985. }
  54986. if( rc2==SQLITE_OK ){
  54987. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  54988. }
  54989. if( rc==SQLITE_OK ){
  54990. rc = rc2;
  54991. }
  54992. }
  54993. }
  54994. db->nStatement--;
  54995. p->iStatement = 0;
  54996. /* If the statement transaction is being rolled back, also restore the
  54997. ** database handles deferred constraint counter to the value it had when
  54998. ** the statement transaction was opened. */
  54999. if( eOp==SAVEPOINT_ROLLBACK ){
  55000. db->nDeferredCons = p->nStmtDefCons;
  55001. }
  55002. }
  55003. return rc;
  55004. }
  55005. /*
  55006. ** This function is called when a transaction opened by the database
  55007. ** handle associated with the VM passed as an argument is about to be
  55008. ** committed. If there are outstanding deferred foreign key constraint
  55009. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  55010. **
  55011. ** If there are outstanding FK violations and this function returns
  55012. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
  55013. ** an error message to it. Then return SQLITE_ERROR.
  55014. */
  55015. #ifndef SQLITE_OMIT_FOREIGN_KEY
  55016. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  55017. sqlite3 *db = p->db;
  55018. if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
  55019. p->rc = SQLITE_CONSTRAINT;
  55020. p->errorAction = OE_Abort;
  55021. sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
  55022. return SQLITE_ERROR;
  55023. }
  55024. return SQLITE_OK;
  55025. }
  55026. #endif
  55027. /*
  55028. ** This routine is called the when a VDBE tries to halt. If the VDBE
  55029. ** has made changes and is in autocommit mode, then commit those
  55030. ** changes. If a rollback is needed, then do the rollback.
  55031. **
  55032. ** This routine is the only way to move the state of a VM from
  55033. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  55034. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  55035. **
  55036. ** Return an error code. If the commit could not complete because of
  55037. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  55038. ** means the close did not happen and needs to be repeated.
  55039. */
  55040. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  55041. int rc; /* Used to store transient return codes */
  55042. sqlite3 *db = p->db;
  55043. /* This function contains the logic that determines if a statement or
  55044. ** transaction will be committed or rolled back as a result of the
  55045. ** execution of this virtual machine.
  55046. **
  55047. ** If any of the following errors occur:
  55048. **
  55049. ** SQLITE_NOMEM
  55050. ** SQLITE_IOERR
  55051. ** SQLITE_FULL
  55052. ** SQLITE_INTERRUPT
  55053. **
  55054. ** Then the internal cache might have been left in an inconsistent
  55055. ** state. We need to rollback the statement transaction, if there is
  55056. ** one, or the complete transaction if there is no statement transaction.
  55057. */
  55058. if( p->db->mallocFailed ){
  55059. p->rc = SQLITE_NOMEM;
  55060. }
  55061. closeAllCursors(p);
  55062. if( p->magic!=VDBE_MAGIC_RUN ){
  55063. return SQLITE_OK;
  55064. }
  55065. checkActiveVdbeCnt(db);
  55066. /* No commit or rollback needed if the program never started */
  55067. if( p->pc>=0 ){
  55068. int mrc; /* Primary error code from p->rc */
  55069. int eStatementOp = 0;
  55070. int isSpecialError; /* Set to true if a 'special' error */
  55071. /* Lock all btrees used by the statement */
  55072. sqlite3VdbeEnter(p);
  55073. /* Check for one of the special errors */
  55074. mrc = p->rc & 0xff;
  55075. assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
  55076. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  55077. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  55078. if( isSpecialError ){
  55079. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  55080. ** no rollback is necessary. Otherwise, at least a savepoint
  55081. ** transaction must be rolled back to restore the database to a
  55082. ** consistent state.
  55083. **
  55084. ** Even if the statement is read-only, it is important to perform
  55085. ** a statement or transaction rollback operation. If the error
  55086. ** occured while writing to the journal, sub-journal or database
  55087. ** file as part of an effort to free up cache space (see function
  55088. ** pagerStress() in pager.c), the rollback is required to restore
  55089. ** the pager to a consistent state.
  55090. */
  55091. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  55092. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  55093. eStatementOp = SAVEPOINT_ROLLBACK;
  55094. }else{
  55095. /* We are forced to roll back the active transaction. Before doing
  55096. ** so, abort any other statements this handle currently has active.
  55097. */
  55098. invalidateCursorsOnModifiedBtrees(db);
  55099. sqlite3RollbackAll(db);
  55100. sqlite3CloseSavepoints(db);
  55101. db->autoCommit = 1;
  55102. }
  55103. }
  55104. }
  55105. /* Check for immediate foreign key violations. */
  55106. if( p->rc==SQLITE_OK ){
  55107. sqlite3VdbeCheckFk(p, 0);
  55108. }
  55109. /* If the auto-commit flag is set and this is the only active writer
  55110. ** VM, then we do either a commit or rollback of the current transaction.
  55111. **
  55112. ** Note: This block also runs if one of the special errors handled
  55113. ** above has occurred.
  55114. */
  55115. if( !sqlite3VtabInSync(db)
  55116. && db->autoCommit
  55117. && db->writeVdbeCnt==(p->readOnly==0)
  55118. ){
  55119. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  55120. rc = sqlite3VdbeCheckFk(p, 1);
  55121. if( rc!=SQLITE_OK ){
  55122. if( NEVER(p->readOnly) ){
  55123. sqlite3VdbeLeave(p);
  55124. return SQLITE_ERROR;
  55125. }
  55126. rc = SQLITE_CONSTRAINT;
  55127. }else{
  55128. /* The auto-commit flag is true, the vdbe program was successful
  55129. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  55130. ** key constraints to hold up the transaction. This means a commit
  55131. ** is required. */
  55132. rc = vdbeCommit(db, p);
  55133. }
  55134. if( rc==SQLITE_BUSY && p->readOnly ){
  55135. sqlite3VdbeLeave(p);
  55136. return SQLITE_BUSY;
  55137. }else if( rc!=SQLITE_OK ){
  55138. p->rc = rc;
  55139. sqlite3RollbackAll(db);
  55140. }else{
  55141. db->nDeferredCons = 0;
  55142. sqlite3CommitInternalChanges(db);
  55143. }
  55144. }else{
  55145. sqlite3RollbackAll(db);
  55146. }
  55147. db->nStatement = 0;
  55148. }else if( eStatementOp==0 ){
  55149. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  55150. eStatementOp = SAVEPOINT_RELEASE;
  55151. }else if( p->errorAction==OE_Abort ){
  55152. eStatementOp = SAVEPOINT_ROLLBACK;
  55153. }else{
  55154. invalidateCursorsOnModifiedBtrees(db);
  55155. sqlite3RollbackAll(db);
  55156. sqlite3CloseSavepoints(db);
  55157. db->autoCommit = 1;
  55158. }
  55159. }
  55160. /* If eStatementOp is non-zero, then a statement transaction needs to
  55161. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  55162. ** do so. If this operation returns an error, and the current statement
  55163. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  55164. ** current statement error code.
  55165. **
  55166. ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
  55167. ** is SAVEPOINT_ROLLBACK. But if p->rc==SQLITE_OK then eStatementOp
  55168. ** must be SAVEPOINT_RELEASE. Hence the NEVER(p->rc==SQLITE_OK) in
  55169. ** the following code.
  55170. */
  55171. if( eStatementOp ){
  55172. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  55173. if( rc ){
  55174. assert( eStatementOp==SAVEPOINT_ROLLBACK );
  55175. if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
  55176. p->rc = rc;
  55177. sqlite3DbFree(db, p->zErrMsg);
  55178. p->zErrMsg = 0;
  55179. }
  55180. invalidateCursorsOnModifiedBtrees(db);
  55181. sqlite3RollbackAll(db);
  55182. sqlite3CloseSavepoints(db);
  55183. db->autoCommit = 1;
  55184. }
  55185. }
  55186. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  55187. ** has been rolled back, update the database connection change-counter.
  55188. */
  55189. if( p->changeCntOn ){
  55190. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  55191. sqlite3VdbeSetChanges(db, p->nChange);
  55192. }else{
  55193. sqlite3VdbeSetChanges(db, 0);
  55194. }
  55195. p->nChange = 0;
  55196. }
  55197. /* Rollback or commit any schema changes that occurred. */
  55198. if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
  55199. sqlite3ResetInternalSchema(db, -1);
  55200. db->flags = (db->flags | SQLITE_InternChanges);
  55201. }
  55202. /* Release the locks */
  55203. sqlite3VdbeLeave(p);
  55204. }
  55205. /* We have successfully halted and closed the VM. Record this fact. */
  55206. if( p->pc>=0 ){
  55207. db->activeVdbeCnt--;
  55208. if( !p->readOnly ){
  55209. db->writeVdbeCnt--;
  55210. }
  55211. assert( db->activeVdbeCnt>=db->writeVdbeCnt );
  55212. }
  55213. p->magic = VDBE_MAGIC_HALT;
  55214. checkActiveVdbeCnt(db);
  55215. if( p->db->mallocFailed ){
  55216. p->rc = SQLITE_NOMEM;
  55217. }
  55218. /* If the auto-commit flag is set to true, then any locks that were held
  55219. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  55220. ** to invoke any required unlock-notify callbacks.
  55221. */
  55222. if( db->autoCommit ){
  55223. sqlite3ConnectionUnlocked(db);
  55224. }
  55225. assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
  55226. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  55227. }
  55228. /*
  55229. ** Each VDBE holds the result of the most recent sqlite3_step() call
  55230. ** in p->rc. This routine sets that result back to SQLITE_OK.
  55231. */
  55232. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  55233. p->rc = SQLITE_OK;
  55234. }
  55235. /*
  55236. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  55237. ** Write any error messages into *pzErrMsg. Return the result code.
  55238. **
  55239. ** After this routine is run, the VDBE should be ready to be executed
  55240. ** again.
  55241. **
  55242. ** To look at it another way, this routine resets the state of the
  55243. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  55244. ** VDBE_MAGIC_INIT.
  55245. */
  55246. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  55247. sqlite3 *db;
  55248. db = p->db;
  55249. /* If the VM did not run to completion or if it encountered an
  55250. ** error, then it might not have been halted properly. So halt
  55251. ** it now.
  55252. */
  55253. sqlite3VdbeHalt(p);
  55254. /* If the VDBE has be run even partially, then transfer the error code
  55255. ** and error message from the VDBE into the main database structure. But
  55256. ** if the VDBE has just been set to run but has not actually executed any
  55257. ** instructions yet, leave the main database error information unchanged.
  55258. */
  55259. if( p->pc>=0 ){
  55260. if( p->zErrMsg ){
  55261. sqlite3BeginBenignMalloc();
  55262. sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
  55263. sqlite3EndBenignMalloc();
  55264. db->errCode = p->rc;
  55265. sqlite3DbFree(db, p->zErrMsg);
  55266. p->zErrMsg = 0;
  55267. }else if( p->rc ){
  55268. sqlite3Error(db, p->rc, 0);
  55269. }else{
  55270. sqlite3Error(db, SQLITE_OK, 0);
  55271. }
  55272. if( p->runOnlyOnce ) p->expired = 1;
  55273. }else if( p->rc && p->expired ){
  55274. /* The expired flag was set on the VDBE before the first call
  55275. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  55276. ** called), set the database error in this case as well.
  55277. */
  55278. sqlite3Error(db, p->rc, 0);
  55279. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  55280. sqlite3DbFree(db, p->zErrMsg);
  55281. p->zErrMsg = 0;
  55282. }
  55283. /* Reclaim all memory used by the VDBE
  55284. */
  55285. Cleanup(p);
  55286. /* Save profiling information from this VDBE run.
  55287. */
  55288. #ifdef VDBE_PROFILE
  55289. {
  55290. FILE *out = fopen("vdbe_profile.out", "a");
  55291. if( out ){
  55292. int i;
  55293. fprintf(out, "---- ");
  55294. for(i=0; i<p->nOp; i++){
  55295. fprintf(out, "%02x", p->aOp[i].opcode);
  55296. }
  55297. fprintf(out, "\n");
  55298. for(i=0; i<p->nOp; i++){
  55299. fprintf(out, "%6d %10lld %8lld ",
  55300. p->aOp[i].cnt,
  55301. p->aOp[i].cycles,
  55302. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  55303. );
  55304. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  55305. }
  55306. fclose(out);
  55307. }
  55308. }
  55309. #endif
  55310. p->magic = VDBE_MAGIC_INIT;
  55311. return p->rc & db->errMask;
  55312. }
  55313. /*
  55314. ** Clean up and delete a VDBE after execution. Return an integer which is
  55315. ** the result code. Write any error message text into *pzErrMsg.
  55316. */
  55317. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  55318. int rc = SQLITE_OK;
  55319. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  55320. rc = sqlite3VdbeReset(p);
  55321. assert( (rc & p->db->errMask)==rc );
  55322. }
  55323. sqlite3VdbeDelete(p);
  55324. return rc;
  55325. }
  55326. /*
  55327. ** Call the destructor for each auxdata entry in pVdbeFunc for which
  55328. ** the corresponding bit in mask is clear. Auxdata entries beyond 31
  55329. ** are always destroyed. To destroy all auxdata entries, call this
  55330. ** routine with mask==0.
  55331. */
  55332. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  55333. int i;
  55334. for(i=0; i<pVdbeFunc->nAux; i++){
  55335. struct AuxData *pAux = &pVdbeFunc->apAux[i];
  55336. if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
  55337. if( pAux->xDelete ){
  55338. pAux->xDelete(pAux->pAux);
  55339. }
  55340. pAux->pAux = 0;
  55341. }
  55342. }
  55343. }
  55344. /*
  55345. ** Free all memory associated with the Vdbe passed as the second argument.
  55346. ** The difference between this function and sqlite3VdbeDelete() is that
  55347. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  55348. ** the database connection.
  55349. */
  55350. SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
  55351. SubProgram *pSub, *pNext;
  55352. assert( p->db==0 || p->db==db );
  55353. releaseMemArray(p->aVar, p->nVar);
  55354. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  55355. for(pSub=p->pProgram; pSub; pSub=pNext){
  55356. pNext = pSub->pNext;
  55357. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  55358. sqlite3DbFree(db, pSub);
  55359. }
  55360. vdbeFreeOpArray(db, p->aOp, p->nOp);
  55361. sqlite3DbFree(db, p->aLabel);
  55362. sqlite3DbFree(db, p->aColName);
  55363. sqlite3DbFree(db, p->zSql);
  55364. sqlite3DbFree(db, p->pFree);
  55365. sqlite3DbFree(db, p);
  55366. }
  55367. /*
  55368. ** Delete an entire VDBE.
  55369. */
  55370. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  55371. sqlite3 *db;
  55372. if( NEVER(p==0) ) return;
  55373. db = p->db;
  55374. if( p->pPrev ){
  55375. p->pPrev->pNext = p->pNext;
  55376. }else{
  55377. assert( db->pVdbe==p );
  55378. db->pVdbe = p->pNext;
  55379. }
  55380. if( p->pNext ){
  55381. p->pNext->pPrev = p->pPrev;
  55382. }
  55383. p->magic = VDBE_MAGIC_DEAD;
  55384. p->db = 0;
  55385. sqlite3VdbeDeleteObject(db, p);
  55386. }
  55387. /*
  55388. ** Make sure the cursor p is ready to read or write the row to which it
  55389. ** was last positioned. Return an error code if an OOM fault or I/O error
  55390. ** prevents us from positioning the cursor to its correct position.
  55391. **
  55392. ** If a MoveTo operation is pending on the given cursor, then do that
  55393. ** MoveTo now. If no move is pending, check to see if the row has been
  55394. ** deleted out from under the cursor and if it has, mark the row as
  55395. ** a NULL row.
  55396. **
  55397. ** If the cursor is already pointing to the correct row and that row has
  55398. ** not been deleted out from under the cursor, then this routine is a no-op.
  55399. */
  55400. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  55401. if( p->deferredMoveto ){
  55402. int res, rc;
  55403. #ifdef SQLITE_TEST
  55404. extern int sqlite3_search_count;
  55405. #endif
  55406. assert( p->isTable );
  55407. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  55408. if( rc ) return rc;
  55409. p->lastRowid = p->movetoTarget;
  55410. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  55411. p->rowidIsValid = 1;
  55412. #ifdef SQLITE_TEST
  55413. sqlite3_search_count++;
  55414. #endif
  55415. p->deferredMoveto = 0;
  55416. p->cacheStatus = CACHE_STALE;
  55417. }else if( ALWAYS(p->pCursor) ){
  55418. int hasMoved;
  55419. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  55420. if( rc ) return rc;
  55421. if( hasMoved ){
  55422. p->cacheStatus = CACHE_STALE;
  55423. p->nullRow = 1;
  55424. }
  55425. }
  55426. return SQLITE_OK;
  55427. }
  55428. /*
  55429. ** The following functions:
  55430. **
  55431. ** sqlite3VdbeSerialType()
  55432. ** sqlite3VdbeSerialTypeLen()
  55433. ** sqlite3VdbeSerialLen()
  55434. ** sqlite3VdbeSerialPut()
  55435. ** sqlite3VdbeSerialGet()
  55436. **
  55437. ** encapsulate the code that serializes values for storage in SQLite
  55438. ** data and index records. Each serialized value consists of a
  55439. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  55440. ** integer, stored as a varint.
  55441. **
  55442. ** In an SQLite index record, the serial type is stored directly before
  55443. ** the blob of data that it corresponds to. In a table record, all serial
  55444. ** types are stored at the start of the record, and the blobs of data at
  55445. ** the end. Hence these functions allow the caller to handle the
  55446. ** serial-type and data blob seperately.
  55447. **
  55448. ** The following table describes the various storage classes for data:
  55449. **
  55450. ** serial type bytes of data type
  55451. ** -------------- --------------- ---------------
  55452. ** 0 0 NULL
  55453. ** 1 1 signed integer
  55454. ** 2 2 signed integer
  55455. ** 3 3 signed integer
  55456. ** 4 4 signed integer
  55457. ** 5 6 signed integer
  55458. ** 6 8 signed integer
  55459. ** 7 8 IEEE float
  55460. ** 8 0 Integer constant 0
  55461. ** 9 0 Integer constant 1
  55462. ** 10,11 reserved for expansion
  55463. ** N>=12 and even (N-12)/2 BLOB
  55464. ** N>=13 and odd (N-13)/2 text
  55465. **
  55466. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  55467. ** of SQLite will not understand those serial types.
  55468. */
  55469. /*
  55470. ** Return the serial-type for the value stored in pMem.
  55471. */
  55472. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  55473. int flags = pMem->flags;
  55474. int n;
  55475. if( flags&MEM_Null ){
  55476. return 0;
  55477. }
  55478. if( flags&MEM_Int ){
  55479. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  55480. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  55481. i64 i = pMem->u.i;
  55482. u64 u;
  55483. if( file_format>=4 && (i&1)==i ){
  55484. return 8+(u32)i;
  55485. }
  55486. if( i<0 ){
  55487. if( i<(-MAX_6BYTE) ) return 6;
  55488. /* Previous test prevents: u = -(-9223372036854775808) */
  55489. u = -i;
  55490. }else{
  55491. u = i;
  55492. }
  55493. if( u<=127 ) return 1;
  55494. if( u<=32767 ) return 2;
  55495. if( u<=8388607 ) return 3;
  55496. if( u<=2147483647 ) return 4;
  55497. if( u<=MAX_6BYTE ) return 5;
  55498. return 6;
  55499. }
  55500. if( flags&MEM_Real ){
  55501. return 7;
  55502. }
  55503. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  55504. n = pMem->n;
  55505. if( flags & MEM_Zero ){
  55506. n += pMem->u.nZero;
  55507. }
  55508. assert( n>=0 );
  55509. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  55510. }
  55511. /*
  55512. ** Return the length of the data corresponding to the supplied serial-type.
  55513. */
  55514. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  55515. if( serial_type>=12 ){
  55516. return (serial_type-12)/2;
  55517. }else{
  55518. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  55519. return aSize[serial_type];
  55520. }
  55521. }
  55522. /*
  55523. ** If we are on an architecture with mixed-endian floating
  55524. ** points (ex: ARM7) then swap the lower 4 bytes with the
  55525. ** upper 4 bytes. Return the result.
  55526. **
  55527. ** For most architectures, this is a no-op.
  55528. **
  55529. ** (later): It is reported to me that the mixed-endian problem
  55530. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  55531. ** that early versions of GCC stored the two words of a 64-bit
  55532. ** float in the wrong order. And that error has been propagated
  55533. ** ever since. The blame is not necessarily with GCC, though.
  55534. ** GCC might have just copying the problem from a prior compiler.
  55535. ** I am also told that newer versions of GCC that follow a different
  55536. ** ABI get the byte order right.
  55537. **
  55538. ** Developers using SQLite on an ARM7 should compile and run their
  55539. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  55540. ** enabled, some asserts below will ensure that the byte order of
  55541. ** floating point values is correct.
  55542. **
  55543. ** (2007-08-30) Frank van Vugt has studied this problem closely
  55544. ** and has send his findings to the SQLite developers. Frank
  55545. ** writes that some Linux kernels offer floating point hardware
  55546. ** emulation that uses only 32-bit mantissas instead of a full
  55547. ** 48-bits as required by the IEEE standard. (This is the
  55548. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  55549. ** byte swapping becomes very complicated. To avoid problems,
  55550. ** the necessary byte swapping is carried out using a 64-bit integer
  55551. ** rather than a 64-bit float. Frank assures us that the code here
  55552. ** works for him. We, the developers, have no way to independently
  55553. ** verify this, but Frank seems to know what he is talking about
  55554. ** so we trust him.
  55555. */
  55556. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  55557. static u64 floatSwap(u64 in){
  55558. union {
  55559. u64 r;
  55560. u32 i[2];
  55561. } u;
  55562. u32 t;
  55563. u.r = in;
  55564. t = u.i[0];
  55565. u.i[0] = u.i[1];
  55566. u.i[1] = t;
  55567. return u.r;
  55568. }
  55569. # define swapMixedEndianFloat(X) X = floatSwap(X)
  55570. #else
  55571. # define swapMixedEndianFloat(X)
  55572. #endif
  55573. /*
  55574. ** Write the serialized data blob for the value stored in pMem into
  55575. ** buf. It is assumed that the caller has allocated sufficient space.
  55576. ** Return the number of bytes written.
  55577. **
  55578. ** nBuf is the amount of space left in buf[]. nBuf must always be
  55579. ** large enough to hold the entire field. Except, if the field is
  55580. ** a blob with a zero-filled tail, then buf[] might be just the right
  55581. ** size to hold everything except for the zero-filled tail. If buf[]
  55582. ** is only big enough to hold the non-zero prefix, then only write that
  55583. ** prefix into buf[]. But if buf[] is large enough to hold both the
  55584. ** prefix and the tail then write the prefix and set the tail to all
  55585. ** zeros.
  55586. **
  55587. ** Return the number of bytes actually written into buf[]. The number
  55588. ** of bytes in the zero-filled tail is included in the return value only
  55589. ** if those bytes were zeroed in buf[].
  55590. */
  55591. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  55592. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  55593. u32 len;
  55594. /* Integer and Real */
  55595. if( serial_type<=7 && serial_type>0 ){
  55596. u64 v;
  55597. u32 i;
  55598. if( serial_type==7 ){
  55599. assert( sizeof(v)==sizeof(pMem->r) );
  55600. memcpy(&v, &pMem->r, sizeof(v));
  55601. swapMixedEndianFloat(v);
  55602. }else{
  55603. v = pMem->u.i;
  55604. }
  55605. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  55606. assert( len<=(u32)nBuf );
  55607. while( i-- ){
  55608. buf[i] = (u8)(v&0xFF);
  55609. v >>= 8;
  55610. }
  55611. return len;
  55612. }
  55613. /* String or blob */
  55614. if( serial_type>=12 ){
  55615. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  55616. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  55617. assert( pMem->n<=nBuf );
  55618. len = pMem->n;
  55619. memcpy(buf, pMem->z, len);
  55620. if( pMem->flags & MEM_Zero ){
  55621. len += pMem->u.nZero;
  55622. assert( nBuf>=0 );
  55623. if( len > (u32)nBuf ){
  55624. len = (u32)nBuf;
  55625. }
  55626. memset(&buf[pMem->n], 0, len-pMem->n);
  55627. }
  55628. return len;
  55629. }
  55630. /* NULL or constants 0 or 1 */
  55631. return 0;
  55632. }
  55633. /*
  55634. ** Deserialize the data blob pointed to by buf as serial type serial_type
  55635. ** and store the result in pMem. Return the number of bytes read.
  55636. */
  55637. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  55638. const unsigned char *buf, /* Buffer to deserialize from */
  55639. u32 serial_type, /* Serial type to deserialize */
  55640. Mem *pMem /* Memory cell to write value into */
  55641. ){
  55642. switch( serial_type ){
  55643. case 10: /* Reserved for future use */
  55644. case 11: /* Reserved for future use */
  55645. case 0: { /* NULL */
  55646. pMem->flags = MEM_Null;
  55647. break;
  55648. }
  55649. case 1: { /* 1-byte signed integer */
  55650. pMem->u.i = (signed char)buf[0];
  55651. pMem->flags = MEM_Int;
  55652. return 1;
  55653. }
  55654. case 2: { /* 2-byte signed integer */
  55655. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  55656. pMem->flags = MEM_Int;
  55657. return 2;
  55658. }
  55659. case 3: { /* 3-byte signed integer */
  55660. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  55661. pMem->flags = MEM_Int;
  55662. return 3;
  55663. }
  55664. case 4: { /* 4-byte signed integer */
  55665. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  55666. pMem->flags = MEM_Int;
  55667. return 4;
  55668. }
  55669. case 5: { /* 6-byte signed integer */
  55670. u64 x = (((signed char)buf[0])<<8) | buf[1];
  55671. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  55672. x = (x<<32) | y;
  55673. pMem->u.i = *(i64*)&x;
  55674. pMem->flags = MEM_Int;
  55675. return 6;
  55676. }
  55677. case 6: /* 8-byte signed integer */
  55678. case 7: { /* IEEE floating point */
  55679. u64 x;
  55680. u32 y;
  55681. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  55682. /* Verify that integers and floating point values use the same
  55683. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  55684. ** defined that 64-bit floating point values really are mixed
  55685. ** endian.
  55686. */
  55687. static const u64 t1 = ((u64)0x3ff00000)<<32;
  55688. static const double r1 = 1.0;
  55689. u64 t2 = t1;
  55690. swapMixedEndianFloat(t2);
  55691. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  55692. #endif
  55693. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  55694. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  55695. x = (x<<32) | y;
  55696. if( serial_type==6 ){
  55697. pMem->u.i = *(i64*)&x;
  55698. pMem->flags = MEM_Int;
  55699. }else{
  55700. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  55701. swapMixedEndianFloat(x);
  55702. memcpy(&pMem->r, &x, sizeof(x));
  55703. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  55704. }
  55705. return 8;
  55706. }
  55707. case 8: /* Integer 0 */
  55708. case 9: { /* Integer 1 */
  55709. pMem->u.i = serial_type-8;
  55710. pMem->flags = MEM_Int;
  55711. return 0;
  55712. }
  55713. default: {
  55714. u32 len = (serial_type-12)/2;
  55715. pMem->z = (char *)buf;
  55716. pMem->n = len;
  55717. pMem->xDel = 0;
  55718. if( serial_type&0x01 ){
  55719. pMem->flags = MEM_Str | MEM_Ephem;
  55720. }else{
  55721. pMem->flags = MEM_Blob | MEM_Ephem;
  55722. }
  55723. return len;
  55724. }
  55725. }
  55726. return 0;
  55727. }
  55728. /*
  55729. ** Given the nKey-byte encoding of a record in pKey[], parse the
  55730. ** record into a UnpackedRecord structure. Return a pointer to
  55731. ** that structure.
  55732. **
  55733. ** The calling function might provide szSpace bytes of memory
  55734. ** space at pSpace. This space can be used to hold the returned
  55735. ** VDbeParsedRecord structure if it is large enough. If it is
  55736. ** not big enough, space is obtained from sqlite3_malloc().
  55737. **
  55738. ** The returned structure should be closed by a call to
  55739. ** sqlite3VdbeDeleteUnpackedRecord().
  55740. */
  55741. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
  55742. KeyInfo *pKeyInfo, /* Information about the record format */
  55743. int nKey, /* Size of the binary record */
  55744. const void *pKey, /* The binary record */
  55745. char *pSpace, /* Unaligned space available to hold the object */
  55746. int szSpace /* Size of pSpace[] in bytes */
  55747. ){
  55748. const unsigned char *aKey = (const unsigned char *)pKey;
  55749. UnpackedRecord *p; /* The unpacked record that we will return */
  55750. int nByte; /* Memory space needed to hold p, in bytes */
  55751. int d;
  55752. u32 idx;
  55753. u16 u; /* Unsigned loop counter */
  55754. u32 szHdr;
  55755. Mem *pMem;
  55756. int nOff; /* Increase pSpace by this much to 8-byte align it */
  55757. /*
  55758. ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
  55759. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  55760. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  55761. */
  55762. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  55763. pSpace += nOff;
  55764. szSpace -= nOff;
  55765. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  55766. if( nByte>szSpace ){
  55767. p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  55768. if( p==0 ) return 0;
  55769. p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
  55770. }else{
  55771. p = (UnpackedRecord*)pSpace;
  55772. p->flags = UNPACKED_NEED_DESTROY;
  55773. }
  55774. p->pKeyInfo = pKeyInfo;
  55775. p->nField = pKeyInfo->nField + 1;
  55776. p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  55777. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  55778. idx = getVarint32(aKey, szHdr);
  55779. d = szHdr;
  55780. u = 0;
  55781. while( idx<szHdr && u<p->nField && d<=nKey ){
  55782. u32 serial_type;
  55783. idx += getVarint32(&aKey[idx], serial_type);
  55784. pMem->enc = pKeyInfo->enc;
  55785. pMem->db = pKeyInfo->db;
  55786. pMem->flags = 0;
  55787. pMem->zMalloc = 0;
  55788. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  55789. pMem++;
  55790. u++;
  55791. }
  55792. assert( u<=pKeyInfo->nField + 1 );
  55793. p->nField = u;
  55794. return (void*)p;
  55795. }
  55796. /*
  55797. ** This routine destroys a UnpackedRecord object.
  55798. */
  55799. SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
  55800. int i;
  55801. Mem *pMem;
  55802. assert( p!=0 );
  55803. assert( p->flags & UNPACKED_NEED_DESTROY );
  55804. for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
  55805. /* The unpacked record is always constructed by the
  55806. ** sqlite3VdbeUnpackRecord() function above, which makes all
  55807. ** strings and blobs static. And none of the elements are
  55808. ** ever transformed, so there is never anything to delete.
  55809. */
  55810. if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
  55811. }
  55812. if( p->flags & UNPACKED_NEED_FREE ){
  55813. sqlite3DbFree(p->pKeyInfo->db, p);
  55814. }
  55815. }
  55816. /*
  55817. ** This function compares the two table rows or index records
  55818. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  55819. ** or positive integer if key1 is less than, equal to or
  55820. ** greater than key2. The {nKey1, pKey1} key must be a blob
  55821. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  55822. ** key must be a parsed key such as obtained from
  55823. ** sqlite3VdbeParseRecord.
  55824. **
  55825. ** Key1 and Key2 do not have to contain the same number of fields.
  55826. ** The key with fewer fields is usually compares less than the
  55827. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  55828. ** and the common prefixes are equal, then key1 is less than key2.
  55829. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  55830. ** equal, then the keys are considered to be equal and
  55831. ** the parts beyond the common prefix are ignored.
  55832. **
  55833. ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
  55834. ** the header of pKey1 is ignored. It is assumed that pKey1 is
  55835. ** an index key, and thus ends with a rowid value. The last byte
  55836. ** of the header will therefore be the serial type of the rowid:
  55837. ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
  55838. ** The serial type of the final rowid will always be a single byte.
  55839. ** By ignoring this last byte of the header, we force the comparison
  55840. ** to ignore the rowid at the end of key1.
  55841. */
  55842. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  55843. int nKey1, const void *pKey1, /* Left key */
  55844. UnpackedRecord *pPKey2 /* Right key */
  55845. ){
  55846. int d1; /* Offset into aKey[] of next data element */
  55847. u32 idx1; /* Offset into aKey[] of next header element */
  55848. u32 szHdr1; /* Number of bytes in header */
  55849. int i = 0;
  55850. int nField;
  55851. int rc = 0;
  55852. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  55853. KeyInfo *pKeyInfo;
  55854. Mem mem1;
  55855. pKeyInfo = pPKey2->pKeyInfo;
  55856. mem1.enc = pKeyInfo->enc;
  55857. mem1.db = pKeyInfo->db;
  55858. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  55859. VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
  55860. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  55861. ** We could initialize it, as shown here, to silence those complaints.
  55862. ** But in fact, mem1.u.i will never actually be used initialized, and doing
  55863. ** the unnecessary initialization has a measurable negative performance
  55864. ** impact, since this routine is a very high runner. And so, we choose
  55865. ** to ignore the compiler warnings and leave this variable uninitialized.
  55866. */
  55867. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  55868. idx1 = getVarint32(aKey1, szHdr1);
  55869. d1 = szHdr1;
  55870. if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
  55871. szHdr1--;
  55872. }
  55873. nField = pKeyInfo->nField;
  55874. while( idx1<szHdr1 && i<pPKey2->nField ){
  55875. u32 serial_type1;
  55876. /* Read the serial types for the next element in each key. */
  55877. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  55878. if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
  55879. /* Extract the values to be compared.
  55880. */
  55881. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  55882. /* Do the comparison
  55883. */
  55884. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  55885. i<nField ? pKeyInfo->aColl[i] : 0);
  55886. if( rc!=0 ){
  55887. assert( mem1.zMalloc==0 ); /* See comment below */
  55888. /* Invert the result if we are using DESC sort order. */
  55889. if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
  55890. rc = -rc;
  55891. }
  55892. /* If the PREFIX_SEARCH flag is set and all fields except the final
  55893. ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
  55894. ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  55895. ** This is used by the OP_IsUnique opcode.
  55896. */
  55897. if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
  55898. assert( idx1==szHdr1 && rc );
  55899. assert( mem1.flags & MEM_Int );
  55900. pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
  55901. pPKey2->rowid = mem1.u.i;
  55902. }
  55903. return rc;
  55904. }
  55905. i++;
  55906. }
  55907. /* No memory allocation is ever used on mem1. Prove this using
  55908. ** the following assert(). If the assert() fails, it indicates a
  55909. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  55910. */
  55911. assert( mem1.zMalloc==0 );
  55912. /* rc==0 here means that one of the keys ran out of fields and
  55913. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  55914. ** flag is set, then break the tie by treating key2 as larger.
  55915. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  55916. ** are considered to be equal. Otherwise, the longer key is the
  55917. ** larger. As it happens, the pPKey2 will always be the longer
  55918. ** if there is a difference.
  55919. */
  55920. assert( rc==0 );
  55921. if( pPKey2->flags & UNPACKED_INCRKEY ){
  55922. rc = -1;
  55923. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  55924. /* Leave rc==0 */
  55925. }else if( idx1<szHdr1 ){
  55926. rc = 1;
  55927. }
  55928. return rc;
  55929. }
  55930. /*
  55931. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  55932. ** Read the rowid (the last field in the record) and store it in *rowid.
  55933. ** Return SQLITE_OK if everything works, or an error code otherwise.
  55934. **
  55935. ** pCur might be pointing to text obtained from a corrupt database file.
  55936. ** So the content cannot be trusted. Do appropriate checks on the content.
  55937. */
  55938. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  55939. i64 nCellKey = 0;
  55940. int rc;
  55941. u32 szHdr; /* Size of the header */
  55942. u32 typeRowid; /* Serial type of the rowid */
  55943. u32 lenRowid; /* Size of the rowid */
  55944. Mem m, v;
  55945. UNUSED_PARAMETER(db);
  55946. /* Get the size of the index entry. Only indices entries of less
  55947. ** than 2GiB are support - anything large must be database corruption.
  55948. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  55949. ** this code can safely assume that nCellKey is 32-bits
  55950. */
  55951. assert( sqlite3BtreeCursorIsValid(pCur) );
  55952. rc = sqlite3BtreeKeySize(pCur, &nCellKey);
  55953. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  55954. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  55955. /* Read in the complete content of the index entry */
  55956. memset(&m, 0, sizeof(m));
  55957. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  55958. if( rc ){
  55959. return rc;
  55960. }
  55961. /* The index entry must begin with a header size */
  55962. (void)getVarint32((u8*)m.z, szHdr);
  55963. testcase( szHdr==3 );
  55964. testcase( szHdr==m.n );
  55965. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  55966. goto idx_rowid_corruption;
  55967. }
  55968. /* The last field of the index should be an integer - the ROWID.
  55969. ** Verify that the last entry really is an integer. */
  55970. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  55971. testcase( typeRowid==1 );
  55972. testcase( typeRowid==2 );
  55973. testcase( typeRowid==3 );
  55974. testcase( typeRowid==4 );
  55975. testcase( typeRowid==5 );
  55976. testcase( typeRowid==6 );
  55977. testcase( typeRowid==8 );
  55978. testcase( typeRowid==9 );
  55979. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  55980. goto idx_rowid_corruption;
  55981. }
  55982. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  55983. testcase( (u32)m.n==szHdr+lenRowid );
  55984. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  55985. goto idx_rowid_corruption;
  55986. }
  55987. /* Fetch the integer off the end of the index record */
  55988. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  55989. *rowid = v.u.i;
  55990. sqlite3VdbeMemRelease(&m);
  55991. return SQLITE_OK;
  55992. /* Jump here if database corruption is detected after m has been
  55993. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  55994. idx_rowid_corruption:
  55995. testcase( m.zMalloc!=0 );
  55996. sqlite3VdbeMemRelease(&m);
  55997. return SQLITE_CORRUPT_BKPT;
  55998. }
  55999. /*
  56000. ** Compare the key of the index entry that cursor pC is pointing to against
  56001. ** the key string in pUnpacked. Write into *pRes a number
  56002. ** that is negative, zero, or positive if pC is less than, equal to,
  56003. ** or greater than pUnpacked. Return SQLITE_OK on success.
  56004. **
  56005. ** pUnpacked is either created without a rowid or is truncated so that it
  56006. ** omits the rowid at the end. The rowid at the end of the index entry
  56007. ** is ignored as well. Hence, this routine only compares the prefixes
  56008. ** of the keys prior to the final rowid, not the entire key.
  56009. */
  56010. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  56011. VdbeCursor *pC, /* The cursor to compare against */
  56012. UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
  56013. int *res /* Write the comparison result here */
  56014. ){
  56015. i64 nCellKey = 0;
  56016. int rc;
  56017. BtCursor *pCur = pC->pCursor;
  56018. Mem m;
  56019. assert( sqlite3BtreeCursorIsValid(pCur) );
  56020. rc = sqlite3BtreeKeySize(pCur, &nCellKey);
  56021. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  56022. /* nCellKey will always be between 0 and 0xffffffff because of the say
  56023. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  56024. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  56025. *res = 0;
  56026. return SQLITE_CORRUPT_BKPT;
  56027. }
  56028. memset(&m, 0, sizeof(m));
  56029. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  56030. if( rc ){
  56031. return rc;
  56032. }
  56033. assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
  56034. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  56035. sqlite3VdbeMemRelease(&m);
  56036. return SQLITE_OK;
  56037. }
  56038. /*
  56039. ** This routine sets the value to be returned by subsequent calls to
  56040. ** sqlite3_changes() on the database handle 'db'.
  56041. */
  56042. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  56043. assert( sqlite3_mutex_held(db->mutex) );
  56044. db->nChange = nChange;
  56045. db->nTotalChange += nChange;
  56046. }
  56047. /*
  56048. ** Set a flag in the vdbe to update the change counter when it is finalised
  56049. ** or reset.
  56050. */
  56051. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  56052. v->changeCntOn = 1;
  56053. }
  56054. /*
  56055. ** Mark every prepared statement associated with a database connection
  56056. ** as expired.
  56057. **
  56058. ** An expired statement means that recompilation of the statement is
  56059. ** recommend. Statements expire when things happen that make their
  56060. ** programs obsolete. Removing user-defined functions or collating
  56061. ** sequences, or changing an authorization function are the types of
  56062. ** things that make prepared statements obsolete.
  56063. */
  56064. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  56065. Vdbe *p;
  56066. for(p = db->pVdbe; p; p=p->pNext){
  56067. p->expired = 1;
  56068. }
  56069. }
  56070. /*
  56071. ** Return the database associated with the Vdbe.
  56072. */
  56073. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  56074. return v->db;
  56075. }
  56076. /*
  56077. ** Return a pointer to an sqlite3_value structure containing the value bound
  56078. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  56079. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  56080. ** constants) to the value before returning it.
  56081. **
  56082. ** The returned value must be freed by the caller using sqlite3ValueFree().
  56083. */
  56084. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
  56085. assert( iVar>0 );
  56086. if( v ){
  56087. Mem *pMem = &v->aVar[iVar-1];
  56088. if( 0==(pMem->flags & MEM_Null) ){
  56089. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  56090. if( pRet ){
  56091. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  56092. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  56093. sqlite3VdbeMemStoreType((Mem *)pRet);
  56094. }
  56095. return pRet;
  56096. }
  56097. }
  56098. return 0;
  56099. }
  56100. /*
  56101. ** Configure SQL variable iVar so that binding a new value to it signals
  56102. ** to sqlite3_reoptimize() that re-preparing the statement may result
  56103. ** in a better query plan.
  56104. */
  56105. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  56106. assert( iVar>0 );
  56107. if( iVar>32 ){
  56108. v->expmask = 0xffffffff;
  56109. }else{
  56110. v->expmask |= ((u32)1 << (iVar-1));
  56111. }
  56112. }
  56113. /************** End of vdbeaux.c *********************************************/
  56114. /************** Begin file vdbeapi.c *****************************************/
  56115. /*
  56116. ** 2004 May 26
  56117. **
  56118. ** The author disclaims copyright to this source code. In place of
  56119. ** a legal notice, here is a blessing:
  56120. **
  56121. ** May you do good and not evil.
  56122. ** May you find forgiveness for yourself and forgive others.
  56123. ** May you share freely, never taking more than you give.
  56124. **
  56125. *************************************************************************
  56126. **
  56127. ** This file contains code use to implement APIs that are part of the
  56128. ** VDBE.
  56129. */
  56130. #ifndef SQLITE_OMIT_DEPRECATED
  56131. /*
  56132. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  56133. ** to be recompiled. A statement needs to be recompiled whenever the
  56134. ** execution environment changes in a way that would alter the program
  56135. ** that sqlite3_prepare() generates. For example, if new functions or
  56136. ** collating sequences are registered or if an authorizer function is
  56137. ** added or changed.
  56138. */
  56139. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  56140. Vdbe *p = (Vdbe*)pStmt;
  56141. return p==0 || p->expired;
  56142. }
  56143. #endif
  56144. /*
  56145. ** Check on a Vdbe to make sure it has not been finalized. Log
  56146. ** an error and return true if it has been finalized (or is otherwise
  56147. ** invalid). Return false if it is ok.
  56148. */
  56149. static int vdbeSafety(Vdbe *p){
  56150. if( p->db==0 ){
  56151. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  56152. return 1;
  56153. }else{
  56154. return 0;
  56155. }
  56156. }
  56157. static int vdbeSafetyNotNull(Vdbe *p){
  56158. if( p==0 ){
  56159. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  56160. return 1;
  56161. }else{
  56162. return vdbeSafety(p);
  56163. }
  56164. }
  56165. /*
  56166. ** The following routine destroys a virtual machine that is created by
  56167. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  56168. ** success/failure code that describes the result of executing the virtual
  56169. ** machine.
  56170. **
  56171. ** This routine sets the error code and string returned by
  56172. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  56173. */
  56174. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  56175. int rc;
  56176. if( pStmt==0 ){
  56177. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  56178. ** pointer is a harmless no-op. */
  56179. rc = SQLITE_OK;
  56180. }else{
  56181. Vdbe *v = (Vdbe*)pStmt;
  56182. sqlite3 *db = v->db;
  56183. #if SQLITE_THREADSAFE
  56184. sqlite3_mutex *mutex;
  56185. #endif
  56186. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  56187. #if SQLITE_THREADSAFE
  56188. mutex = v->db->mutex;
  56189. #endif
  56190. sqlite3_mutex_enter(mutex);
  56191. rc = sqlite3VdbeFinalize(v);
  56192. rc = sqlite3ApiExit(db, rc);
  56193. sqlite3_mutex_leave(mutex);
  56194. }
  56195. return rc;
  56196. }
  56197. /*
  56198. ** Terminate the current execution of an SQL statement and reset it
  56199. ** back to its starting state so that it can be reused. A success code from
  56200. ** the prior execution is returned.
  56201. **
  56202. ** This routine sets the error code and string returned by
  56203. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  56204. */
  56205. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  56206. int rc;
  56207. if( pStmt==0 ){
  56208. rc = SQLITE_OK;
  56209. }else{
  56210. Vdbe *v = (Vdbe*)pStmt;
  56211. sqlite3_mutex_enter(v->db->mutex);
  56212. rc = sqlite3VdbeReset(v);
  56213. sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
  56214. assert( (rc & (v->db->errMask))==rc );
  56215. rc = sqlite3ApiExit(v->db, rc);
  56216. sqlite3_mutex_leave(v->db->mutex);
  56217. }
  56218. return rc;
  56219. }
  56220. /*
  56221. ** Set all the parameters in the compiled SQL statement to NULL.
  56222. */
  56223. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  56224. int i;
  56225. int rc = SQLITE_OK;
  56226. Vdbe *p = (Vdbe*)pStmt;
  56227. #if SQLITE_THREADSAFE
  56228. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  56229. #endif
  56230. sqlite3_mutex_enter(mutex);
  56231. for(i=0; i<p->nVar; i++){
  56232. sqlite3VdbeMemRelease(&p->aVar[i]);
  56233. p->aVar[i].flags = MEM_Null;
  56234. }
  56235. if( p->isPrepareV2 && p->expmask ){
  56236. p->expired = 1;
  56237. }
  56238. sqlite3_mutex_leave(mutex);
  56239. return rc;
  56240. }
  56241. /**************************** sqlite3_value_ *******************************
  56242. ** The following routines extract information from a Mem or sqlite3_value
  56243. ** structure.
  56244. */
  56245. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  56246. Mem *p = (Mem*)pVal;
  56247. if( p->flags & (MEM_Blob|MEM_Str) ){
  56248. sqlite3VdbeMemExpandBlob(p);
  56249. p->flags &= ~MEM_Str;
  56250. p->flags |= MEM_Blob;
  56251. return p->n ? p->z : 0;
  56252. }else{
  56253. return sqlite3_value_text(pVal);
  56254. }
  56255. }
  56256. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  56257. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  56258. }
  56259. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  56260. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  56261. }
  56262. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  56263. return sqlite3VdbeRealValue((Mem*)pVal);
  56264. }
  56265. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  56266. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  56267. }
  56268. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  56269. return sqlite3VdbeIntValue((Mem*)pVal);
  56270. }
  56271. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  56272. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  56273. }
  56274. #ifndef SQLITE_OMIT_UTF16
  56275. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  56276. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  56277. }
  56278. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  56279. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  56280. }
  56281. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  56282. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  56283. }
  56284. #endif /* SQLITE_OMIT_UTF16 */
  56285. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  56286. return pVal->type;
  56287. }
  56288. /**************************** sqlite3_result_ *******************************
  56289. ** The following routines are used by user-defined functions to specify
  56290. ** the function result.
  56291. **
  56292. ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
  56293. ** result as a string or blob but if the string or blob is too large, it
  56294. ** then sets the error code to SQLITE_TOOBIG
  56295. */
  56296. static void setResultStrOrError(
  56297. sqlite3_context *pCtx, /* Function context */
  56298. const char *z, /* String pointer */
  56299. int n, /* Bytes in string, or negative */
  56300. u8 enc, /* Encoding of z. 0 for BLOBs */
  56301. void (*xDel)(void*) /* Destructor function */
  56302. ){
  56303. if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
  56304. sqlite3_result_error_toobig(pCtx);
  56305. }
  56306. }
  56307. SQLITE_API void sqlite3_result_blob(
  56308. sqlite3_context *pCtx,
  56309. const void *z,
  56310. int n,
  56311. void (*xDel)(void *)
  56312. ){
  56313. assert( n>=0 );
  56314. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56315. setResultStrOrError(pCtx, z, n, 0, xDel);
  56316. }
  56317. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  56318. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56319. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  56320. }
  56321. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  56322. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56323. pCtx->isError = SQLITE_ERROR;
  56324. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  56325. }
  56326. #ifndef SQLITE_OMIT_UTF16
  56327. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  56328. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56329. pCtx->isError = SQLITE_ERROR;
  56330. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  56331. }
  56332. #endif
  56333. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  56334. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56335. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  56336. }
  56337. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  56338. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56339. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  56340. }
  56341. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  56342. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56343. sqlite3VdbeMemSetNull(&pCtx->s);
  56344. }
  56345. SQLITE_API void sqlite3_result_text(
  56346. sqlite3_context *pCtx,
  56347. const char *z,
  56348. int n,
  56349. void (*xDel)(void *)
  56350. ){
  56351. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56352. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  56353. }
  56354. #ifndef SQLITE_OMIT_UTF16
  56355. SQLITE_API void sqlite3_result_text16(
  56356. sqlite3_context *pCtx,
  56357. const void *z,
  56358. int n,
  56359. void (*xDel)(void *)
  56360. ){
  56361. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56362. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  56363. }
  56364. SQLITE_API void sqlite3_result_text16be(
  56365. sqlite3_context *pCtx,
  56366. const void *z,
  56367. int n,
  56368. void (*xDel)(void *)
  56369. ){
  56370. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56371. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  56372. }
  56373. SQLITE_API void sqlite3_result_text16le(
  56374. sqlite3_context *pCtx,
  56375. const void *z,
  56376. int n,
  56377. void (*xDel)(void *)
  56378. ){
  56379. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56380. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  56381. }
  56382. #endif /* SQLITE_OMIT_UTF16 */
  56383. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  56384. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56385. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  56386. }
  56387. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  56388. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56389. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  56390. }
  56391. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  56392. pCtx->isError = errCode;
  56393. if( pCtx->s.flags & MEM_Null ){
  56394. sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
  56395. SQLITE_UTF8, SQLITE_STATIC);
  56396. }
  56397. }
  56398. /* Force an SQLITE_TOOBIG error. */
  56399. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  56400. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56401. pCtx->isError = SQLITE_TOOBIG;
  56402. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  56403. SQLITE_UTF8, SQLITE_STATIC);
  56404. }
  56405. /* An SQLITE_NOMEM error. */
  56406. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  56407. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56408. sqlite3VdbeMemSetNull(&pCtx->s);
  56409. pCtx->isError = SQLITE_NOMEM;
  56410. pCtx->s.db->mallocFailed = 1;
  56411. }
  56412. /*
  56413. ** This function is called after a transaction has been committed. It
  56414. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  56415. */
  56416. static int doWalCallbacks(sqlite3 *db){
  56417. int rc = SQLITE_OK;
  56418. #ifndef SQLITE_OMIT_WAL
  56419. int i;
  56420. for(i=0; i<db->nDb; i++){
  56421. Btree *pBt = db->aDb[i].pBt;
  56422. if( pBt ){
  56423. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  56424. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  56425. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  56426. }
  56427. }
  56428. }
  56429. #endif
  56430. return rc;
  56431. }
  56432. /*
  56433. ** Execute the statement pStmt, either until a row of data is ready, the
  56434. ** statement is completely executed or an error occurs.
  56435. **
  56436. ** This routine implements the bulk of the logic behind the sqlite_step()
  56437. ** API. The only thing omitted is the automatic recompile if a
  56438. ** schema change has occurred. That detail is handled by the
  56439. ** outer sqlite3_step() wrapper procedure.
  56440. */
  56441. static int sqlite3Step(Vdbe *p){
  56442. sqlite3 *db;
  56443. int rc;
  56444. assert(p);
  56445. if( p->magic!=VDBE_MAGIC_RUN ){
  56446. /* We used to require that sqlite3_reset() be called before retrying
  56447. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  56448. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  56449. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  56450. ** This "automatic-reset" change is not technically an incompatibility,
  56451. ** since any application that receives an SQLITE_MISUSE is broken by
  56452. ** definition.
  56453. **
  56454. ** Nevertheless, some published applications that were originally written
  56455. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  56456. ** returns, and the so were broken by the automatic-reset change. As a
  56457. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  56458. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  56459. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  56460. ** or SQLITE_BUSY error.
  56461. */
  56462. #ifdef SQLITE_OMIT_AUTORESET
  56463. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  56464. sqlite3_reset((sqlite3_stmt*)p);
  56465. }else{
  56466. return SQLITE_MISUSE_BKPT;
  56467. }
  56468. #else
  56469. sqlite3_reset((sqlite3_stmt*)p);
  56470. #endif
  56471. }
  56472. /* Check that malloc() has not failed. If it has, return early. */
  56473. db = p->db;
  56474. if( db->mallocFailed ){
  56475. p->rc = SQLITE_NOMEM;
  56476. return SQLITE_NOMEM;
  56477. }
  56478. if( p->pc<=0 && p->expired ){
  56479. p->rc = SQLITE_SCHEMA;
  56480. rc = SQLITE_ERROR;
  56481. goto end_of_step;
  56482. }
  56483. if( p->pc<0 ){
  56484. /* If there are no other statements currently running, then
  56485. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  56486. ** from interrupting a statement that has not yet started.
  56487. */
  56488. if( db->activeVdbeCnt==0 ){
  56489. db->u1.isInterrupted = 0;
  56490. }
  56491. assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
  56492. #ifndef SQLITE_OMIT_TRACE
  56493. if( db->xProfile && !db->init.busy ){
  56494. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  56495. }
  56496. #endif
  56497. db->activeVdbeCnt++;
  56498. if( p->readOnly==0 ) db->writeVdbeCnt++;
  56499. p->pc = 0;
  56500. }
  56501. #ifndef SQLITE_OMIT_EXPLAIN
  56502. if( p->explain ){
  56503. rc = sqlite3VdbeList(p);
  56504. }else
  56505. #endif /* SQLITE_OMIT_EXPLAIN */
  56506. {
  56507. db->vdbeExecCnt++;
  56508. rc = sqlite3VdbeExec(p);
  56509. db->vdbeExecCnt--;
  56510. }
  56511. #ifndef SQLITE_OMIT_TRACE
  56512. /* Invoke the profile callback if there is one
  56513. */
  56514. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  56515. sqlite3_int64 iNow;
  56516. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  56517. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  56518. }
  56519. #endif
  56520. if( rc==SQLITE_DONE ){
  56521. assert( p->rc==SQLITE_OK );
  56522. p->rc = doWalCallbacks(db);
  56523. if( p->rc!=SQLITE_OK ){
  56524. rc = SQLITE_ERROR;
  56525. }
  56526. }
  56527. db->errCode = rc;
  56528. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  56529. p->rc = SQLITE_NOMEM;
  56530. }
  56531. end_of_step:
  56532. /* At this point local variable rc holds the value that should be
  56533. ** returned if this statement was compiled using the legacy
  56534. ** sqlite3_prepare() interface. According to the docs, this can only
  56535. ** be one of the values in the first assert() below. Variable p->rc
  56536. ** contains the value that would be returned if sqlite3_finalize()
  56537. ** were called on statement p.
  56538. */
  56539. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  56540. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  56541. );
  56542. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  56543. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  56544. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  56545. ** error has occured, then return the error code in p->rc to the
  56546. ** caller. Set the error code in the database handle to the same value.
  56547. */
  56548. rc = db->errCode = p->rc;
  56549. }
  56550. return (rc&db->errMask);
  56551. }
  56552. /*
  56553. ** This is the top-level implementation of sqlite3_step(). Call
  56554. ** sqlite3Step() to do most of the work. If a schema error occurs,
  56555. ** call sqlite3Reprepare() and try again.
  56556. */
  56557. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  56558. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  56559. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  56560. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  56561. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  56562. sqlite3 *db; /* The database connection */
  56563. if( vdbeSafetyNotNull(v) ){
  56564. return SQLITE_MISUSE_BKPT;
  56565. }
  56566. db = v->db;
  56567. sqlite3_mutex_enter(db->mutex);
  56568. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  56569. && cnt++ < 5
  56570. && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
  56571. sqlite3_reset(pStmt);
  56572. v->expired = 0;
  56573. }
  56574. if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  56575. /* This case occurs after failing to recompile an sql statement.
  56576. ** The error message from the SQL compiler has already been loaded
  56577. ** into the database handle. This block copies the error message
  56578. ** from the database handle into the statement and sets the statement
  56579. ** program counter to 0 to ensure that when the statement is
  56580. ** finalized or reset the parser error message is available via
  56581. ** sqlite3_errmsg() and sqlite3_errcode().
  56582. */
  56583. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  56584. sqlite3DbFree(db, v->zErrMsg);
  56585. if( !db->mallocFailed ){
  56586. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  56587. v->rc = rc2;
  56588. } else {
  56589. v->zErrMsg = 0;
  56590. v->rc = rc = SQLITE_NOMEM;
  56591. }
  56592. }
  56593. rc = sqlite3ApiExit(db, rc);
  56594. sqlite3_mutex_leave(db->mutex);
  56595. return rc;
  56596. }
  56597. /*
  56598. ** Extract the user data from a sqlite3_context structure and return a
  56599. ** pointer to it.
  56600. */
  56601. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  56602. assert( p && p->pFunc );
  56603. return p->pFunc->pUserData;
  56604. }
  56605. /*
  56606. ** Extract the user data from a sqlite3_context structure and return a
  56607. ** pointer to it.
  56608. **
  56609. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  56610. ** returns a copy of the pointer to the database connection (the 1st
  56611. ** parameter) of the sqlite3_create_function() and
  56612. ** sqlite3_create_function16() routines that originally registered the
  56613. ** application defined function.
  56614. */
  56615. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  56616. assert( p && p->pFunc );
  56617. return p->s.db;
  56618. }
  56619. /*
  56620. ** The following is the implementation of an SQL function that always
  56621. ** fails with an error message stating that the function is used in the
  56622. ** wrong context. The sqlite3_overload_function() API might construct
  56623. ** SQL function that use this routine so that the functions will exist
  56624. ** for name resolution but are actually overloaded by the xFindFunction
  56625. ** method of virtual tables.
  56626. */
  56627. SQLITE_PRIVATE void sqlite3InvalidFunction(
  56628. sqlite3_context *context, /* The function calling context */
  56629. int NotUsed, /* Number of arguments to the function */
  56630. sqlite3_value **NotUsed2 /* Value of each argument */
  56631. ){
  56632. const char *zName = context->pFunc->zName;
  56633. char *zErr;
  56634. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  56635. zErr = sqlite3_mprintf(
  56636. "unable to use function %s in the requested context", zName);
  56637. sqlite3_result_error(context, zErr, -1);
  56638. sqlite3_free(zErr);
  56639. }
  56640. /*
  56641. ** Allocate or return the aggregate context for a user function. A new
  56642. ** context is allocated on the first call. Subsequent calls return the
  56643. ** same context that was returned on prior calls.
  56644. */
  56645. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  56646. Mem *pMem;
  56647. assert( p && p->pFunc && p->pFunc->xStep );
  56648. assert( sqlite3_mutex_held(p->s.db->mutex) );
  56649. pMem = p->pMem;
  56650. testcase( nByte<0 );
  56651. if( (pMem->flags & MEM_Agg)==0 ){
  56652. if( nByte<=0 ){
  56653. sqlite3VdbeMemReleaseExternal(pMem);
  56654. pMem->flags = MEM_Null;
  56655. pMem->z = 0;
  56656. }else{
  56657. sqlite3VdbeMemGrow(pMem, nByte, 0);
  56658. pMem->flags = MEM_Agg;
  56659. pMem->u.pDef = p->pFunc;
  56660. if( pMem->z ){
  56661. memset(pMem->z, 0, nByte);
  56662. }
  56663. }
  56664. }
  56665. return (void*)pMem->z;
  56666. }
  56667. /*
  56668. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  56669. ** the user-function defined by pCtx.
  56670. */
  56671. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  56672. VdbeFunc *pVdbeFunc;
  56673. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56674. pVdbeFunc = pCtx->pVdbeFunc;
  56675. if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
  56676. return 0;
  56677. }
  56678. return pVdbeFunc->apAux[iArg].pAux;
  56679. }
  56680. /*
  56681. ** Set the auxilary data pointer and delete function, for the iArg'th
  56682. ** argument to the user-function defined by pCtx. Any previous value is
  56683. ** deleted by calling the delete function specified when it was set.
  56684. */
  56685. SQLITE_API void sqlite3_set_auxdata(
  56686. sqlite3_context *pCtx,
  56687. int iArg,
  56688. void *pAux,
  56689. void (*xDelete)(void*)
  56690. ){
  56691. struct AuxData *pAuxData;
  56692. VdbeFunc *pVdbeFunc;
  56693. if( iArg<0 ) goto failed;
  56694. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  56695. pVdbeFunc = pCtx->pVdbeFunc;
  56696. if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
  56697. int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
  56698. int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
  56699. pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
  56700. if( !pVdbeFunc ){
  56701. goto failed;
  56702. }
  56703. pCtx->pVdbeFunc = pVdbeFunc;
  56704. memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
  56705. pVdbeFunc->nAux = iArg+1;
  56706. pVdbeFunc->pFunc = pCtx->pFunc;
  56707. }
  56708. pAuxData = &pVdbeFunc->apAux[iArg];
  56709. if( pAuxData->pAux && pAuxData->xDelete ){
  56710. pAuxData->xDelete(pAuxData->pAux);
  56711. }
  56712. pAuxData->pAux = pAux;
  56713. pAuxData->xDelete = xDelete;
  56714. return;
  56715. failed:
  56716. if( xDelete ){
  56717. xDelete(pAux);
  56718. }
  56719. }
  56720. #ifndef SQLITE_OMIT_DEPRECATED
  56721. /*
  56722. ** Return the number of times the Step function of a aggregate has been
  56723. ** called.
  56724. **
  56725. ** This function is deprecated. Do not use it for new code. It is
  56726. ** provide only to avoid breaking legacy code. New aggregate function
  56727. ** implementations should keep their own counts within their aggregate
  56728. ** context.
  56729. */
  56730. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  56731. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  56732. return p->pMem->n;
  56733. }
  56734. #endif
  56735. /*
  56736. ** Return the number of columns in the result set for the statement pStmt.
  56737. */
  56738. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  56739. Vdbe *pVm = (Vdbe *)pStmt;
  56740. return pVm ? pVm->nResColumn : 0;
  56741. }
  56742. /*
  56743. ** Return the number of values available from the current row of the
  56744. ** currently executing statement pStmt.
  56745. */
  56746. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  56747. Vdbe *pVm = (Vdbe *)pStmt;
  56748. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  56749. return pVm->nResColumn;
  56750. }
  56751. /*
  56752. ** Check to see if column iCol of the given statement is valid. If
  56753. ** it is, return a pointer to the Mem for the value of that column.
  56754. ** If iCol is not valid, return a pointer to a Mem which has a value
  56755. ** of NULL.
  56756. */
  56757. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  56758. Vdbe *pVm;
  56759. Mem *pOut;
  56760. pVm = (Vdbe *)pStmt;
  56761. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  56762. sqlite3_mutex_enter(pVm->db->mutex);
  56763. pOut = &pVm->pResultSet[i];
  56764. }else{
  56765. /* If the value passed as the second argument is out of range, return
  56766. ** a pointer to the following static Mem object which contains the
  56767. ** value SQL NULL. Even though the Mem structure contains an element
  56768. ** of type i64, on certain architecture (x86) with certain compiler
  56769. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  56770. ** instead of an 8-byte one. This all works fine, except that when
  56771. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  56772. ** that a Mem structure is located on an 8-byte boundary. To prevent
  56773. ** this assert() from failing, when building with SQLITE_DEBUG defined
  56774. ** using gcc, force nullMem to be 8-byte aligned using the magical
  56775. ** __attribute__((aligned(8))) macro. */
  56776. static const Mem nullMem
  56777. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  56778. __attribute__((aligned(8)))
  56779. #endif
  56780. = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
  56781. #ifdef SQLITE_DEBUG
  56782. 0, 0, /* pScopyFrom, pFiller */
  56783. #endif
  56784. 0, 0 };
  56785. if( pVm && ALWAYS(pVm->db) ){
  56786. sqlite3_mutex_enter(pVm->db->mutex);
  56787. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  56788. }
  56789. pOut = (Mem*)&nullMem;
  56790. }
  56791. return pOut;
  56792. }
  56793. /*
  56794. ** This function is called after invoking an sqlite3_value_XXX function on a
  56795. ** column value (i.e. a value returned by evaluating an SQL expression in the
  56796. ** select list of a SELECT statement) that may cause a malloc() failure. If
  56797. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  56798. ** code of statement pStmt set to SQLITE_NOMEM.
  56799. **
  56800. ** Specifically, this is called from within:
  56801. **
  56802. ** sqlite3_column_int()
  56803. ** sqlite3_column_int64()
  56804. ** sqlite3_column_text()
  56805. ** sqlite3_column_text16()
  56806. ** sqlite3_column_real()
  56807. ** sqlite3_column_bytes()
  56808. ** sqlite3_column_bytes16()
  56809. ** sqiite3_column_blob()
  56810. */
  56811. static void columnMallocFailure(sqlite3_stmt *pStmt)
  56812. {
  56813. /* If malloc() failed during an encoding conversion within an
  56814. ** sqlite3_column_XXX API, then set the return code of the statement to
  56815. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  56816. ** and _finalize() will return NOMEM.
  56817. */
  56818. Vdbe *p = (Vdbe *)pStmt;
  56819. if( p ){
  56820. p->rc = sqlite3ApiExit(p->db, p->rc);
  56821. sqlite3_mutex_leave(p->db->mutex);
  56822. }
  56823. }
  56824. /**************************** sqlite3_column_ *******************************
  56825. ** The following routines are used to access elements of the current row
  56826. ** in the result set.
  56827. */
  56828. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  56829. const void *val;
  56830. val = sqlite3_value_blob( columnMem(pStmt,i) );
  56831. /* Even though there is no encoding conversion, value_blob() might
  56832. ** need to call malloc() to expand the result of a zeroblob()
  56833. ** expression.
  56834. */
  56835. columnMallocFailure(pStmt);
  56836. return val;
  56837. }
  56838. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  56839. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  56840. columnMallocFailure(pStmt);
  56841. return val;
  56842. }
  56843. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  56844. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  56845. columnMallocFailure(pStmt);
  56846. return val;
  56847. }
  56848. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  56849. double val = sqlite3_value_double( columnMem(pStmt,i) );
  56850. columnMallocFailure(pStmt);
  56851. return val;
  56852. }
  56853. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  56854. int val = sqlite3_value_int( columnMem(pStmt,i) );
  56855. columnMallocFailure(pStmt);
  56856. return val;
  56857. }
  56858. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  56859. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  56860. columnMallocFailure(pStmt);
  56861. return val;
  56862. }
  56863. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  56864. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  56865. columnMallocFailure(pStmt);
  56866. return val;
  56867. }
  56868. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  56869. Mem *pOut = columnMem(pStmt, i);
  56870. if( pOut->flags&MEM_Static ){
  56871. pOut->flags &= ~MEM_Static;
  56872. pOut->flags |= MEM_Ephem;
  56873. }
  56874. columnMallocFailure(pStmt);
  56875. return (sqlite3_value *)pOut;
  56876. }
  56877. #ifndef SQLITE_OMIT_UTF16
  56878. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  56879. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  56880. columnMallocFailure(pStmt);
  56881. return val;
  56882. }
  56883. #endif /* SQLITE_OMIT_UTF16 */
  56884. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  56885. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  56886. columnMallocFailure(pStmt);
  56887. return iType;
  56888. }
  56889. /* The following function is experimental and subject to change or
  56890. ** removal */
  56891. /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
  56892. ** return sqlite3_value_numeric_type( columnMem(pStmt,i) );
  56893. **}
  56894. */
  56895. /*
  56896. ** Convert the N-th element of pStmt->pColName[] into a string using
  56897. ** xFunc() then return that string. If N is out of range, return 0.
  56898. **
  56899. ** There are up to 5 names for each column. useType determines which
  56900. ** name is returned. Here are the names:
  56901. **
  56902. ** 0 The column name as it should be displayed for output
  56903. ** 1 The datatype name for the column
  56904. ** 2 The name of the database that the column derives from
  56905. ** 3 The name of the table that the column derives from
  56906. ** 4 The name of the table column that the result column derives from
  56907. **
  56908. ** If the result is not a simple column reference (if it is an expression
  56909. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  56910. */
  56911. static const void *columnName(
  56912. sqlite3_stmt *pStmt,
  56913. int N,
  56914. const void *(*xFunc)(Mem*),
  56915. int useType
  56916. ){
  56917. const void *ret = 0;
  56918. Vdbe *p = (Vdbe *)pStmt;
  56919. int n;
  56920. sqlite3 *db = p->db;
  56921. assert( db!=0 );
  56922. n = sqlite3_column_count(pStmt);
  56923. if( N<n && N>=0 ){
  56924. N += useType*n;
  56925. sqlite3_mutex_enter(db->mutex);
  56926. assert( db->mallocFailed==0 );
  56927. ret = xFunc(&p->aColName[N]);
  56928. /* A malloc may have failed inside of the xFunc() call. If this
  56929. ** is the case, clear the mallocFailed flag and return NULL.
  56930. */
  56931. if( db->mallocFailed ){
  56932. db->mallocFailed = 0;
  56933. ret = 0;
  56934. }
  56935. sqlite3_mutex_leave(db->mutex);
  56936. }
  56937. return ret;
  56938. }
  56939. /*
  56940. ** Return the name of the Nth column of the result set returned by SQL
  56941. ** statement pStmt.
  56942. */
  56943. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  56944. return columnName(
  56945. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  56946. }
  56947. #ifndef SQLITE_OMIT_UTF16
  56948. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  56949. return columnName(
  56950. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  56951. }
  56952. #endif
  56953. /*
  56954. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  56955. ** not define OMIT_DECLTYPE.
  56956. */
  56957. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  56958. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  56959. and SQLITE_ENABLE_COLUMN_METADATA"
  56960. #endif
  56961. #ifndef SQLITE_OMIT_DECLTYPE
  56962. /*
  56963. ** Return the column declaration type (if applicable) of the 'i'th column
  56964. ** of the result set of SQL statement pStmt.
  56965. */
  56966. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  56967. return columnName(
  56968. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  56969. }
  56970. #ifndef SQLITE_OMIT_UTF16
  56971. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  56972. return columnName(
  56973. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  56974. }
  56975. #endif /* SQLITE_OMIT_UTF16 */
  56976. #endif /* SQLITE_OMIT_DECLTYPE */
  56977. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  56978. /*
  56979. ** Return the name of the database from which a result column derives.
  56980. ** NULL is returned if the result column is an expression or constant or
  56981. ** anything else which is not an unabiguous reference to a database column.
  56982. */
  56983. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  56984. return columnName(
  56985. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  56986. }
  56987. #ifndef SQLITE_OMIT_UTF16
  56988. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  56989. return columnName(
  56990. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  56991. }
  56992. #endif /* SQLITE_OMIT_UTF16 */
  56993. /*
  56994. ** Return the name of the table from which a result column derives.
  56995. ** NULL is returned if the result column is an expression or constant or
  56996. ** anything else which is not an unabiguous reference to a database column.
  56997. */
  56998. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  56999. return columnName(
  57000. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  57001. }
  57002. #ifndef SQLITE_OMIT_UTF16
  57003. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  57004. return columnName(
  57005. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  57006. }
  57007. #endif /* SQLITE_OMIT_UTF16 */
  57008. /*
  57009. ** Return the name of the table column from which a result column derives.
  57010. ** NULL is returned if the result column is an expression or constant or
  57011. ** anything else which is not an unabiguous reference to a database column.
  57012. */
  57013. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  57014. return columnName(
  57015. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  57016. }
  57017. #ifndef SQLITE_OMIT_UTF16
  57018. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  57019. return columnName(
  57020. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  57021. }
  57022. #endif /* SQLITE_OMIT_UTF16 */
  57023. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  57024. /******************************* sqlite3_bind_ ***************************
  57025. **
  57026. ** Routines used to attach values to wildcards in a compiled SQL statement.
  57027. */
  57028. /*
  57029. ** Unbind the value bound to variable i in virtual machine p. This is the
  57030. ** the same as binding a NULL value to the column. If the "i" parameter is
  57031. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  57032. **
  57033. ** A successful evaluation of this routine acquires the mutex on p.
  57034. ** the mutex is released if any kind of error occurs.
  57035. **
  57036. ** The error code stored in database p->db is overwritten with the return
  57037. ** value in any case.
  57038. */
  57039. static int vdbeUnbind(Vdbe *p, int i){
  57040. Mem *pVar;
  57041. if( vdbeSafetyNotNull(p) ){
  57042. return SQLITE_MISUSE_BKPT;
  57043. }
  57044. sqlite3_mutex_enter(p->db->mutex);
  57045. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  57046. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  57047. sqlite3_mutex_leave(p->db->mutex);
  57048. sqlite3_log(SQLITE_MISUSE,
  57049. "bind on a busy prepared statement: [%s]", p->zSql);
  57050. return SQLITE_MISUSE_BKPT;
  57051. }
  57052. if( i<1 || i>p->nVar ){
  57053. sqlite3Error(p->db, SQLITE_RANGE, 0);
  57054. sqlite3_mutex_leave(p->db->mutex);
  57055. return SQLITE_RANGE;
  57056. }
  57057. i--;
  57058. pVar = &p->aVar[i];
  57059. sqlite3VdbeMemRelease(pVar);
  57060. pVar->flags = MEM_Null;
  57061. sqlite3Error(p->db, SQLITE_OK, 0);
  57062. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  57063. ** binding a new value to this variable invalidates the current query plan.
  57064. **
  57065. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  57066. ** parameter in the WHERE clause might influence the choice of query plan
  57067. ** for a statement, then the statement will be automatically recompiled,
  57068. ** as if there had been a schema change, on the first sqlite3_step() call
  57069. ** following any change to the bindings of that parameter.
  57070. */
  57071. if( p->isPrepareV2 &&
  57072. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  57073. ){
  57074. p->expired = 1;
  57075. }
  57076. return SQLITE_OK;
  57077. }
  57078. /*
  57079. ** Bind a text or BLOB value.
  57080. */
  57081. static int bindText(
  57082. sqlite3_stmt *pStmt, /* The statement to bind against */
  57083. int i, /* Index of the parameter to bind */
  57084. const void *zData, /* Pointer to the data to be bound */
  57085. int nData, /* Number of bytes of data to be bound */
  57086. void (*xDel)(void*), /* Destructor for the data */
  57087. u8 encoding /* Encoding for the data */
  57088. ){
  57089. Vdbe *p = (Vdbe *)pStmt;
  57090. Mem *pVar;
  57091. int rc;
  57092. rc = vdbeUnbind(p, i);
  57093. if( rc==SQLITE_OK ){
  57094. if( zData!=0 ){
  57095. pVar = &p->aVar[i-1];
  57096. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  57097. if( rc==SQLITE_OK && encoding!=0 ){
  57098. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  57099. }
  57100. sqlite3Error(p->db, rc, 0);
  57101. rc = sqlite3ApiExit(p->db, rc);
  57102. }
  57103. sqlite3_mutex_leave(p->db->mutex);
  57104. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  57105. xDel((void*)zData);
  57106. }
  57107. return rc;
  57108. }
  57109. /*
  57110. ** Bind a blob value to an SQL statement variable.
  57111. */
  57112. SQLITE_API int sqlite3_bind_blob(
  57113. sqlite3_stmt *pStmt,
  57114. int i,
  57115. const void *zData,
  57116. int nData,
  57117. void (*xDel)(void*)
  57118. ){
  57119. return bindText(pStmt, i, zData, nData, xDel, 0);
  57120. }
  57121. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  57122. int rc;
  57123. Vdbe *p = (Vdbe *)pStmt;
  57124. rc = vdbeUnbind(p, i);
  57125. if( rc==SQLITE_OK ){
  57126. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  57127. sqlite3_mutex_leave(p->db->mutex);
  57128. }
  57129. return rc;
  57130. }
  57131. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  57132. return sqlite3_bind_int64(p, i, (i64)iValue);
  57133. }
  57134. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  57135. int rc;
  57136. Vdbe *p = (Vdbe *)pStmt;
  57137. rc = vdbeUnbind(p, i);
  57138. if( rc==SQLITE_OK ){
  57139. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  57140. sqlite3_mutex_leave(p->db->mutex);
  57141. }
  57142. return rc;
  57143. }
  57144. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  57145. int rc;
  57146. Vdbe *p = (Vdbe*)pStmt;
  57147. rc = vdbeUnbind(p, i);
  57148. if( rc==SQLITE_OK ){
  57149. sqlite3_mutex_leave(p->db->mutex);
  57150. }
  57151. return rc;
  57152. }
  57153. SQLITE_API int sqlite3_bind_text(
  57154. sqlite3_stmt *pStmt,
  57155. int i,
  57156. const char *zData,
  57157. int nData,
  57158. void (*xDel)(void*)
  57159. ){
  57160. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  57161. }
  57162. #ifndef SQLITE_OMIT_UTF16
  57163. SQLITE_API int sqlite3_bind_text16(
  57164. sqlite3_stmt *pStmt,
  57165. int i,
  57166. const void *zData,
  57167. int nData,
  57168. void (*xDel)(void*)
  57169. ){
  57170. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  57171. }
  57172. #endif /* SQLITE_OMIT_UTF16 */
  57173. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  57174. int rc;
  57175. switch( pValue->type ){
  57176. case SQLITE_INTEGER: {
  57177. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  57178. break;
  57179. }
  57180. case SQLITE_FLOAT: {
  57181. rc = sqlite3_bind_double(pStmt, i, pValue->r);
  57182. break;
  57183. }
  57184. case SQLITE_BLOB: {
  57185. if( pValue->flags & MEM_Zero ){
  57186. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  57187. }else{
  57188. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  57189. }
  57190. break;
  57191. }
  57192. case SQLITE_TEXT: {
  57193. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  57194. pValue->enc);
  57195. break;
  57196. }
  57197. default: {
  57198. rc = sqlite3_bind_null(pStmt, i);
  57199. break;
  57200. }
  57201. }
  57202. return rc;
  57203. }
  57204. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  57205. int rc;
  57206. Vdbe *p = (Vdbe *)pStmt;
  57207. rc = vdbeUnbind(p, i);
  57208. if( rc==SQLITE_OK ){
  57209. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  57210. sqlite3_mutex_leave(p->db->mutex);
  57211. }
  57212. return rc;
  57213. }
  57214. /*
  57215. ** Return the number of wildcards that can be potentially bound to.
  57216. ** This routine is added to support DBD::SQLite.
  57217. */
  57218. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  57219. Vdbe *p = (Vdbe*)pStmt;
  57220. return p ? p->nVar : 0;
  57221. }
  57222. /*
  57223. ** Create a mapping from variable numbers to variable names
  57224. ** in the Vdbe.azVar[] array, if such a mapping does not already
  57225. ** exist.
  57226. */
  57227. static void createVarMap(Vdbe *p){
  57228. if( !p->okVar ){
  57229. int j;
  57230. Op *pOp;
  57231. sqlite3_mutex_enter(p->db->mutex);
  57232. /* The race condition here is harmless. If two threads call this
  57233. ** routine on the same Vdbe at the same time, they both might end
  57234. ** up initializing the Vdbe.azVar[] array. That is a little extra
  57235. ** work but it results in the same answer.
  57236. */
  57237. for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
  57238. if( pOp->opcode==OP_Variable ){
  57239. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  57240. p->azVar[pOp->p1-1] = pOp->p4.z;
  57241. }
  57242. }
  57243. p->okVar = 1;
  57244. sqlite3_mutex_leave(p->db->mutex);
  57245. }
  57246. }
  57247. /*
  57248. ** Return the name of a wildcard parameter. Return NULL if the index
  57249. ** is out of range or if the wildcard is unnamed.
  57250. **
  57251. ** The result is always UTF-8.
  57252. */
  57253. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  57254. Vdbe *p = (Vdbe*)pStmt;
  57255. if( p==0 || i<1 || i>p->nVar ){
  57256. return 0;
  57257. }
  57258. createVarMap(p);
  57259. return p->azVar[i-1];
  57260. }
  57261. /*
  57262. ** Given a wildcard parameter name, return the index of the variable
  57263. ** with that name. If there is no variable with the given name,
  57264. ** return 0.
  57265. */
  57266. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  57267. int i;
  57268. if( p==0 ){
  57269. return 0;
  57270. }
  57271. createVarMap(p);
  57272. if( zName ){
  57273. for(i=0; i<p->nVar; i++){
  57274. const char *z = p->azVar[i];
  57275. if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
  57276. return i+1;
  57277. }
  57278. }
  57279. }
  57280. return 0;
  57281. }
  57282. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  57283. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  57284. }
  57285. /*
  57286. ** Transfer all bindings from the first statement over to the second.
  57287. */
  57288. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  57289. Vdbe *pFrom = (Vdbe*)pFromStmt;
  57290. Vdbe *pTo = (Vdbe*)pToStmt;
  57291. int i;
  57292. assert( pTo->db==pFrom->db );
  57293. assert( pTo->nVar==pFrom->nVar );
  57294. sqlite3_mutex_enter(pTo->db->mutex);
  57295. for(i=0; i<pFrom->nVar; i++){
  57296. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  57297. }
  57298. sqlite3_mutex_leave(pTo->db->mutex);
  57299. return SQLITE_OK;
  57300. }
  57301. #ifndef SQLITE_OMIT_DEPRECATED
  57302. /*
  57303. ** Deprecated external interface. Internal/core SQLite code
  57304. ** should call sqlite3TransferBindings.
  57305. **
  57306. ** Is is misuse to call this routine with statements from different
  57307. ** database connections. But as this is a deprecated interface, we
  57308. ** will not bother to check for that condition.
  57309. **
  57310. ** If the two statements contain a different number of bindings, then
  57311. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  57312. ** SQLITE_OK is returned.
  57313. */
  57314. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  57315. Vdbe *pFrom = (Vdbe*)pFromStmt;
  57316. Vdbe *pTo = (Vdbe*)pToStmt;
  57317. if( pFrom->nVar!=pTo->nVar ){
  57318. return SQLITE_ERROR;
  57319. }
  57320. if( pTo->isPrepareV2 && pTo->expmask ){
  57321. pTo->expired = 1;
  57322. }
  57323. if( pFrom->isPrepareV2 && pFrom->expmask ){
  57324. pFrom->expired = 1;
  57325. }
  57326. return sqlite3TransferBindings(pFromStmt, pToStmt);
  57327. }
  57328. #endif
  57329. /*
  57330. ** Return the sqlite3* database handle to which the prepared statement given
  57331. ** in the argument belongs. This is the same database handle that was
  57332. ** the first argument to the sqlite3_prepare() that was used to create
  57333. ** the statement in the first place.
  57334. */
  57335. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  57336. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  57337. }
  57338. /*
  57339. ** Return true if the prepared statement is guaranteed to not modify the
  57340. ** database.
  57341. */
  57342. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  57343. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  57344. }
  57345. /*
  57346. ** Return a pointer to the next prepared statement after pStmt associated
  57347. ** with database connection pDb. If pStmt is NULL, return the first
  57348. ** prepared statement for the database connection. Return NULL if there
  57349. ** are no more.
  57350. */
  57351. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  57352. sqlite3_stmt *pNext;
  57353. sqlite3_mutex_enter(pDb->mutex);
  57354. if( pStmt==0 ){
  57355. pNext = (sqlite3_stmt*)pDb->pVdbe;
  57356. }else{
  57357. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  57358. }
  57359. sqlite3_mutex_leave(pDb->mutex);
  57360. return pNext;
  57361. }
  57362. /*
  57363. ** Return the value of a status counter for a prepared statement
  57364. */
  57365. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  57366. Vdbe *pVdbe = (Vdbe*)pStmt;
  57367. int v = pVdbe->aCounter[op-1];
  57368. if( resetFlag ) pVdbe->aCounter[op-1] = 0;
  57369. return v;
  57370. }
  57371. /************** End of vdbeapi.c *********************************************/
  57372. /************** Begin file vdbetrace.c ***************************************/
  57373. /*
  57374. ** 2009 November 25
  57375. **
  57376. ** The author disclaims copyright to this source code. In place of
  57377. ** a legal notice, here is a blessing:
  57378. **
  57379. ** May you do good and not evil.
  57380. ** May you find forgiveness for yourself and forgive others.
  57381. ** May you share freely, never taking more than you give.
  57382. **
  57383. *************************************************************************
  57384. **
  57385. ** This file contains code used to insert the values of host parameters
  57386. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  57387. */
  57388. #ifndef SQLITE_OMIT_TRACE
  57389. /*
  57390. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  57391. ** bytes in this text up to but excluding the first character in
  57392. ** a host parameter. If the text contains no host parameters, return
  57393. ** the total number of bytes in the text.
  57394. */
  57395. static int findNextHostParameter(const char *zSql, int *pnToken){
  57396. int tokenType;
  57397. int nTotal = 0;
  57398. int n;
  57399. *pnToken = 0;
  57400. while( zSql[0] ){
  57401. n = sqlite3GetToken((u8*)zSql, &tokenType);
  57402. assert( n>0 && tokenType!=TK_ILLEGAL );
  57403. if( tokenType==TK_VARIABLE ){
  57404. *pnToken = n;
  57405. break;
  57406. }
  57407. nTotal += n;
  57408. zSql += n;
  57409. }
  57410. return nTotal;
  57411. }
  57412. /*
  57413. ** This function returns a pointer to a nul-terminated string in memory
  57414. ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
  57415. ** string contains a copy of zRawSql but with host parameters expanded to
  57416. ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
  57417. ** then the returned string holds a copy of zRawSql with "-- " prepended
  57418. ** to each line of text.
  57419. **
  57420. ** The calling function is responsible for making sure the memory returned
  57421. ** is eventually freed.
  57422. **
  57423. ** ALGORITHM: Scan the input string looking for host parameters in any of
  57424. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  57425. ** string literals, quoted identifier names, and comments. For text forms,
  57426. ** the host parameter index is found by scanning the perpared
  57427. ** statement for the corresponding OP_Variable opcode. Once the host
  57428. ** parameter index is known, locate the value in p->aVar[]. Then render
  57429. ** the value as a literal in place of the host parameter name.
  57430. */
  57431. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  57432. Vdbe *p, /* The prepared statement being evaluated */
  57433. const char *zRawSql /* Raw text of the SQL statement */
  57434. ){
  57435. sqlite3 *db; /* The database connection */
  57436. int idx = 0; /* Index of a host parameter */
  57437. int nextIndex = 1; /* Index of next ? host parameter */
  57438. int n; /* Length of a token prefix */
  57439. int nToken; /* Length of the parameter token */
  57440. int i; /* Loop counter */
  57441. Mem *pVar; /* Value of a host parameter */
  57442. StrAccum out; /* Accumulate the output here */
  57443. char zBase[100]; /* Initial working space */
  57444. db = p->db;
  57445. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  57446. db->aLimit[SQLITE_LIMIT_LENGTH]);
  57447. out.db = db;
  57448. if( db->vdbeExecCnt>1 ){
  57449. while( *zRawSql ){
  57450. const char *zStart = zRawSql;
  57451. while( *(zRawSql++)!='\n' && *zRawSql );
  57452. sqlite3StrAccumAppend(&out, "-- ", 3);
  57453. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  57454. }
  57455. }else{
  57456. while( zRawSql[0] ){
  57457. n = findNextHostParameter(zRawSql, &nToken);
  57458. assert( n>0 );
  57459. sqlite3StrAccumAppend(&out, zRawSql, n);
  57460. zRawSql += n;
  57461. assert( zRawSql[0] || nToken==0 );
  57462. if( nToken==0 ) break;
  57463. if( zRawSql[0]=='?' ){
  57464. if( nToken>1 ){
  57465. assert( sqlite3Isdigit(zRawSql[1]) );
  57466. sqlite3GetInt32(&zRawSql[1], &idx);
  57467. }else{
  57468. idx = nextIndex;
  57469. }
  57470. }else{
  57471. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  57472. testcase( zRawSql[0]==':' );
  57473. testcase( zRawSql[0]=='$' );
  57474. testcase( zRawSql[0]=='@' );
  57475. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  57476. assert( idx>0 );
  57477. }
  57478. zRawSql += nToken;
  57479. nextIndex = idx + 1;
  57480. assert( idx>0 && idx<=p->nVar );
  57481. pVar = &p->aVar[idx-1];
  57482. if( pVar->flags & MEM_Null ){
  57483. sqlite3StrAccumAppend(&out, "NULL", 4);
  57484. }else if( pVar->flags & MEM_Int ){
  57485. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  57486. }else if( pVar->flags & MEM_Real ){
  57487. sqlite3XPrintf(&out, "%!.15g", pVar->r);
  57488. }else if( pVar->flags & MEM_Str ){
  57489. #ifndef SQLITE_OMIT_UTF16
  57490. u8 enc = ENC(db);
  57491. if( enc!=SQLITE_UTF8 ){
  57492. Mem utf8;
  57493. memset(&utf8, 0, sizeof(utf8));
  57494. utf8.db = db;
  57495. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  57496. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  57497. sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
  57498. sqlite3VdbeMemRelease(&utf8);
  57499. }else
  57500. #endif
  57501. {
  57502. sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
  57503. }
  57504. }else if( pVar->flags & MEM_Zero ){
  57505. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  57506. }else{
  57507. assert( pVar->flags & MEM_Blob );
  57508. sqlite3StrAccumAppend(&out, "x'", 2);
  57509. for(i=0; i<pVar->n; i++){
  57510. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  57511. }
  57512. sqlite3StrAccumAppend(&out, "'", 1);
  57513. }
  57514. }
  57515. }
  57516. return sqlite3StrAccumFinish(&out);
  57517. }
  57518. #endif /* #ifndef SQLITE_OMIT_TRACE */
  57519. /************** End of vdbetrace.c *******************************************/
  57520. /************** Begin file vdbe.c ********************************************/
  57521. /*
  57522. ** 2001 September 15
  57523. **
  57524. ** The author disclaims copyright to this source code. In place of
  57525. ** a legal notice, here is a blessing:
  57526. **
  57527. ** May you do good and not evil.
  57528. ** May you find forgiveness for yourself and forgive others.
  57529. ** May you share freely, never taking more than you give.
  57530. **
  57531. *************************************************************************
  57532. ** The code in this file implements execution method of the
  57533. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  57534. ** handles housekeeping details such as creating and deleting
  57535. ** VDBE instances. This file is solely interested in executing
  57536. ** the VDBE program.
  57537. **
  57538. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  57539. ** to a VDBE.
  57540. **
  57541. ** The SQL parser generates a program which is then executed by
  57542. ** the VDBE to do the work of the SQL statement. VDBE programs are
  57543. ** similar in form to assembly language. The program consists of
  57544. ** a linear sequence of operations. Each operation has an opcode
  57545. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  57546. ** is a null-terminated string. Operand P5 is an unsigned character.
  57547. ** Few opcodes use all 5 operands.
  57548. **
  57549. ** Computation results are stored on a set of registers numbered beginning
  57550. ** with 1 and going up to Vdbe.nMem. Each register can store
  57551. ** either an integer, a null-terminated string, a floating point
  57552. ** number, or the SQL "NULL" value. An implicit conversion from one
  57553. ** type to the other occurs as necessary.
  57554. **
  57555. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  57556. ** function which does the work of interpreting a VDBE program.
  57557. ** But other routines are also provided to help in building up
  57558. ** a program instruction by instruction.
  57559. **
  57560. ** Various scripts scan this source file in order to generate HTML
  57561. ** documentation, headers files, or other derived files. The formatting
  57562. ** of the code in this file is, therefore, important. See other comments
  57563. ** in this file for details. If in doubt, do not deviate from existing
  57564. ** commenting and indentation practices when changing or adding code.
  57565. */
  57566. /*
  57567. ** Invoke this macro on memory cells just prior to changing the
  57568. ** value of the cell. This macro verifies that shallow copies are
  57569. ** not misused.
  57570. */
  57571. #ifdef SQLITE_DEBUG
  57572. # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
  57573. #else
  57574. # define memAboutToChange(P,M)
  57575. #endif
  57576. /*
  57577. ** The following global variable is incremented every time a cursor
  57578. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  57579. ** procedures use this information to make sure that indices are
  57580. ** working correctly. This variable has no function other than to
  57581. ** help verify the correct operation of the library.
  57582. */
  57583. #ifdef SQLITE_TEST
  57584. SQLITE_API int sqlite3_search_count = 0;
  57585. #endif
  57586. /*
  57587. ** When this global variable is positive, it gets decremented once before
  57588. ** each instruction in the VDBE. When reaches zero, the u1.isInterrupted
  57589. ** field of the sqlite3 structure is set in order to simulate and interrupt.
  57590. **
  57591. ** This facility is used for testing purposes only. It does not function
  57592. ** in an ordinary build.
  57593. */
  57594. #ifdef SQLITE_TEST
  57595. SQLITE_API int sqlite3_interrupt_count = 0;
  57596. #endif
  57597. /*
  57598. ** The next global variable is incremented each type the OP_Sort opcode
  57599. ** is executed. The test procedures use this information to make sure that
  57600. ** sorting is occurring or not occurring at appropriate times. This variable
  57601. ** has no function other than to help verify the correct operation of the
  57602. ** library.
  57603. */
  57604. #ifdef SQLITE_TEST
  57605. SQLITE_API int sqlite3_sort_count = 0;
  57606. #endif
  57607. /*
  57608. ** The next global variable records the size of the largest MEM_Blob
  57609. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  57610. ** use this information to make sure that the zero-blob functionality
  57611. ** is working correctly. This variable has no function other than to
  57612. ** help verify the correct operation of the library.
  57613. */
  57614. #ifdef SQLITE_TEST
  57615. SQLITE_API int sqlite3_max_blobsize = 0;
  57616. static void updateMaxBlobsize(Mem *p){
  57617. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  57618. sqlite3_max_blobsize = p->n;
  57619. }
  57620. }
  57621. #endif
  57622. /*
  57623. ** The next global variable is incremented each type the OP_Found opcode
  57624. ** is executed. This is used to test whether or not the foreign key
  57625. ** operation implemented using OP_FkIsZero is working. This variable
  57626. ** has no function other than to help verify the correct operation of the
  57627. ** library.
  57628. */
  57629. #ifdef SQLITE_TEST
  57630. SQLITE_API int sqlite3_found_count = 0;
  57631. #endif
  57632. /*
  57633. ** Test a register to see if it exceeds the current maximum blob size.
  57634. ** If it does, record the new maximum blob size.
  57635. */
  57636. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  57637. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  57638. #else
  57639. # define UPDATE_MAX_BLOBSIZE(P)
  57640. #endif
  57641. /*
  57642. ** Convert the given register into a string if it isn't one
  57643. ** already. Return non-zero if a malloc() fails.
  57644. */
  57645. #define Stringify(P, enc) \
  57646. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  57647. { goto no_mem; }
  57648. /*
  57649. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  57650. ** a pointer to a dynamically allocated string where some other entity
  57651. ** is responsible for deallocating that string. Because the register
  57652. ** does not control the string, it might be deleted without the register
  57653. ** knowing it.
  57654. **
  57655. ** This routine converts an ephemeral string into a dynamically allocated
  57656. ** string that the register itself controls. In other words, it
  57657. ** converts an MEM_Ephem string into an MEM_Dyn string.
  57658. */
  57659. #define Deephemeralize(P) \
  57660. if( ((P)->flags&MEM_Ephem)!=0 \
  57661. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  57662. /*
  57663. ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
  57664. ** P if required.
  57665. */
  57666. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  57667. /*
  57668. ** Argument pMem points at a register that will be passed to a
  57669. ** user-defined function or returned to the user as the result of a query.
  57670. ** This routine sets the pMem->type variable used by the sqlite3_value_*()
  57671. ** routines.
  57672. */
  57673. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
  57674. int flags = pMem->flags;
  57675. if( flags & MEM_Null ){
  57676. pMem->type = SQLITE_NULL;
  57677. }
  57678. else if( flags & MEM_Int ){
  57679. pMem->type = SQLITE_INTEGER;
  57680. }
  57681. else if( flags & MEM_Real ){
  57682. pMem->type = SQLITE_FLOAT;
  57683. }
  57684. else if( flags & MEM_Str ){
  57685. pMem->type = SQLITE_TEXT;
  57686. }else{
  57687. pMem->type = SQLITE_BLOB;
  57688. }
  57689. }
  57690. /*
  57691. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  57692. ** if we run out of memory.
  57693. */
  57694. static VdbeCursor *allocateCursor(
  57695. Vdbe *p, /* The virtual machine */
  57696. int iCur, /* Index of the new VdbeCursor */
  57697. int nField, /* Number of fields in the table or index */
  57698. int iDb, /* When database the cursor belongs to, or -1 */
  57699. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  57700. ){
  57701. /* Find the memory cell that will be used to store the blob of memory
  57702. ** required for this VdbeCursor structure. It is convenient to use a
  57703. ** vdbe memory cell to manage the memory allocation required for a
  57704. ** VdbeCursor structure for the following reasons:
  57705. **
  57706. ** * Sometimes cursor numbers are used for a couple of different
  57707. ** purposes in a vdbe program. The different uses might require
  57708. ** different sized allocations. Memory cells provide growable
  57709. ** allocations.
  57710. **
  57711. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  57712. ** be freed lazily via the sqlite3_release_memory() API. This
  57713. ** minimizes the number of malloc calls made by the system.
  57714. **
  57715. ** Memory cells for cursors are allocated at the top of the address
  57716. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  57717. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  57718. */
  57719. Mem *pMem = &p->aMem[p->nMem-iCur];
  57720. int nByte;
  57721. VdbeCursor *pCx = 0;
  57722. nByte =
  57723. ROUND8(sizeof(VdbeCursor)) +
  57724. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  57725. 2*nField*sizeof(u32);
  57726. assert( iCur<p->nCursor );
  57727. if( p->apCsr[iCur] ){
  57728. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  57729. p->apCsr[iCur] = 0;
  57730. }
  57731. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  57732. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  57733. memset(pCx, 0, sizeof(VdbeCursor));
  57734. pCx->iDb = iDb;
  57735. pCx->nField = nField;
  57736. if( nField ){
  57737. pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
  57738. }
  57739. if( isBtreeCursor ){
  57740. pCx->pCursor = (BtCursor*)
  57741. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
  57742. sqlite3BtreeCursorZero(pCx->pCursor);
  57743. }
  57744. }
  57745. return pCx;
  57746. }
  57747. /*
  57748. ** Try to convert a value into a numeric representation if we can
  57749. ** do so without loss of information. In other words, if the string
  57750. ** looks like a number, convert it into a number. If it does not
  57751. ** look like a number, leave it alone.
  57752. */
  57753. static void applyNumericAffinity(Mem *pRec){
  57754. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  57755. double rValue;
  57756. i64 iValue;
  57757. u8 enc = pRec->enc;
  57758. if( (pRec->flags&MEM_Str)==0 ) return;
  57759. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  57760. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  57761. pRec->u.i = iValue;
  57762. pRec->flags |= MEM_Int;
  57763. }else{
  57764. pRec->r = rValue;
  57765. pRec->flags |= MEM_Real;
  57766. }
  57767. }
  57768. }
  57769. /*
  57770. ** Processing is determine by the affinity parameter:
  57771. **
  57772. ** SQLITE_AFF_INTEGER:
  57773. ** SQLITE_AFF_REAL:
  57774. ** SQLITE_AFF_NUMERIC:
  57775. ** Try to convert pRec to an integer representation or a
  57776. ** floating-point representation if an integer representation
  57777. ** is not possible. Note that the integer representation is
  57778. ** always preferred, even if the affinity is REAL, because
  57779. ** an integer representation is more space efficient on disk.
  57780. **
  57781. ** SQLITE_AFF_TEXT:
  57782. ** Convert pRec to a text representation.
  57783. **
  57784. ** SQLITE_AFF_NONE:
  57785. ** No-op. pRec is unchanged.
  57786. */
  57787. static void applyAffinity(
  57788. Mem *pRec, /* The value to apply affinity to */
  57789. char affinity, /* The affinity to be applied */
  57790. u8 enc /* Use this text encoding */
  57791. ){
  57792. if( affinity==SQLITE_AFF_TEXT ){
  57793. /* Only attempt the conversion to TEXT if there is an integer or real
  57794. ** representation (blob and NULL do not get converted) but no string
  57795. ** representation.
  57796. */
  57797. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  57798. sqlite3VdbeMemStringify(pRec, enc);
  57799. }
  57800. pRec->flags &= ~(MEM_Real|MEM_Int);
  57801. }else if( affinity!=SQLITE_AFF_NONE ){
  57802. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  57803. || affinity==SQLITE_AFF_NUMERIC );
  57804. applyNumericAffinity(pRec);
  57805. if( pRec->flags & MEM_Real ){
  57806. sqlite3VdbeIntegerAffinity(pRec);
  57807. }
  57808. }
  57809. }
  57810. /*
  57811. ** Try to convert the type of a function argument or a result column
  57812. ** into a numeric representation. Use either INTEGER or REAL whichever
  57813. ** is appropriate. But only do the conversion if it is possible without
  57814. ** loss of information and return the revised type of the argument.
  57815. */
  57816. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  57817. Mem *pMem = (Mem*)pVal;
  57818. if( pMem->type==SQLITE_TEXT ){
  57819. applyNumericAffinity(pMem);
  57820. sqlite3VdbeMemStoreType(pMem);
  57821. }
  57822. return pMem->type;
  57823. }
  57824. /*
  57825. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  57826. ** not the internal Mem* type.
  57827. */
  57828. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  57829. sqlite3_value *pVal,
  57830. u8 affinity,
  57831. u8 enc
  57832. ){
  57833. applyAffinity((Mem *)pVal, affinity, enc);
  57834. }
  57835. #ifdef SQLITE_DEBUG
  57836. /*
  57837. ** Write a nice string representation of the contents of cell pMem
  57838. ** into buffer zBuf, length nBuf.
  57839. */
  57840. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  57841. char *zCsr = zBuf;
  57842. int f = pMem->flags;
  57843. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  57844. if( f&MEM_Blob ){
  57845. int i;
  57846. char c;
  57847. if( f & MEM_Dyn ){
  57848. c = 'z';
  57849. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  57850. }else if( f & MEM_Static ){
  57851. c = 't';
  57852. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  57853. }else if( f & MEM_Ephem ){
  57854. c = 'e';
  57855. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  57856. }else{
  57857. c = 's';
  57858. }
  57859. sqlite3_snprintf(100, zCsr, "%c", c);
  57860. zCsr += sqlite3Strlen30(zCsr);
  57861. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  57862. zCsr += sqlite3Strlen30(zCsr);
  57863. for(i=0; i<16 && i<pMem->n; i++){
  57864. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  57865. zCsr += sqlite3Strlen30(zCsr);
  57866. }
  57867. for(i=0; i<16 && i<pMem->n; i++){
  57868. char z = pMem->z[i];
  57869. if( z<32 || z>126 ) *zCsr++ = '.';
  57870. else *zCsr++ = z;
  57871. }
  57872. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  57873. zCsr += sqlite3Strlen30(zCsr);
  57874. if( f & MEM_Zero ){
  57875. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  57876. zCsr += sqlite3Strlen30(zCsr);
  57877. }
  57878. *zCsr = '\0';
  57879. }else if( f & MEM_Str ){
  57880. int j, k;
  57881. zBuf[0] = ' ';
  57882. if( f & MEM_Dyn ){
  57883. zBuf[1] = 'z';
  57884. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  57885. }else if( f & MEM_Static ){
  57886. zBuf[1] = 't';
  57887. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  57888. }else if( f & MEM_Ephem ){
  57889. zBuf[1] = 'e';
  57890. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  57891. }else{
  57892. zBuf[1] = 's';
  57893. }
  57894. k = 2;
  57895. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  57896. k += sqlite3Strlen30(&zBuf[k]);
  57897. zBuf[k++] = '[';
  57898. for(j=0; j<15 && j<pMem->n; j++){
  57899. u8 c = pMem->z[j];
  57900. if( c>=0x20 && c<0x7f ){
  57901. zBuf[k++] = c;
  57902. }else{
  57903. zBuf[k++] = '.';
  57904. }
  57905. }
  57906. zBuf[k++] = ']';
  57907. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  57908. k += sqlite3Strlen30(&zBuf[k]);
  57909. zBuf[k++] = 0;
  57910. }
  57911. }
  57912. #endif
  57913. #ifdef SQLITE_DEBUG
  57914. /*
  57915. ** Print the value of a register for tracing purposes:
  57916. */
  57917. static void memTracePrint(FILE *out, Mem *p){
  57918. if( p->flags & MEM_Null ){
  57919. fprintf(out, " NULL");
  57920. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  57921. fprintf(out, " si:%lld", p->u.i);
  57922. }else if( p->flags & MEM_Int ){
  57923. fprintf(out, " i:%lld", p->u.i);
  57924. #ifndef SQLITE_OMIT_FLOATING_POINT
  57925. }else if( p->flags & MEM_Real ){
  57926. fprintf(out, " r:%g", p->r);
  57927. #endif
  57928. }else if( p->flags & MEM_RowSet ){
  57929. fprintf(out, " (rowset)");
  57930. }else{
  57931. char zBuf[200];
  57932. sqlite3VdbeMemPrettyPrint(p, zBuf);
  57933. fprintf(out, " ");
  57934. fprintf(out, "%s", zBuf);
  57935. }
  57936. }
  57937. static void registerTrace(FILE *out, int iReg, Mem *p){
  57938. fprintf(out, "REG[%d] = ", iReg);
  57939. memTracePrint(out, p);
  57940. fprintf(out, "\n");
  57941. }
  57942. #endif
  57943. #ifdef SQLITE_DEBUG
  57944. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  57945. #else
  57946. # define REGISTER_TRACE(R,M)
  57947. #endif
  57948. #ifdef VDBE_PROFILE
  57949. /*
  57950. ** hwtime.h contains inline assembler code for implementing
  57951. ** high-performance timing routines.
  57952. */
  57953. /************** Include hwtime.h in the middle of vdbe.c *********************/
  57954. /************** Begin file hwtime.h ******************************************/
  57955. /*
  57956. ** 2008 May 27
  57957. **
  57958. ** The author disclaims copyright to this source code. In place of
  57959. ** a legal notice, here is a blessing:
  57960. **
  57961. ** May you do good and not evil.
  57962. ** May you find forgiveness for yourself and forgive others.
  57963. ** May you share freely, never taking more than you give.
  57964. **
  57965. ******************************************************************************
  57966. **
  57967. ** This file contains inline asm code for retrieving "high-performance"
  57968. ** counters for x86 class CPUs.
  57969. */
  57970. #ifndef _HWTIME_H_
  57971. #define _HWTIME_H_
  57972. /*
  57973. ** The following routine only works on pentium-class (or newer) processors.
  57974. ** It uses the RDTSC opcode to read the cycle count value out of the
  57975. ** processor and returns that value. This can be used for high-res
  57976. ** profiling.
  57977. */
  57978. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  57979. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  57980. #if defined(__GNUC__)
  57981. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  57982. unsigned int lo, hi;
  57983. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  57984. return (sqlite_uint64)hi << 32 | lo;
  57985. }
  57986. #elif defined(_MSC_VER)
  57987. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  57988. __asm {
  57989. rdtsc
  57990. ret ; return value at EDX:EAX
  57991. }
  57992. }
  57993. #endif
  57994. #elif (defined(__GNUC__) && defined(__x86_64__))
  57995. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  57996. unsigned long val;
  57997. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  57998. return val;
  57999. }
  58000. #elif (defined(__GNUC__) && defined(__ppc__))
  58001. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  58002. unsigned long long retval;
  58003. unsigned long junk;
  58004. __asm__ __volatile__ ("\n\
  58005. 1: mftbu %1\n\
  58006. mftb %L0\n\
  58007. mftbu %0\n\
  58008. cmpw %0,%1\n\
  58009. bne 1b"
  58010. : "=r" (retval), "=r" (junk));
  58011. return retval;
  58012. }
  58013. #else
  58014. #error Need implementation of sqlite3Hwtime() for your platform.
  58015. /*
  58016. ** To compile without implementing sqlite3Hwtime() for your platform,
  58017. ** you can remove the above #error and use the following
  58018. ** stub function. You will lose timing support for many
  58019. ** of the debugging and testing utilities, but it should at
  58020. ** least compile and run.
  58021. */
  58022. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  58023. #endif
  58024. #endif /* !defined(_HWTIME_H_) */
  58025. /************** End of hwtime.h **********************************************/
  58026. /************** Continuing where we left off in vdbe.c ***********************/
  58027. #endif
  58028. /*
  58029. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  58030. ** sqlite3_interrupt() routine has been called. If it has been, then
  58031. ** processing of the VDBE program is interrupted.
  58032. **
  58033. ** This macro added to every instruction that does a jump in order to
  58034. ** implement a loop. This test used to be on every single instruction,
  58035. ** but that meant we more testing that we needed. By only testing the
  58036. ** flag on jump instructions, we get a (small) speed improvement.
  58037. */
  58038. #define CHECK_FOR_INTERRUPT \
  58039. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  58040. #ifndef NDEBUG
  58041. /*
  58042. ** This function is only called from within an assert() expression. It
  58043. ** checks that the sqlite3.nTransaction variable is correctly set to
  58044. ** the number of non-transaction savepoints currently in the
  58045. ** linked list starting at sqlite3.pSavepoint.
  58046. **
  58047. ** Usage:
  58048. **
  58049. ** assert( checkSavepointCount(db) );
  58050. */
  58051. static int checkSavepointCount(sqlite3 *db){
  58052. int n = 0;
  58053. Savepoint *p;
  58054. for(p=db->pSavepoint; p; p=p->pNext) n++;
  58055. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  58056. return 1;
  58057. }
  58058. #endif
  58059. /*
  58060. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  58061. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  58062. ** in memory obtained from sqlite3DbMalloc).
  58063. */
  58064. static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
  58065. sqlite3 *db = p->db;
  58066. sqlite3DbFree(db, p->zErrMsg);
  58067. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  58068. sqlite3_free(pVtab->zErrMsg);
  58069. pVtab->zErrMsg = 0;
  58070. }
  58071. /*
  58072. ** Execute as much of a VDBE program as we can then return.
  58073. **
  58074. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  58075. ** close the program with a final OP_Halt and to set up the callbacks
  58076. ** and the error message pointer.
  58077. **
  58078. ** Whenever a row or result data is available, this routine will either
  58079. ** invoke the result callback (if there is one) or return with
  58080. ** SQLITE_ROW.
  58081. **
  58082. ** If an attempt is made to open a locked database, then this routine
  58083. ** will either invoke the busy callback (if there is one) or it will
  58084. ** return SQLITE_BUSY.
  58085. **
  58086. ** If an error occurs, an error message is written to memory obtained
  58087. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  58088. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  58089. **
  58090. ** If the callback ever returns non-zero, then the program exits
  58091. ** immediately. There will be no error message but the p->rc field is
  58092. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  58093. **
  58094. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  58095. ** routine to return SQLITE_ERROR.
  58096. **
  58097. ** Other fatal errors return SQLITE_ERROR.
  58098. **
  58099. ** After this routine has finished, sqlite3VdbeFinalize() should be
  58100. ** used to clean up the mess that was left behind.
  58101. */
  58102. SQLITE_PRIVATE int sqlite3VdbeExec(
  58103. Vdbe *p /* The VDBE */
  58104. ){
  58105. int pc=0; /* The program counter */
  58106. Op *aOp = p->aOp; /* Copy of p->aOp */
  58107. Op *pOp; /* Current operation */
  58108. int rc = SQLITE_OK; /* Value to return */
  58109. sqlite3 *db = p->db; /* The database */
  58110. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  58111. u8 encoding = ENC(db); /* The database encoding */
  58112. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  58113. int checkProgress; /* True if progress callbacks are enabled */
  58114. int nProgressOps = 0; /* Opcodes executed since progress callback. */
  58115. #endif
  58116. Mem *aMem = p->aMem; /* Copy of p->aMem */
  58117. Mem *pIn1 = 0; /* 1st input operand */
  58118. Mem *pIn2 = 0; /* 2nd input operand */
  58119. Mem *pIn3 = 0; /* 3rd input operand */
  58120. Mem *pOut = 0; /* Output operand */
  58121. int iCompare = 0; /* Result of last OP_Compare operation */
  58122. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  58123. #ifdef VDBE_PROFILE
  58124. u64 start; /* CPU clock count at start of opcode */
  58125. int origPc; /* Program counter at start of opcode */
  58126. #endif
  58127. /********************************************************************
  58128. ** Automatically generated code
  58129. **
  58130. ** The following union is automatically generated by the
  58131. ** vdbe-compress.tcl script. The purpose of this union is to
  58132. ** reduce the amount of stack space required by this function.
  58133. ** See comments in the vdbe-compress.tcl script for details.
  58134. */
  58135. union vdbeExecUnion {
  58136. struct OP_Yield_stack_vars {
  58137. int pcDest;
  58138. } aa;
  58139. struct OP_Variable_stack_vars {
  58140. Mem *pVar; /* Value being transferred */
  58141. } ab;
  58142. struct OP_Move_stack_vars {
  58143. char *zMalloc; /* Holding variable for allocated memory */
  58144. int n; /* Number of registers left to copy */
  58145. int p1; /* Register to copy from */
  58146. int p2; /* Register to copy to */
  58147. } ac;
  58148. struct OP_ResultRow_stack_vars {
  58149. Mem *pMem;
  58150. int i;
  58151. } ad;
  58152. struct OP_Concat_stack_vars {
  58153. i64 nByte;
  58154. } ae;
  58155. struct OP_Remainder_stack_vars {
  58156. int flags; /* Combined MEM_* flags from both inputs */
  58157. i64 iA; /* Integer value of left operand */
  58158. i64 iB; /* Integer value of right operand */
  58159. double rA; /* Real value of left operand */
  58160. double rB; /* Real value of right operand */
  58161. } af;
  58162. struct OP_Function_stack_vars {
  58163. int i;
  58164. Mem *pArg;
  58165. sqlite3_context ctx;
  58166. sqlite3_value **apVal;
  58167. int n;
  58168. } ag;
  58169. struct OP_ShiftRight_stack_vars {
  58170. i64 iA;
  58171. u64 uA;
  58172. i64 iB;
  58173. u8 op;
  58174. } ah;
  58175. struct OP_Ge_stack_vars {
  58176. int res; /* Result of the comparison of pIn1 against pIn3 */
  58177. char affinity; /* Affinity to use for comparison */
  58178. u16 flags1; /* Copy of initial value of pIn1->flags */
  58179. u16 flags3; /* Copy of initial value of pIn3->flags */
  58180. } ai;
  58181. struct OP_Compare_stack_vars {
  58182. int n;
  58183. int i;
  58184. int p1;
  58185. int p2;
  58186. const KeyInfo *pKeyInfo;
  58187. int idx;
  58188. CollSeq *pColl; /* Collating sequence to use on this term */
  58189. int bRev; /* True for DESCENDING sort order */
  58190. } aj;
  58191. struct OP_Or_stack_vars {
  58192. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  58193. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  58194. } ak;
  58195. struct OP_IfNot_stack_vars {
  58196. int c;
  58197. } al;
  58198. struct OP_Column_stack_vars {
  58199. u32 payloadSize; /* Number of bytes in the record */
  58200. i64 payloadSize64; /* Number of bytes in the record */
  58201. int p1; /* P1 value of the opcode */
  58202. int p2; /* column number to retrieve */
  58203. VdbeCursor *pC; /* The VDBE cursor */
  58204. char *zRec; /* Pointer to complete record-data */
  58205. BtCursor *pCrsr; /* The BTree cursor */
  58206. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  58207. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  58208. int nField; /* number of fields in the record */
  58209. int len; /* The length of the serialized data for the column */
  58210. int i; /* Loop counter */
  58211. char *zData; /* Part of the record being decoded */
  58212. Mem *pDest; /* Where to write the extracted value */
  58213. Mem sMem; /* For storing the record being decoded */
  58214. u8 *zIdx; /* Index into header */
  58215. u8 *zEndHdr; /* Pointer to first byte after the header */
  58216. u32 offset; /* Offset into the data */
  58217. u32 szField; /* Number of bytes in the content of a field */
  58218. int szHdr; /* Size of the header size field at start of record */
  58219. int avail; /* Number of bytes of available data */
  58220. Mem *pReg; /* PseudoTable input register */
  58221. } am;
  58222. struct OP_Affinity_stack_vars {
  58223. const char *zAffinity; /* The affinity to be applied */
  58224. char cAff; /* A single character of affinity */
  58225. } an;
  58226. struct OP_MakeRecord_stack_vars {
  58227. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  58228. Mem *pRec; /* The new record */
  58229. u64 nData; /* Number of bytes of data space */
  58230. int nHdr; /* Number of bytes of header space */
  58231. i64 nByte; /* Data space required for this record */
  58232. int nZero; /* Number of zero bytes at the end of the record */
  58233. int nVarint; /* Number of bytes in a varint */
  58234. u32 serial_type; /* Type field */
  58235. Mem *pData0; /* First field to be combined into the record */
  58236. Mem *pLast; /* Last field of the record */
  58237. int nField; /* Number of fields in the record */
  58238. char *zAffinity; /* The affinity string for the record */
  58239. int file_format; /* File format to use for encoding */
  58240. int i; /* Space used in zNewRecord[] */
  58241. int len; /* Length of a field */
  58242. } ao;
  58243. struct OP_Count_stack_vars {
  58244. i64 nEntry;
  58245. BtCursor *pCrsr;
  58246. } ap;
  58247. struct OP_Savepoint_stack_vars {
  58248. int p1; /* Value of P1 operand */
  58249. char *zName; /* Name of savepoint */
  58250. int nName;
  58251. Savepoint *pNew;
  58252. Savepoint *pSavepoint;
  58253. Savepoint *pTmp;
  58254. int iSavepoint;
  58255. int ii;
  58256. } aq;
  58257. struct OP_AutoCommit_stack_vars {
  58258. int desiredAutoCommit;
  58259. int iRollback;
  58260. int turnOnAC;
  58261. } ar;
  58262. struct OP_Transaction_stack_vars {
  58263. Btree *pBt;
  58264. } as;
  58265. struct OP_ReadCookie_stack_vars {
  58266. int iMeta;
  58267. int iDb;
  58268. int iCookie;
  58269. } at;
  58270. struct OP_SetCookie_stack_vars {
  58271. Db *pDb;
  58272. } au;
  58273. struct OP_VerifyCookie_stack_vars {
  58274. int iMeta;
  58275. int iGen;
  58276. Btree *pBt;
  58277. } av;
  58278. struct OP_OpenWrite_stack_vars {
  58279. int nField;
  58280. KeyInfo *pKeyInfo;
  58281. int p2;
  58282. int iDb;
  58283. int wrFlag;
  58284. Btree *pX;
  58285. VdbeCursor *pCur;
  58286. Db *pDb;
  58287. } aw;
  58288. struct OP_OpenEphemeral_stack_vars {
  58289. VdbeCursor *pCx;
  58290. } ax;
  58291. struct OP_OpenPseudo_stack_vars {
  58292. VdbeCursor *pCx;
  58293. } ay;
  58294. struct OP_SeekGt_stack_vars {
  58295. int res;
  58296. int oc;
  58297. VdbeCursor *pC;
  58298. UnpackedRecord r;
  58299. int nField;
  58300. i64 iKey; /* The rowid we are to seek to */
  58301. } az;
  58302. struct OP_Seek_stack_vars {
  58303. VdbeCursor *pC;
  58304. } ba;
  58305. struct OP_Found_stack_vars {
  58306. int alreadyExists;
  58307. VdbeCursor *pC;
  58308. int res;
  58309. UnpackedRecord *pIdxKey;
  58310. UnpackedRecord r;
  58311. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  58312. } bb;
  58313. struct OP_IsUnique_stack_vars {
  58314. u16 ii;
  58315. VdbeCursor *pCx;
  58316. BtCursor *pCrsr;
  58317. u16 nField;
  58318. Mem *aMx;
  58319. UnpackedRecord r; /* B-Tree index search key */
  58320. i64 R; /* Rowid stored in register P3 */
  58321. } bc;
  58322. struct OP_NotExists_stack_vars {
  58323. VdbeCursor *pC;
  58324. BtCursor *pCrsr;
  58325. int res;
  58326. u64 iKey;
  58327. } bd;
  58328. struct OP_NewRowid_stack_vars {
  58329. i64 v; /* The new rowid */
  58330. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  58331. int res; /* Result of an sqlite3BtreeLast() */
  58332. int cnt; /* Counter to limit the number of searches */
  58333. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  58334. VdbeFrame *pFrame; /* Root frame of VDBE */
  58335. } be;
  58336. struct OP_InsertInt_stack_vars {
  58337. Mem *pData; /* MEM cell holding data for the record to be inserted */
  58338. Mem *pKey; /* MEM cell holding key for the record */
  58339. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  58340. VdbeCursor *pC; /* Cursor to table into which insert is written */
  58341. int nZero; /* Number of zero-bytes to append */
  58342. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  58343. const char *zDb; /* database name - used by the update hook */
  58344. const char *zTbl; /* Table name - used by the opdate hook */
  58345. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  58346. } bf;
  58347. struct OP_Delete_stack_vars {
  58348. i64 iKey;
  58349. VdbeCursor *pC;
  58350. } bg;
  58351. struct OP_RowData_stack_vars {
  58352. VdbeCursor *pC;
  58353. BtCursor *pCrsr;
  58354. u32 n;
  58355. i64 n64;
  58356. } bh;
  58357. struct OP_Rowid_stack_vars {
  58358. VdbeCursor *pC;
  58359. i64 v;
  58360. sqlite3_vtab *pVtab;
  58361. const sqlite3_module *pModule;
  58362. } bi;
  58363. struct OP_NullRow_stack_vars {
  58364. VdbeCursor *pC;
  58365. } bj;
  58366. struct OP_Last_stack_vars {
  58367. VdbeCursor *pC;
  58368. BtCursor *pCrsr;
  58369. int res;
  58370. } bk;
  58371. struct OP_Rewind_stack_vars {
  58372. VdbeCursor *pC;
  58373. BtCursor *pCrsr;
  58374. int res;
  58375. } bl;
  58376. struct OP_Next_stack_vars {
  58377. VdbeCursor *pC;
  58378. BtCursor *pCrsr;
  58379. int res;
  58380. } bm;
  58381. struct OP_IdxInsert_stack_vars {
  58382. VdbeCursor *pC;
  58383. BtCursor *pCrsr;
  58384. int nKey;
  58385. const char *zKey;
  58386. } bn;
  58387. struct OP_IdxDelete_stack_vars {
  58388. VdbeCursor *pC;
  58389. BtCursor *pCrsr;
  58390. int res;
  58391. UnpackedRecord r;
  58392. } bo;
  58393. struct OP_IdxRowid_stack_vars {
  58394. BtCursor *pCrsr;
  58395. VdbeCursor *pC;
  58396. i64 rowid;
  58397. } bp;
  58398. struct OP_IdxGE_stack_vars {
  58399. VdbeCursor *pC;
  58400. int res;
  58401. UnpackedRecord r;
  58402. } bq;
  58403. struct OP_Destroy_stack_vars {
  58404. int iMoved;
  58405. int iCnt;
  58406. Vdbe *pVdbe;
  58407. int iDb;
  58408. } br;
  58409. struct OP_Clear_stack_vars {
  58410. int nChange;
  58411. } bs;
  58412. struct OP_CreateTable_stack_vars {
  58413. int pgno;
  58414. int flags;
  58415. Db *pDb;
  58416. } bt;
  58417. struct OP_ParseSchema_stack_vars {
  58418. int iDb;
  58419. const char *zMaster;
  58420. char *zSql;
  58421. InitData initData;
  58422. } bu;
  58423. struct OP_IntegrityCk_stack_vars {
  58424. int nRoot; /* Number of tables to check. (Number of root pages.) */
  58425. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  58426. int j; /* Loop counter */
  58427. int nErr; /* Number of errors reported */
  58428. char *z; /* Text of the error report */
  58429. Mem *pnErr; /* Register keeping track of errors remaining */
  58430. } bv;
  58431. struct OP_RowSetRead_stack_vars {
  58432. i64 val;
  58433. } bw;
  58434. struct OP_RowSetTest_stack_vars {
  58435. int iSet;
  58436. int exists;
  58437. } bx;
  58438. struct OP_Program_stack_vars {
  58439. int nMem; /* Number of memory registers for sub-program */
  58440. int nByte; /* Bytes of runtime space required for sub-program */
  58441. Mem *pRt; /* Register to allocate runtime space */
  58442. Mem *pMem; /* Used to iterate through memory cells */
  58443. Mem *pEnd; /* Last memory cell in new array */
  58444. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  58445. SubProgram *pProgram; /* Sub-program to execute */
  58446. void *t; /* Token identifying trigger */
  58447. } by;
  58448. struct OP_Param_stack_vars {
  58449. VdbeFrame *pFrame;
  58450. Mem *pIn;
  58451. } bz;
  58452. struct OP_MemMax_stack_vars {
  58453. Mem *pIn1;
  58454. VdbeFrame *pFrame;
  58455. } ca;
  58456. struct OP_AggStep_stack_vars {
  58457. int n;
  58458. int i;
  58459. Mem *pMem;
  58460. Mem *pRec;
  58461. sqlite3_context ctx;
  58462. sqlite3_value **apVal;
  58463. } cb;
  58464. struct OP_AggFinal_stack_vars {
  58465. Mem *pMem;
  58466. } cc;
  58467. struct OP_Checkpoint_stack_vars {
  58468. int i; /* Loop counter */
  58469. int aRes[3]; /* Results */
  58470. Mem *pMem; /* Write results here */
  58471. } cd;
  58472. struct OP_JournalMode_stack_vars {
  58473. Btree *pBt; /* Btree to change journal mode of */
  58474. Pager *pPager; /* Pager associated with pBt */
  58475. int eNew; /* New journal mode */
  58476. int eOld; /* The old journal mode */
  58477. const char *zFilename; /* Name of database file for pPager */
  58478. } ce;
  58479. struct OP_IncrVacuum_stack_vars {
  58480. Btree *pBt;
  58481. } cf;
  58482. struct OP_VBegin_stack_vars {
  58483. VTable *pVTab;
  58484. } cg;
  58485. struct OP_VOpen_stack_vars {
  58486. VdbeCursor *pCur;
  58487. sqlite3_vtab_cursor *pVtabCursor;
  58488. sqlite3_vtab *pVtab;
  58489. sqlite3_module *pModule;
  58490. } ch;
  58491. struct OP_VFilter_stack_vars {
  58492. int nArg;
  58493. int iQuery;
  58494. const sqlite3_module *pModule;
  58495. Mem *pQuery;
  58496. Mem *pArgc;
  58497. sqlite3_vtab_cursor *pVtabCursor;
  58498. sqlite3_vtab *pVtab;
  58499. VdbeCursor *pCur;
  58500. int res;
  58501. int i;
  58502. Mem **apArg;
  58503. } ci;
  58504. struct OP_VColumn_stack_vars {
  58505. sqlite3_vtab *pVtab;
  58506. const sqlite3_module *pModule;
  58507. Mem *pDest;
  58508. sqlite3_context sContext;
  58509. } cj;
  58510. struct OP_VNext_stack_vars {
  58511. sqlite3_vtab *pVtab;
  58512. const sqlite3_module *pModule;
  58513. int res;
  58514. VdbeCursor *pCur;
  58515. } ck;
  58516. struct OP_VRename_stack_vars {
  58517. sqlite3_vtab *pVtab;
  58518. Mem *pName;
  58519. } cl;
  58520. struct OP_VUpdate_stack_vars {
  58521. sqlite3_vtab *pVtab;
  58522. sqlite3_module *pModule;
  58523. int nArg;
  58524. int i;
  58525. sqlite_int64 rowid;
  58526. Mem **apArg;
  58527. Mem *pX;
  58528. } cm;
  58529. struct OP_Trace_stack_vars {
  58530. char *zTrace;
  58531. } cn;
  58532. } u;
  58533. /* End automatically generated code
  58534. ********************************************************************/
  58535. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  58536. sqlite3VdbeEnter(p);
  58537. if( p->rc==SQLITE_NOMEM ){
  58538. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  58539. ** sqlite3_column_text16() failed. */
  58540. goto no_mem;
  58541. }
  58542. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  58543. p->rc = SQLITE_OK;
  58544. assert( p->explain==0 );
  58545. p->pResultSet = 0;
  58546. db->busyHandler.nBusy = 0;
  58547. CHECK_FOR_INTERRUPT;
  58548. sqlite3VdbeIOTraceSql(p);
  58549. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  58550. checkProgress = db->xProgress!=0;
  58551. #endif
  58552. #ifdef SQLITE_DEBUG
  58553. sqlite3BeginBenignMalloc();
  58554. if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
  58555. int i;
  58556. printf("VDBE Program Listing:\n");
  58557. sqlite3VdbePrintSql(p);
  58558. for(i=0; i<p->nOp; i++){
  58559. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  58560. }
  58561. }
  58562. sqlite3EndBenignMalloc();
  58563. #endif
  58564. for(pc=p->pc; rc==SQLITE_OK; pc++){
  58565. assert( pc>=0 && pc<p->nOp );
  58566. if( db->mallocFailed ) goto no_mem;
  58567. #ifdef VDBE_PROFILE
  58568. origPc = pc;
  58569. start = sqlite3Hwtime();
  58570. #endif
  58571. pOp = &aOp[pc];
  58572. /* Only allow tracing if SQLITE_DEBUG is defined.
  58573. */
  58574. #ifdef SQLITE_DEBUG
  58575. if( p->trace ){
  58576. if( pc==0 ){
  58577. printf("VDBE Execution Trace:\n");
  58578. sqlite3VdbePrintSql(p);
  58579. }
  58580. sqlite3VdbePrintOp(p->trace, pc, pOp);
  58581. }
  58582. #endif
  58583. /* Check to see if we need to simulate an interrupt. This only happens
  58584. ** if we have a special test build.
  58585. */
  58586. #ifdef SQLITE_TEST
  58587. if( sqlite3_interrupt_count>0 ){
  58588. sqlite3_interrupt_count--;
  58589. if( sqlite3_interrupt_count==0 ){
  58590. sqlite3_interrupt(db);
  58591. }
  58592. }
  58593. #endif
  58594. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  58595. /* Call the progress callback if it is configured and the required number
  58596. ** of VDBE ops have been executed (either since this invocation of
  58597. ** sqlite3VdbeExec() or since last time the progress callback was called).
  58598. ** If the progress callback returns non-zero, exit the virtual machine with
  58599. ** a return code SQLITE_ABORT.
  58600. */
  58601. if( checkProgress ){
  58602. if( db->nProgressOps==nProgressOps ){
  58603. int prc;
  58604. prc = db->xProgress(db->pProgressArg);
  58605. if( prc!=0 ){
  58606. rc = SQLITE_INTERRUPT;
  58607. goto vdbe_error_halt;
  58608. }
  58609. nProgressOps = 0;
  58610. }
  58611. nProgressOps++;
  58612. }
  58613. #endif
  58614. /* On any opcode with the "out2-prerelase" tag, free any
  58615. ** external allocations out of mem[p2] and set mem[p2] to be
  58616. ** an undefined integer. Opcodes will either fill in the integer
  58617. ** value or convert mem[p2] to a different type.
  58618. */
  58619. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  58620. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  58621. assert( pOp->p2>0 );
  58622. assert( pOp->p2<=p->nMem );
  58623. pOut = &aMem[pOp->p2];
  58624. memAboutToChange(p, pOut);
  58625. sqlite3VdbeMemReleaseExternal(pOut);
  58626. pOut->flags = MEM_Int;
  58627. }
  58628. /* Sanity checking on other operands */
  58629. #ifdef SQLITE_DEBUG
  58630. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  58631. assert( pOp->p1>0 );
  58632. assert( pOp->p1<=p->nMem );
  58633. assert( memIsValid(&aMem[pOp->p1]) );
  58634. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  58635. }
  58636. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  58637. assert( pOp->p2>0 );
  58638. assert( pOp->p2<=p->nMem );
  58639. assert( memIsValid(&aMem[pOp->p2]) );
  58640. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  58641. }
  58642. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  58643. assert( pOp->p3>0 );
  58644. assert( pOp->p3<=p->nMem );
  58645. assert( memIsValid(&aMem[pOp->p3]) );
  58646. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  58647. }
  58648. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  58649. assert( pOp->p2>0 );
  58650. assert( pOp->p2<=p->nMem );
  58651. memAboutToChange(p, &aMem[pOp->p2]);
  58652. }
  58653. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  58654. assert( pOp->p3>0 );
  58655. assert( pOp->p3<=p->nMem );
  58656. memAboutToChange(p, &aMem[pOp->p3]);
  58657. }
  58658. #endif
  58659. switch( pOp->opcode ){
  58660. /*****************************************************************************
  58661. ** What follows is a massive switch statement where each case implements a
  58662. ** separate instruction in the virtual machine. If we follow the usual
  58663. ** indentation conventions, each case should be indented by 6 spaces. But
  58664. ** that is a lot of wasted space on the left margin. So the code within
  58665. ** the switch statement will break with convention and be flush-left. Another
  58666. ** big comment (similar to this one) will mark the point in the code where
  58667. ** we transition back to normal indentation.
  58668. **
  58669. ** The formatting of each case is important. The makefile for SQLite
  58670. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  58671. ** file looking for lines that begin with "case OP_". The opcodes.h files
  58672. ** will be filled with #defines that give unique integer values to each
  58673. ** opcode and the opcodes.c file is filled with an array of strings where
  58674. ** each string is the symbolic name for the corresponding opcode. If the
  58675. ** case statement is followed by a comment of the form "/# same as ... #/"
  58676. ** that comment is used to determine the particular value of the opcode.
  58677. **
  58678. ** Other keywords in the comment that follows each case are used to
  58679. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  58680. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  58681. ** the mkopcodeh.awk script for additional information.
  58682. **
  58683. ** Documentation about VDBE opcodes is generated by scanning this file
  58684. ** for lines of that contain "Opcode:". That line and all subsequent
  58685. ** comment lines are used in the generation of the opcode.html documentation
  58686. ** file.
  58687. **
  58688. ** SUMMARY:
  58689. **
  58690. ** Formatting is important to scripts that scan this file.
  58691. ** Do not deviate from the formatting style currently in use.
  58692. **
  58693. *****************************************************************************/
  58694. /* Opcode: Goto * P2 * * *
  58695. **
  58696. ** An unconditional jump to address P2.
  58697. ** The next instruction executed will be
  58698. ** the one at index P2 from the beginning of
  58699. ** the program.
  58700. */
  58701. case OP_Goto: { /* jump */
  58702. CHECK_FOR_INTERRUPT;
  58703. pc = pOp->p2 - 1;
  58704. break;
  58705. }
  58706. /* Opcode: Gosub P1 P2 * * *
  58707. **
  58708. ** Write the current address onto register P1
  58709. ** and then jump to address P2.
  58710. */
  58711. case OP_Gosub: { /* jump, in1 */
  58712. pIn1 = &aMem[pOp->p1];
  58713. assert( (pIn1->flags & MEM_Dyn)==0 );
  58714. memAboutToChange(p, pIn1);
  58715. pIn1->flags = MEM_Int;
  58716. pIn1->u.i = pc;
  58717. REGISTER_TRACE(pOp->p1, pIn1);
  58718. pc = pOp->p2 - 1;
  58719. break;
  58720. }
  58721. /* Opcode: Return P1 * * * *
  58722. **
  58723. ** Jump to the next instruction after the address in register P1.
  58724. */
  58725. case OP_Return: { /* in1 */
  58726. pIn1 = &aMem[pOp->p1];
  58727. assert( pIn1->flags & MEM_Int );
  58728. pc = (int)pIn1->u.i;
  58729. break;
  58730. }
  58731. /* Opcode: Yield P1 * * * *
  58732. **
  58733. ** Swap the program counter with the value in register P1.
  58734. */
  58735. case OP_Yield: { /* in1 */
  58736. #if 0 /* local variables moved into u.aa */
  58737. int pcDest;
  58738. #endif /* local variables moved into u.aa */
  58739. pIn1 = &aMem[pOp->p1];
  58740. assert( (pIn1->flags & MEM_Dyn)==0 );
  58741. pIn1->flags = MEM_Int;
  58742. u.aa.pcDest = (int)pIn1->u.i;
  58743. pIn1->u.i = pc;
  58744. REGISTER_TRACE(pOp->p1, pIn1);
  58745. pc = u.aa.pcDest;
  58746. break;
  58747. }
  58748. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  58749. **
  58750. ** Check the value in register P3. If is is NULL then Halt using
  58751. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  58752. ** value in register P3 is not NULL, then this routine is a no-op.
  58753. */
  58754. case OP_HaltIfNull: { /* in3 */
  58755. pIn3 = &aMem[pOp->p3];
  58756. if( (pIn3->flags & MEM_Null)==0 ) break;
  58757. /* Fall through into OP_Halt */
  58758. }
  58759. /* Opcode: Halt P1 P2 * P4 *
  58760. **
  58761. ** Exit immediately. All open cursors, etc are closed
  58762. ** automatically.
  58763. **
  58764. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  58765. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  58766. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  58767. ** whether or not to rollback the current transaction. Do not rollback
  58768. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  58769. ** then back out all changes that have occurred during this execution of the
  58770. ** VDBE, but do not rollback the transaction.
  58771. **
  58772. ** If P4 is not null then it is an error message string.
  58773. **
  58774. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  58775. ** every program. So a jump past the last instruction of the program
  58776. ** is the same as executing Halt.
  58777. */
  58778. case OP_Halt: {
  58779. if( pOp->p1==SQLITE_OK && p->pFrame ){
  58780. /* Halt the sub-program. Return control to the parent frame. */
  58781. VdbeFrame *pFrame = p->pFrame;
  58782. p->pFrame = pFrame->pParent;
  58783. p->nFrame--;
  58784. sqlite3VdbeSetChanges(db, p->nChange);
  58785. pc = sqlite3VdbeFrameRestore(pFrame);
  58786. if( pOp->p2==OE_Ignore ){
  58787. /* Instruction pc is the OP_Program that invoked the sub-program
  58788. ** currently being halted. If the p2 instruction of this OP_Halt
  58789. ** instruction is set to OE_Ignore, then the sub-program is throwing
  58790. ** an IGNORE exception. In this case jump to the address specified
  58791. ** as the p2 of the calling OP_Program. */
  58792. pc = p->aOp[pc].p2-1;
  58793. }
  58794. aOp = p->aOp;
  58795. aMem = p->aMem;
  58796. break;
  58797. }
  58798. p->rc = pOp->p1;
  58799. p->errorAction = (u8)pOp->p2;
  58800. p->pc = pc;
  58801. if( pOp->p4.z ){
  58802. assert( p->rc!=SQLITE_OK );
  58803. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  58804. testcase( sqlite3GlobalConfig.xLog!=0 );
  58805. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  58806. }else if( p->rc ){
  58807. testcase( sqlite3GlobalConfig.xLog!=0 );
  58808. sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  58809. }
  58810. rc = sqlite3VdbeHalt(p);
  58811. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  58812. if( rc==SQLITE_BUSY ){
  58813. p->rc = rc = SQLITE_BUSY;
  58814. }else{
  58815. assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
  58816. assert( rc==SQLITE_OK || db->nDeferredCons>0 );
  58817. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  58818. }
  58819. goto vdbe_return;
  58820. }
  58821. /* Opcode: Integer P1 P2 * * *
  58822. **
  58823. ** The 32-bit integer value P1 is written into register P2.
  58824. */
  58825. case OP_Integer: { /* out2-prerelease */
  58826. pOut->u.i = pOp->p1;
  58827. break;
  58828. }
  58829. /* Opcode: Int64 * P2 * P4 *
  58830. **
  58831. ** P4 is a pointer to a 64-bit integer value.
  58832. ** Write that value into register P2.
  58833. */
  58834. case OP_Int64: { /* out2-prerelease */
  58835. assert( pOp->p4.pI64!=0 );
  58836. pOut->u.i = *pOp->p4.pI64;
  58837. break;
  58838. }
  58839. #ifndef SQLITE_OMIT_FLOATING_POINT
  58840. /* Opcode: Real * P2 * P4 *
  58841. **
  58842. ** P4 is a pointer to a 64-bit floating point value.
  58843. ** Write that value into register P2.
  58844. */
  58845. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  58846. pOut->flags = MEM_Real;
  58847. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  58848. pOut->r = *pOp->p4.pReal;
  58849. break;
  58850. }
  58851. #endif
  58852. /* Opcode: String8 * P2 * P4 *
  58853. **
  58854. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  58855. ** into an OP_String before it is executed for the first time.
  58856. */
  58857. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  58858. assert( pOp->p4.z!=0 );
  58859. pOp->opcode = OP_String;
  58860. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  58861. #ifndef SQLITE_OMIT_UTF16
  58862. if( encoding!=SQLITE_UTF8 ){
  58863. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  58864. if( rc==SQLITE_TOOBIG ) goto too_big;
  58865. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  58866. assert( pOut->zMalloc==pOut->z );
  58867. assert( pOut->flags & MEM_Dyn );
  58868. pOut->zMalloc = 0;
  58869. pOut->flags |= MEM_Static;
  58870. pOut->flags &= ~MEM_Dyn;
  58871. if( pOp->p4type==P4_DYNAMIC ){
  58872. sqlite3DbFree(db, pOp->p4.z);
  58873. }
  58874. pOp->p4type = P4_DYNAMIC;
  58875. pOp->p4.z = pOut->z;
  58876. pOp->p1 = pOut->n;
  58877. }
  58878. #endif
  58879. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  58880. goto too_big;
  58881. }
  58882. /* Fall through to the next case, OP_String */
  58883. }
  58884. /* Opcode: String P1 P2 * P4 *
  58885. **
  58886. ** The string value P4 of length P1 (bytes) is stored in register P2.
  58887. */
  58888. case OP_String: { /* out2-prerelease */
  58889. assert( pOp->p4.z!=0 );
  58890. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  58891. pOut->z = pOp->p4.z;
  58892. pOut->n = pOp->p1;
  58893. pOut->enc = encoding;
  58894. UPDATE_MAX_BLOBSIZE(pOut);
  58895. break;
  58896. }
  58897. /* Opcode: Null * P2 * * *
  58898. **
  58899. ** Write a NULL into register P2.
  58900. */
  58901. case OP_Null: { /* out2-prerelease */
  58902. pOut->flags = MEM_Null;
  58903. break;
  58904. }
  58905. /* Opcode: Blob P1 P2 * P4
  58906. **
  58907. ** P4 points to a blob of data P1 bytes long. Store this
  58908. ** blob in register P2.
  58909. */
  58910. case OP_Blob: { /* out2-prerelease */
  58911. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  58912. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  58913. pOut->enc = encoding;
  58914. UPDATE_MAX_BLOBSIZE(pOut);
  58915. break;
  58916. }
  58917. /* Opcode: Variable P1 P2 * P4 *
  58918. **
  58919. ** Transfer the values of bound parameter P1 into register P2
  58920. **
  58921. ** If the parameter is named, then its name appears in P4 and P3==1.
  58922. ** The P4 value is used by sqlite3_bind_parameter_name().
  58923. */
  58924. case OP_Variable: { /* out2-prerelease */
  58925. #if 0 /* local variables moved into u.ab */
  58926. Mem *pVar; /* Value being transferred */
  58927. #endif /* local variables moved into u.ab */
  58928. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  58929. u.ab.pVar = &p->aVar[pOp->p1 - 1];
  58930. if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
  58931. goto too_big;
  58932. }
  58933. sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
  58934. UPDATE_MAX_BLOBSIZE(pOut);
  58935. break;
  58936. }
  58937. /* Opcode: Move P1 P2 P3 * *
  58938. **
  58939. ** Move the values in register P1..P1+P3-1 over into
  58940. ** registers P2..P2+P3-1. Registers P1..P1+P1-1 are
  58941. ** left holding a NULL. It is an error for register ranges
  58942. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
  58943. */
  58944. case OP_Move: {
  58945. #if 0 /* local variables moved into u.ac */
  58946. char *zMalloc; /* Holding variable for allocated memory */
  58947. int n; /* Number of registers left to copy */
  58948. int p1; /* Register to copy from */
  58949. int p2; /* Register to copy to */
  58950. #endif /* local variables moved into u.ac */
  58951. u.ac.n = pOp->p3;
  58952. u.ac.p1 = pOp->p1;
  58953. u.ac.p2 = pOp->p2;
  58954. assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
  58955. assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
  58956. pIn1 = &aMem[u.ac.p1];
  58957. pOut = &aMem[u.ac.p2];
  58958. while( u.ac.n-- ){
  58959. assert( pOut<=&aMem[p->nMem] );
  58960. assert( pIn1<=&aMem[p->nMem] );
  58961. assert( memIsValid(pIn1) );
  58962. memAboutToChange(p, pOut);
  58963. u.ac.zMalloc = pOut->zMalloc;
  58964. pOut->zMalloc = 0;
  58965. sqlite3VdbeMemMove(pOut, pIn1);
  58966. pIn1->zMalloc = u.ac.zMalloc;
  58967. REGISTER_TRACE(u.ac.p2++, pOut);
  58968. pIn1++;
  58969. pOut++;
  58970. }
  58971. break;
  58972. }
  58973. /* Opcode: Copy P1 P2 * * *
  58974. **
  58975. ** Make a copy of register P1 into register P2.
  58976. **
  58977. ** This instruction makes a deep copy of the value. A duplicate
  58978. ** is made of any string or blob constant. See also OP_SCopy.
  58979. */
  58980. case OP_Copy: { /* in1, out2 */
  58981. pIn1 = &aMem[pOp->p1];
  58982. pOut = &aMem[pOp->p2];
  58983. assert( pOut!=pIn1 );
  58984. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  58985. Deephemeralize(pOut);
  58986. REGISTER_TRACE(pOp->p2, pOut);
  58987. break;
  58988. }
  58989. /* Opcode: SCopy P1 P2 * * *
  58990. **
  58991. ** Make a shallow copy of register P1 into register P2.
  58992. **
  58993. ** This instruction makes a shallow copy of the value. If the value
  58994. ** is a string or blob, then the copy is only a pointer to the
  58995. ** original and hence if the original changes so will the copy.
  58996. ** Worse, if the original is deallocated, the copy becomes invalid.
  58997. ** Thus the program must guarantee that the original will not change
  58998. ** during the lifetime of the copy. Use OP_Copy to make a complete
  58999. ** copy.
  59000. */
  59001. case OP_SCopy: { /* in1, out2 */
  59002. pIn1 = &aMem[pOp->p1];
  59003. pOut = &aMem[pOp->p2];
  59004. assert( pOut!=pIn1 );
  59005. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  59006. #ifdef SQLITE_DEBUG
  59007. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  59008. #endif
  59009. REGISTER_TRACE(pOp->p2, pOut);
  59010. break;
  59011. }
  59012. /* Opcode: ResultRow P1 P2 * * *
  59013. **
  59014. ** The registers P1 through P1+P2-1 contain a single row of
  59015. ** results. This opcode causes the sqlite3_step() call to terminate
  59016. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  59017. ** structure to provide access to the top P1 values as the result
  59018. ** row.
  59019. */
  59020. case OP_ResultRow: {
  59021. #if 0 /* local variables moved into u.ad */
  59022. Mem *pMem;
  59023. int i;
  59024. #endif /* local variables moved into u.ad */
  59025. assert( p->nResColumn==pOp->p2 );
  59026. assert( pOp->p1>0 );
  59027. assert( pOp->p1+pOp->p2<=p->nMem+1 );
  59028. /* If this statement has violated immediate foreign key constraints, do
  59029. ** not return the number of rows modified. And do not RELEASE the statement
  59030. ** transaction. It needs to be rolled back. */
  59031. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  59032. assert( db->flags&SQLITE_CountRows );
  59033. assert( p->usesStmtJournal );
  59034. break;
  59035. }
  59036. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  59037. ** DML statements invoke this opcode to return the number of rows
  59038. ** modified to the user. This is the only way that a VM that
  59039. ** opens a statement transaction may invoke this opcode.
  59040. **
  59041. ** In case this is such a statement, close any statement transaction
  59042. ** opened by this VM before returning control to the user. This is to
  59043. ** ensure that statement-transactions are always nested, not overlapping.
  59044. ** If the open statement-transaction is not closed here, then the user
  59045. ** may step another VM that opens its own statement transaction. This
  59046. ** may lead to overlapping statement transactions.
  59047. **
  59048. ** The statement transaction is never a top-level transaction. Hence
  59049. ** the RELEASE call below can never fail.
  59050. */
  59051. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  59052. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  59053. if( NEVER(rc!=SQLITE_OK) ){
  59054. break;
  59055. }
  59056. /* Invalidate all ephemeral cursor row caches */
  59057. p->cacheCtr = (p->cacheCtr + 2)|1;
  59058. /* Make sure the results of the current row are \000 terminated
  59059. ** and have an assigned type. The results are de-ephemeralized as
  59060. ** as side effect.
  59061. */
  59062. u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
  59063. for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
  59064. assert( memIsValid(&u.ad.pMem[u.ad.i]) );
  59065. Deephemeralize(&u.ad.pMem[u.ad.i]);
  59066. assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
  59067. || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
  59068. sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
  59069. sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
  59070. REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
  59071. }
  59072. if( db->mallocFailed ) goto no_mem;
  59073. /* Return SQLITE_ROW
  59074. */
  59075. p->pc = pc + 1;
  59076. rc = SQLITE_ROW;
  59077. goto vdbe_return;
  59078. }
  59079. /* Opcode: Concat P1 P2 P3 * *
  59080. **
  59081. ** Add the text in register P1 onto the end of the text in
  59082. ** register P2 and store the result in register P3.
  59083. ** If either the P1 or P2 text are NULL then store NULL in P3.
  59084. **
  59085. ** P3 = P2 || P1
  59086. **
  59087. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  59088. ** if P3 is the same register as P2, the implementation is able
  59089. ** to avoid a memcpy().
  59090. */
  59091. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  59092. #if 0 /* local variables moved into u.ae */
  59093. i64 nByte;
  59094. #endif /* local variables moved into u.ae */
  59095. pIn1 = &aMem[pOp->p1];
  59096. pIn2 = &aMem[pOp->p2];
  59097. pOut = &aMem[pOp->p3];
  59098. assert( pIn1!=pOut );
  59099. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  59100. sqlite3VdbeMemSetNull(pOut);
  59101. break;
  59102. }
  59103. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  59104. Stringify(pIn1, encoding);
  59105. Stringify(pIn2, encoding);
  59106. u.ae.nByte = pIn1->n + pIn2->n;
  59107. if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  59108. goto too_big;
  59109. }
  59110. MemSetTypeFlag(pOut, MEM_Str);
  59111. if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
  59112. goto no_mem;
  59113. }
  59114. if( pOut!=pIn2 ){
  59115. memcpy(pOut->z, pIn2->z, pIn2->n);
  59116. }
  59117. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  59118. pOut->z[u.ae.nByte] = 0;
  59119. pOut->z[u.ae.nByte+1] = 0;
  59120. pOut->flags |= MEM_Term;
  59121. pOut->n = (int)u.ae.nByte;
  59122. pOut->enc = encoding;
  59123. UPDATE_MAX_BLOBSIZE(pOut);
  59124. break;
  59125. }
  59126. /* Opcode: Add P1 P2 P3 * *
  59127. **
  59128. ** Add the value in register P1 to the value in register P2
  59129. ** and store the result in register P3.
  59130. ** If either input is NULL, the result is NULL.
  59131. */
  59132. /* Opcode: Multiply P1 P2 P3 * *
  59133. **
  59134. **
  59135. ** Multiply the value in register P1 by the value in register P2
  59136. ** and store the result in register P3.
  59137. ** If either input is NULL, the result is NULL.
  59138. */
  59139. /* Opcode: Subtract P1 P2 P3 * *
  59140. **
  59141. ** Subtract the value in register P1 from the value in register P2
  59142. ** and store the result in register P3.
  59143. ** If either input is NULL, the result is NULL.
  59144. */
  59145. /* Opcode: Divide P1 P2 P3 * *
  59146. **
  59147. ** Divide the value in register P1 by the value in register P2
  59148. ** and store the result in register P3 (P3=P2/P1). If the value in
  59149. ** register P1 is zero, then the result is NULL. If either input is
  59150. ** NULL, the result is NULL.
  59151. */
  59152. /* Opcode: Remainder P1 P2 P3 * *
  59153. **
  59154. ** Compute the remainder after integer division of the value in
  59155. ** register P1 by the value in register P2 and store the result in P3.
  59156. ** If the value in register P2 is zero the result is NULL.
  59157. ** If either operand is NULL, the result is NULL.
  59158. */
  59159. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  59160. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  59161. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  59162. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  59163. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  59164. #if 0 /* local variables moved into u.af */
  59165. int flags; /* Combined MEM_* flags from both inputs */
  59166. i64 iA; /* Integer value of left operand */
  59167. i64 iB; /* Integer value of right operand */
  59168. double rA; /* Real value of left operand */
  59169. double rB; /* Real value of right operand */
  59170. #endif /* local variables moved into u.af */
  59171. pIn1 = &aMem[pOp->p1];
  59172. applyNumericAffinity(pIn1);
  59173. pIn2 = &aMem[pOp->p2];
  59174. applyNumericAffinity(pIn2);
  59175. pOut = &aMem[pOp->p3];
  59176. u.af.flags = pIn1->flags | pIn2->flags;
  59177. if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  59178. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  59179. u.af.iA = pIn1->u.i;
  59180. u.af.iB = pIn2->u.i;
  59181. switch( pOp->opcode ){
  59182. case OP_Add: if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
  59183. case OP_Subtract: if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
  59184. case OP_Multiply: if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math; break;
  59185. case OP_Divide: {
  59186. if( u.af.iA==0 ) goto arithmetic_result_is_null;
  59187. if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
  59188. u.af.iB /= u.af.iA;
  59189. break;
  59190. }
  59191. default: {
  59192. if( u.af.iA==0 ) goto arithmetic_result_is_null;
  59193. if( u.af.iA==-1 ) u.af.iA = 1;
  59194. u.af.iB %= u.af.iA;
  59195. break;
  59196. }
  59197. }
  59198. pOut->u.i = u.af.iB;
  59199. MemSetTypeFlag(pOut, MEM_Int);
  59200. }else{
  59201. fp_math:
  59202. u.af.rA = sqlite3VdbeRealValue(pIn1);
  59203. u.af.rB = sqlite3VdbeRealValue(pIn2);
  59204. switch( pOp->opcode ){
  59205. case OP_Add: u.af.rB += u.af.rA; break;
  59206. case OP_Subtract: u.af.rB -= u.af.rA; break;
  59207. case OP_Multiply: u.af.rB *= u.af.rA; break;
  59208. case OP_Divide: {
  59209. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  59210. if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
  59211. u.af.rB /= u.af.rA;
  59212. break;
  59213. }
  59214. default: {
  59215. u.af.iA = (i64)u.af.rA;
  59216. u.af.iB = (i64)u.af.rB;
  59217. if( u.af.iA==0 ) goto arithmetic_result_is_null;
  59218. if( u.af.iA==-1 ) u.af.iA = 1;
  59219. u.af.rB = (double)(u.af.iB % u.af.iA);
  59220. break;
  59221. }
  59222. }
  59223. #ifdef SQLITE_OMIT_FLOATING_POINT
  59224. pOut->u.i = u.af.rB;
  59225. MemSetTypeFlag(pOut, MEM_Int);
  59226. #else
  59227. if( sqlite3IsNaN(u.af.rB) ){
  59228. goto arithmetic_result_is_null;
  59229. }
  59230. pOut->r = u.af.rB;
  59231. MemSetTypeFlag(pOut, MEM_Real);
  59232. if( (u.af.flags & MEM_Real)==0 ){
  59233. sqlite3VdbeIntegerAffinity(pOut);
  59234. }
  59235. #endif
  59236. }
  59237. break;
  59238. arithmetic_result_is_null:
  59239. sqlite3VdbeMemSetNull(pOut);
  59240. break;
  59241. }
  59242. /* Opcode: CollSeq * * P4
  59243. **
  59244. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  59245. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  59246. ** be returned. This is used by the built-in min(), max() and nullif()
  59247. ** functions.
  59248. **
  59249. ** The interface used by the implementation of the aforementioned functions
  59250. ** to retrieve the collation sequence set by this opcode is not available
  59251. ** publicly, only to user functions defined in func.c.
  59252. */
  59253. case OP_CollSeq: {
  59254. assert( pOp->p4type==P4_COLLSEQ );
  59255. break;
  59256. }
  59257. /* Opcode: Function P1 P2 P3 P4 P5
  59258. **
  59259. ** Invoke a user function (P4 is a pointer to a Function structure that
  59260. ** defines the function) with P5 arguments taken from register P2 and
  59261. ** successors. The result of the function is stored in register P3.
  59262. ** Register P3 must not be one of the function inputs.
  59263. **
  59264. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  59265. ** function was determined to be constant at compile time. If the first
  59266. ** argument was constant then bit 0 of P1 is set. This is used to determine
  59267. ** whether meta data associated with a user function argument using the
  59268. ** sqlite3_set_auxdata() API may be safely retained until the next
  59269. ** invocation of this opcode.
  59270. **
  59271. ** See also: AggStep and AggFinal
  59272. */
  59273. case OP_Function: {
  59274. #if 0 /* local variables moved into u.ag */
  59275. int i;
  59276. Mem *pArg;
  59277. sqlite3_context ctx;
  59278. sqlite3_value **apVal;
  59279. int n;
  59280. #endif /* local variables moved into u.ag */
  59281. u.ag.n = pOp->p5;
  59282. u.ag.apVal = p->apArg;
  59283. assert( u.ag.apVal || u.ag.n==0 );
  59284. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  59285. pOut = &aMem[pOp->p3];
  59286. memAboutToChange(p, pOut);
  59287. assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
  59288. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
  59289. u.ag.pArg = &aMem[pOp->p2];
  59290. for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
  59291. assert( memIsValid(u.ag.pArg) );
  59292. u.ag.apVal[u.ag.i] = u.ag.pArg;
  59293. Deephemeralize(u.ag.pArg);
  59294. sqlite3VdbeMemStoreType(u.ag.pArg);
  59295. REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
  59296. }
  59297. assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
  59298. if( pOp->p4type==P4_FUNCDEF ){
  59299. u.ag.ctx.pFunc = pOp->p4.pFunc;
  59300. u.ag.ctx.pVdbeFunc = 0;
  59301. }else{
  59302. u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
  59303. u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
  59304. }
  59305. u.ag.ctx.s.flags = MEM_Null;
  59306. u.ag.ctx.s.db = db;
  59307. u.ag.ctx.s.xDel = 0;
  59308. u.ag.ctx.s.zMalloc = 0;
  59309. /* The output cell may already have a buffer allocated. Move
  59310. ** the pointer to u.ag.ctx.s so in case the user-function can use
  59311. ** the already allocated buffer instead of allocating a new one.
  59312. */
  59313. sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
  59314. MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
  59315. u.ag.ctx.isError = 0;
  59316. if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  59317. assert( pOp>aOp );
  59318. assert( pOp[-1].p4type==P4_COLLSEQ );
  59319. assert( pOp[-1].opcode==OP_CollSeq );
  59320. u.ag.ctx.pColl = pOp[-1].p4.pColl;
  59321. }
  59322. (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
  59323. if( db->mallocFailed ){
  59324. /* Even though a malloc() has failed, the implementation of the
  59325. ** user function may have called an sqlite3_result_XXX() function
  59326. ** to return a value. The following call releases any resources
  59327. ** associated with such a value.
  59328. */
  59329. sqlite3VdbeMemRelease(&u.ag.ctx.s);
  59330. goto no_mem;
  59331. }
  59332. /* If any auxiliary data functions have been called by this user function,
  59333. ** immediately call the destructor for any non-static values.
  59334. */
  59335. if( u.ag.ctx.pVdbeFunc ){
  59336. sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
  59337. pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
  59338. pOp->p4type = P4_VDBEFUNC;
  59339. }
  59340. /* If the function returned an error, throw an exception */
  59341. if( u.ag.ctx.isError ){
  59342. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
  59343. rc = u.ag.ctx.isError;
  59344. }
  59345. /* Copy the result of the function into register P3 */
  59346. sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
  59347. sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
  59348. if( sqlite3VdbeMemTooBig(pOut) ){
  59349. goto too_big;
  59350. }
  59351. #if 0
  59352. /* The app-defined function has done something that as caused this
  59353. ** statement to expire. (Perhaps the function called sqlite3_exec()
  59354. ** with a CREATE TABLE statement.)
  59355. */
  59356. if( p->expired ) rc = SQLITE_ABORT;
  59357. #endif
  59358. REGISTER_TRACE(pOp->p3, pOut);
  59359. UPDATE_MAX_BLOBSIZE(pOut);
  59360. break;
  59361. }
  59362. /* Opcode: BitAnd P1 P2 P3 * *
  59363. **
  59364. ** Take the bit-wise AND of the values in register P1 and P2 and
  59365. ** store the result in register P3.
  59366. ** If either input is NULL, the result is NULL.
  59367. */
  59368. /* Opcode: BitOr P1 P2 P3 * *
  59369. **
  59370. ** Take the bit-wise OR of the values in register P1 and P2 and
  59371. ** store the result in register P3.
  59372. ** If either input is NULL, the result is NULL.
  59373. */
  59374. /* Opcode: ShiftLeft P1 P2 P3 * *
  59375. **
  59376. ** Shift the integer value in register P2 to the left by the
  59377. ** number of bits specified by the integer in register P1.
  59378. ** Store the result in register P3.
  59379. ** If either input is NULL, the result is NULL.
  59380. */
  59381. /* Opcode: ShiftRight P1 P2 P3 * *
  59382. **
  59383. ** Shift the integer value in register P2 to the right by the
  59384. ** number of bits specified by the integer in register P1.
  59385. ** Store the result in register P3.
  59386. ** If either input is NULL, the result is NULL.
  59387. */
  59388. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  59389. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  59390. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  59391. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  59392. #if 0 /* local variables moved into u.ah */
  59393. i64 iA;
  59394. u64 uA;
  59395. i64 iB;
  59396. u8 op;
  59397. #endif /* local variables moved into u.ah */
  59398. pIn1 = &aMem[pOp->p1];
  59399. pIn2 = &aMem[pOp->p2];
  59400. pOut = &aMem[pOp->p3];
  59401. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  59402. sqlite3VdbeMemSetNull(pOut);
  59403. break;
  59404. }
  59405. u.ah.iA = sqlite3VdbeIntValue(pIn2);
  59406. u.ah.iB = sqlite3VdbeIntValue(pIn1);
  59407. u.ah.op = pOp->opcode;
  59408. if( u.ah.op==OP_BitAnd ){
  59409. u.ah.iA &= u.ah.iB;
  59410. }else if( u.ah.op==OP_BitOr ){
  59411. u.ah.iA |= u.ah.iB;
  59412. }else if( u.ah.iB!=0 ){
  59413. assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
  59414. /* If shifting by a negative amount, shift in the other direction */
  59415. if( u.ah.iB<0 ){
  59416. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  59417. u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
  59418. u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
  59419. }
  59420. if( u.ah.iB>=64 ){
  59421. u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
  59422. }else{
  59423. memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
  59424. if( u.ah.op==OP_ShiftLeft ){
  59425. u.ah.uA <<= u.ah.iB;
  59426. }else{
  59427. u.ah.uA >>= u.ah.iB;
  59428. /* Sign-extend on a right shift of a negative number */
  59429. if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
  59430. }
  59431. memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
  59432. }
  59433. }
  59434. pOut->u.i = u.ah.iA;
  59435. MemSetTypeFlag(pOut, MEM_Int);
  59436. break;
  59437. }
  59438. /* Opcode: AddImm P1 P2 * * *
  59439. **
  59440. ** Add the constant P2 to the value in register P1.
  59441. ** The result is always an integer.
  59442. **
  59443. ** To force any register to be an integer, just add 0.
  59444. */
  59445. case OP_AddImm: { /* in1 */
  59446. pIn1 = &aMem[pOp->p1];
  59447. memAboutToChange(p, pIn1);
  59448. sqlite3VdbeMemIntegerify(pIn1);
  59449. pIn1->u.i += pOp->p2;
  59450. break;
  59451. }
  59452. /* Opcode: MustBeInt P1 P2 * * *
  59453. **
  59454. ** Force the value in register P1 to be an integer. If the value
  59455. ** in P1 is not an integer and cannot be converted into an integer
  59456. ** without data loss, then jump immediately to P2, or if P2==0
  59457. ** raise an SQLITE_MISMATCH exception.
  59458. */
  59459. case OP_MustBeInt: { /* jump, in1 */
  59460. pIn1 = &aMem[pOp->p1];
  59461. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  59462. if( (pIn1->flags & MEM_Int)==0 ){
  59463. if( pOp->p2==0 ){
  59464. rc = SQLITE_MISMATCH;
  59465. goto abort_due_to_error;
  59466. }else{
  59467. pc = pOp->p2 - 1;
  59468. }
  59469. }else{
  59470. MemSetTypeFlag(pIn1, MEM_Int);
  59471. }
  59472. break;
  59473. }
  59474. #ifndef SQLITE_OMIT_FLOATING_POINT
  59475. /* Opcode: RealAffinity P1 * * * *
  59476. **
  59477. ** If register P1 holds an integer convert it to a real value.
  59478. **
  59479. ** This opcode is used when extracting information from a column that
  59480. ** has REAL affinity. Such column values may still be stored as
  59481. ** integers, for space efficiency, but after extraction we want them
  59482. ** to have only a real value.
  59483. */
  59484. case OP_RealAffinity: { /* in1 */
  59485. pIn1 = &aMem[pOp->p1];
  59486. if( pIn1->flags & MEM_Int ){
  59487. sqlite3VdbeMemRealify(pIn1);
  59488. }
  59489. break;
  59490. }
  59491. #endif
  59492. #ifndef SQLITE_OMIT_CAST
  59493. /* Opcode: ToText P1 * * * *
  59494. **
  59495. ** Force the value in register P1 to be text.
  59496. ** If the value is numeric, convert it to a string using the
  59497. ** equivalent of printf(). Blob values are unchanged and
  59498. ** are afterwards simply interpreted as text.
  59499. **
  59500. ** A NULL value is not changed by this routine. It remains NULL.
  59501. */
  59502. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  59503. pIn1 = &aMem[pOp->p1];
  59504. memAboutToChange(p, pIn1);
  59505. if( pIn1->flags & MEM_Null ) break;
  59506. assert( MEM_Str==(MEM_Blob>>3) );
  59507. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  59508. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  59509. rc = ExpandBlob(pIn1);
  59510. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  59511. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  59512. UPDATE_MAX_BLOBSIZE(pIn1);
  59513. break;
  59514. }
  59515. /* Opcode: ToBlob P1 * * * *
  59516. **
  59517. ** Force the value in register P1 to be a BLOB.
  59518. ** If the value is numeric, convert it to a string first.
  59519. ** Strings are simply reinterpreted as blobs with no change
  59520. ** to the underlying data.
  59521. **
  59522. ** A NULL value is not changed by this routine. It remains NULL.
  59523. */
  59524. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  59525. pIn1 = &aMem[pOp->p1];
  59526. if( pIn1->flags & MEM_Null ) break;
  59527. if( (pIn1->flags & MEM_Blob)==0 ){
  59528. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  59529. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  59530. MemSetTypeFlag(pIn1, MEM_Blob);
  59531. }else{
  59532. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  59533. }
  59534. UPDATE_MAX_BLOBSIZE(pIn1);
  59535. break;
  59536. }
  59537. /* Opcode: ToNumeric P1 * * * *
  59538. **
  59539. ** Force the value in register P1 to be numeric (either an
  59540. ** integer or a floating-point number.)
  59541. ** If the value is text or blob, try to convert it to an using the
  59542. ** equivalent of atoi() or atof() and store 0 if no such conversion
  59543. ** is possible.
  59544. **
  59545. ** A NULL value is not changed by this routine. It remains NULL.
  59546. */
  59547. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  59548. pIn1 = &aMem[pOp->p1];
  59549. sqlite3VdbeMemNumerify(pIn1);
  59550. break;
  59551. }
  59552. #endif /* SQLITE_OMIT_CAST */
  59553. /* Opcode: ToInt P1 * * * *
  59554. **
  59555. ** Force the value in register P1 to be an integer. If
  59556. ** The value is currently a real number, drop its fractional part.
  59557. ** If the value is text or blob, try to convert it to an integer using the
  59558. ** equivalent of atoi() and store 0 if no such conversion is possible.
  59559. **
  59560. ** A NULL value is not changed by this routine. It remains NULL.
  59561. */
  59562. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  59563. pIn1 = &aMem[pOp->p1];
  59564. if( (pIn1->flags & MEM_Null)==0 ){
  59565. sqlite3VdbeMemIntegerify(pIn1);
  59566. }
  59567. break;
  59568. }
  59569. #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
  59570. /* Opcode: ToReal P1 * * * *
  59571. **
  59572. ** Force the value in register P1 to be a floating point number.
  59573. ** If The value is currently an integer, convert it.
  59574. ** If the value is text or blob, try to convert it to an integer using the
  59575. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  59576. **
  59577. ** A NULL value is not changed by this routine. It remains NULL.
  59578. */
  59579. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  59580. pIn1 = &aMem[pOp->p1];
  59581. memAboutToChange(p, pIn1);
  59582. if( (pIn1->flags & MEM_Null)==0 ){
  59583. sqlite3VdbeMemRealify(pIn1);
  59584. }
  59585. break;
  59586. }
  59587. #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
  59588. /* Opcode: Lt P1 P2 P3 P4 P5
  59589. **
  59590. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  59591. ** jump to address P2.
  59592. **
  59593. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  59594. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  59595. ** bit is clear then fall through if either operand is NULL.
  59596. **
  59597. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  59598. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  59599. ** to coerce both inputs according to this affinity before the
  59600. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  59601. ** affinity is used. Note that the affinity conversions are stored
  59602. ** back into the input registers P1 and P3. So this opcode can cause
  59603. ** persistent changes to registers P1 and P3.
  59604. **
  59605. ** Once any conversions have taken place, and neither value is NULL,
  59606. ** the values are compared. If both values are blobs then memcmp() is
  59607. ** used to determine the results of the comparison. If both values
  59608. ** are text, then the appropriate collating function specified in
  59609. ** P4 is used to do the comparison. If P4 is not specified then
  59610. ** memcmp() is used to compare text string. If both values are
  59611. ** numeric, then a numeric comparison is used. If the two values
  59612. ** are of different types, then numbers are considered less than
  59613. ** strings and strings are considered less than blobs.
  59614. **
  59615. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  59616. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  59617. */
  59618. /* Opcode: Ne P1 P2 P3 P4 P5
  59619. **
  59620. ** This works just like the Lt opcode except that the jump is taken if
  59621. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  59622. ** additional information.
  59623. **
  59624. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  59625. ** true or false and is never NULL. If both operands are NULL then the result
  59626. ** of comparison is false. If either operand is NULL then the result is true.
  59627. ** If neither operand is NULL the the result is the same as it would be if
  59628. ** the SQLITE_NULLEQ flag were omitted from P5.
  59629. */
  59630. /* Opcode: Eq P1 P2 P3 P4 P5
  59631. **
  59632. ** This works just like the Lt opcode except that the jump is taken if
  59633. ** the operands in registers P1 and P3 are equal.
  59634. ** See the Lt opcode for additional information.
  59635. **
  59636. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  59637. ** true or false and is never NULL. If both operands are NULL then the result
  59638. ** of comparison is true. If either operand is NULL then the result is false.
  59639. ** If neither operand is NULL the the result is the same as it would be if
  59640. ** the SQLITE_NULLEQ flag were omitted from P5.
  59641. */
  59642. /* Opcode: Le P1 P2 P3 P4 P5
  59643. **
  59644. ** This works just like the Lt opcode except that the jump is taken if
  59645. ** the content of register P3 is less than or equal to the content of
  59646. ** register P1. See the Lt opcode for additional information.
  59647. */
  59648. /* Opcode: Gt P1 P2 P3 P4 P5
  59649. **
  59650. ** This works just like the Lt opcode except that the jump is taken if
  59651. ** the content of register P3 is greater than the content of
  59652. ** register P1. See the Lt opcode for additional information.
  59653. */
  59654. /* Opcode: Ge P1 P2 P3 P4 P5
  59655. **
  59656. ** This works just like the Lt opcode except that the jump is taken if
  59657. ** the content of register P3 is greater than or equal to the content of
  59658. ** register P1. See the Lt opcode for additional information.
  59659. */
  59660. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  59661. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  59662. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  59663. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  59664. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  59665. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  59666. #if 0 /* local variables moved into u.ai */
  59667. int res; /* Result of the comparison of pIn1 against pIn3 */
  59668. char affinity; /* Affinity to use for comparison */
  59669. u16 flags1; /* Copy of initial value of pIn1->flags */
  59670. u16 flags3; /* Copy of initial value of pIn3->flags */
  59671. #endif /* local variables moved into u.ai */
  59672. pIn1 = &aMem[pOp->p1];
  59673. pIn3 = &aMem[pOp->p3];
  59674. u.ai.flags1 = pIn1->flags;
  59675. u.ai.flags3 = pIn3->flags;
  59676. if( (pIn1->flags | pIn3->flags)&MEM_Null ){
  59677. /* One or both operands are NULL */
  59678. if( pOp->p5 & SQLITE_NULLEQ ){
  59679. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  59680. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  59681. ** or not both operands are null.
  59682. */
  59683. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  59684. u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
  59685. }else{
  59686. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  59687. ** then the result is always NULL.
  59688. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  59689. */
  59690. if( pOp->p5 & SQLITE_STOREP2 ){
  59691. pOut = &aMem[pOp->p2];
  59692. MemSetTypeFlag(pOut, MEM_Null);
  59693. REGISTER_TRACE(pOp->p2, pOut);
  59694. }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
  59695. pc = pOp->p2-1;
  59696. }
  59697. break;
  59698. }
  59699. }else{
  59700. /* Neither operand is NULL. Do a comparison. */
  59701. u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
  59702. if( u.ai.affinity ){
  59703. applyAffinity(pIn1, u.ai.affinity, encoding);
  59704. applyAffinity(pIn3, u.ai.affinity, encoding);
  59705. if( db->mallocFailed ) goto no_mem;
  59706. }
  59707. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  59708. ExpandBlob(pIn1);
  59709. ExpandBlob(pIn3);
  59710. u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  59711. }
  59712. switch( pOp->opcode ){
  59713. case OP_Eq: u.ai.res = u.ai.res==0; break;
  59714. case OP_Ne: u.ai.res = u.ai.res!=0; break;
  59715. case OP_Lt: u.ai.res = u.ai.res<0; break;
  59716. case OP_Le: u.ai.res = u.ai.res<=0; break;
  59717. case OP_Gt: u.ai.res = u.ai.res>0; break;
  59718. default: u.ai.res = u.ai.res>=0; break;
  59719. }
  59720. if( pOp->p5 & SQLITE_STOREP2 ){
  59721. pOut = &aMem[pOp->p2];
  59722. memAboutToChange(p, pOut);
  59723. MemSetTypeFlag(pOut, MEM_Int);
  59724. pOut->u.i = u.ai.res;
  59725. REGISTER_TRACE(pOp->p2, pOut);
  59726. }else if( u.ai.res ){
  59727. pc = pOp->p2-1;
  59728. }
  59729. /* Undo any changes made by applyAffinity() to the input registers. */
  59730. pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
  59731. pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
  59732. break;
  59733. }
  59734. /* Opcode: Permutation * * * P4 *
  59735. **
  59736. ** Set the permutation used by the OP_Compare operator to be the array
  59737. ** of integers in P4.
  59738. **
  59739. ** The permutation is only valid until the next OP_Permutation, OP_Compare,
  59740. ** OP_Halt, or OP_ResultRow. Typically the OP_Permutation should occur
  59741. ** immediately prior to the OP_Compare.
  59742. */
  59743. case OP_Permutation: {
  59744. assert( pOp->p4type==P4_INTARRAY );
  59745. assert( pOp->p4.ai );
  59746. aPermute = pOp->p4.ai;
  59747. break;
  59748. }
  59749. /* Opcode: Compare P1 P2 P3 P4 *
  59750. **
  59751. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  59752. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  59753. ** the comparison for use by the next OP_Jump instruct.
  59754. **
  59755. ** P4 is a KeyInfo structure that defines collating sequences and sort
  59756. ** orders for the comparison. The permutation applies to registers
  59757. ** only. The KeyInfo elements are used sequentially.
  59758. **
  59759. ** The comparison is a sort comparison, so NULLs compare equal,
  59760. ** NULLs are less than numbers, numbers are less than strings,
  59761. ** and strings are less than blobs.
  59762. */
  59763. case OP_Compare: {
  59764. #if 0 /* local variables moved into u.aj */
  59765. int n;
  59766. int i;
  59767. int p1;
  59768. int p2;
  59769. const KeyInfo *pKeyInfo;
  59770. int idx;
  59771. CollSeq *pColl; /* Collating sequence to use on this term */
  59772. int bRev; /* True for DESCENDING sort order */
  59773. #endif /* local variables moved into u.aj */
  59774. u.aj.n = pOp->p3;
  59775. u.aj.pKeyInfo = pOp->p4.pKeyInfo;
  59776. assert( u.aj.n>0 );
  59777. assert( u.aj.pKeyInfo!=0 );
  59778. u.aj.p1 = pOp->p1;
  59779. u.aj.p2 = pOp->p2;
  59780. #if SQLITE_DEBUG
  59781. if( aPermute ){
  59782. int k, mx = 0;
  59783. for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  59784. assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
  59785. assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
  59786. }else{
  59787. assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
  59788. assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
  59789. }
  59790. #endif /* SQLITE_DEBUG */
  59791. for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
  59792. u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
  59793. assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
  59794. assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
  59795. REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
  59796. REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
  59797. assert( u.aj.i<u.aj.pKeyInfo->nField );
  59798. u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
  59799. u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
  59800. iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
  59801. if( iCompare ){
  59802. if( u.aj.bRev ) iCompare = -iCompare;
  59803. break;
  59804. }
  59805. }
  59806. aPermute = 0;
  59807. break;
  59808. }
  59809. /* Opcode: Jump P1 P2 P3 * *
  59810. **
  59811. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  59812. ** in the most recent OP_Compare instruction the P1 vector was less than
  59813. ** equal to, or greater than the P2 vector, respectively.
  59814. */
  59815. case OP_Jump: { /* jump */
  59816. if( iCompare<0 ){
  59817. pc = pOp->p1 - 1;
  59818. }else if( iCompare==0 ){
  59819. pc = pOp->p2 - 1;
  59820. }else{
  59821. pc = pOp->p3 - 1;
  59822. }
  59823. break;
  59824. }
  59825. /* Opcode: And P1 P2 P3 * *
  59826. **
  59827. ** Take the logical AND of the values in registers P1 and P2 and
  59828. ** write the result into register P3.
  59829. **
  59830. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  59831. ** the other input is NULL. A NULL and true or two NULLs give
  59832. ** a NULL output.
  59833. */
  59834. /* Opcode: Or P1 P2 P3 * *
  59835. **
  59836. ** Take the logical OR of the values in register P1 and P2 and
  59837. ** store the answer in register P3.
  59838. **
  59839. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  59840. ** even if the other input is NULL. A NULL and false or two NULLs
  59841. ** give a NULL output.
  59842. */
  59843. case OP_And: /* same as TK_AND, in1, in2, out3 */
  59844. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  59845. #if 0 /* local variables moved into u.ak */
  59846. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  59847. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  59848. #endif /* local variables moved into u.ak */
  59849. pIn1 = &aMem[pOp->p1];
  59850. if( pIn1->flags & MEM_Null ){
  59851. u.ak.v1 = 2;
  59852. }else{
  59853. u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
  59854. }
  59855. pIn2 = &aMem[pOp->p2];
  59856. if( pIn2->flags & MEM_Null ){
  59857. u.ak.v2 = 2;
  59858. }else{
  59859. u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
  59860. }
  59861. if( pOp->opcode==OP_And ){
  59862. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  59863. u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
  59864. }else{
  59865. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  59866. u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
  59867. }
  59868. pOut = &aMem[pOp->p3];
  59869. if( u.ak.v1==2 ){
  59870. MemSetTypeFlag(pOut, MEM_Null);
  59871. }else{
  59872. pOut->u.i = u.ak.v1;
  59873. MemSetTypeFlag(pOut, MEM_Int);
  59874. }
  59875. break;
  59876. }
  59877. /* Opcode: Not P1 P2 * * *
  59878. **
  59879. ** Interpret the value in register P1 as a boolean value. Store the
  59880. ** boolean complement in register P2. If the value in register P1 is
  59881. ** NULL, then a NULL is stored in P2.
  59882. */
  59883. case OP_Not: { /* same as TK_NOT, in1, out2 */
  59884. pIn1 = &aMem[pOp->p1];
  59885. pOut = &aMem[pOp->p2];
  59886. if( pIn1->flags & MEM_Null ){
  59887. sqlite3VdbeMemSetNull(pOut);
  59888. }else{
  59889. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  59890. }
  59891. break;
  59892. }
  59893. /* Opcode: BitNot P1 P2 * * *
  59894. **
  59895. ** Interpret the content of register P1 as an integer. Store the
  59896. ** ones-complement of the P1 value into register P2. If P1 holds
  59897. ** a NULL then store a NULL in P2.
  59898. */
  59899. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  59900. pIn1 = &aMem[pOp->p1];
  59901. pOut = &aMem[pOp->p2];
  59902. if( pIn1->flags & MEM_Null ){
  59903. sqlite3VdbeMemSetNull(pOut);
  59904. }else{
  59905. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  59906. }
  59907. break;
  59908. }
  59909. /* Opcode: If P1 P2 P3 * *
  59910. **
  59911. ** Jump to P2 if the value in register P1 is true. The value is
  59912. ** is considered true if it is numeric and non-zero. If the value
  59913. ** in P1 is NULL then take the jump if P3 is true.
  59914. */
  59915. /* Opcode: IfNot P1 P2 P3 * *
  59916. **
  59917. ** Jump to P2 if the value in register P1 is False. The value is
  59918. ** is considered true if it has a numeric value of zero. If the value
  59919. ** in P1 is NULL then take the jump if P3 is true.
  59920. */
  59921. case OP_If: /* jump, in1 */
  59922. case OP_IfNot: { /* jump, in1 */
  59923. #if 0 /* local variables moved into u.al */
  59924. int c;
  59925. #endif /* local variables moved into u.al */
  59926. pIn1 = &aMem[pOp->p1];
  59927. if( pIn1->flags & MEM_Null ){
  59928. u.al.c = pOp->p3;
  59929. }else{
  59930. #ifdef SQLITE_OMIT_FLOATING_POINT
  59931. u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
  59932. #else
  59933. u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
  59934. #endif
  59935. if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
  59936. }
  59937. if( u.al.c ){
  59938. pc = pOp->p2-1;
  59939. }
  59940. break;
  59941. }
  59942. /* Opcode: IsNull P1 P2 * * *
  59943. **
  59944. ** Jump to P2 if the value in register P1 is NULL.
  59945. */
  59946. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  59947. pIn1 = &aMem[pOp->p1];
  59948. if( (pIn1->flags & MEM_Null)!=0 ){
  59949. pc = pOp->p2 - 1;
  59950. }
  59951. break;
  59952. }
  59953. /* Opcode: NotNull P1 P2 * * *
  59954. **
  59955. ** Jump to P2 if the value in register P1 is not NULL.
  59956. */
  59957. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  59958. pIn1 = &aMem[pOp->p1];
  59959. if( (pIn1->flags & MEM_Null)==0 ){
  59960. pc = pOp->p2 - 1;
  59961. }
  59962. break;
  59963. }
  59964. /* Opcode: Column P1 P2 P3 P4 P5
  59965. **
  59966. ** Interpret the data that cursor P1 points to as a structure built using
  59967. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  59968. ** information about the format of the data.) Extract the P2-th column
  59969. ** from this record. If there are less that (P2+1)
  59970. ** values in the record, extract a NULL.
  59971. **
  59972. ** The value extracted is stored in register P3.
  59973. **
  59974. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  59975. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  59976. ** the result.
  59977. **
  59978. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  59979. ** then the cache of the cursor is reset prior to extracting the column.
  59980. ** The first OP_Column against a pseudo-table after the value of the content
  59981. ** register has changed should have this bit set.
  59982. */
  59983. case OP_Column: {
  59984. #if 0 /* local variables moved into u.am */
  59985. u32 payloadSize; /* Number of bytes in the record */
  59986. i64 payloadSize64; /* Number of bytes in the record */
  59987. int p1; /* P1 value of the opcode */
  59988. int p2; /* column number to retrieve */
  59989. VdbeCursor *pC; /* The VDBE cursor */
  59990. char *zRec; /* Pointer to complete record-data */
  59991. BtCursor *pCrsr; /* The BTree cursor */
  59992. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  59993. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  59994. int nField; /* number of fields in the record */
  59995. int len; /* The length of the serialized data for the column */
  59996. int i; /* Loop counter */
  59997. char *zData; /* Part of the record being decoded */
  59998. Mem *pDest; /* Where to write the extracted value */
  59999. Mem sMem; /* For storing the record being decoded */
  60000. u8 *zIdx; /* Index into header */
  60001. u8 *zEndHdr; /* Pointer to first byte after the header */
  60002. u32 offset; /* Offset into the data */
  60003. u32 szField; /* Number of bytes in the content of a field */
  60004. int szHdr; /* Size of the header size field at start of record */
  60005. int avail; /* Number of bytes of available data */
  60006. Mem *pReg; /* PseudoTable input register */
  60007. #endif /* local variables moved into u.am */
  60008. u.am.p1 = pOp->p1;
  60009. u.am.p2 = pOp->p2;
  60010. u.am.pC = 0;
  60011. memset(&u.am.sMem, 0, sizeof(u.am.sMem));
  60012. assert( u.am.p1<p->nCursor );
  60013. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  60014. u.am.pDest = &aMem[pOp->p3];
  60015. memAboutToChange(p, u.am.pDest);
  60016. MemSetTypeFlag(u.am.pDest, MEM_Null);
  60017. u.am.zRec = 0;
  60018. /* This block sets the variable u.am.payloadSize to be the total number of
  60019. ** bytes in the record.
  60020. **
  60021. ** u.am.zRec is set to be the complete text of the record if it is available.
  60022. ** The complete record text is always available for pseudo-tables
  60023. ** If the record is stored in a cursor, the complete record text
  60024. ** might be available in the u.am.pC->aRow cache. Or it might not be.
  60025. ** If the data is unavailable, u.am.zRec is set to NULL.
  60026. **
  60027. ** We also compute the number of columns in the record. For cursors,
  60028. ** the number of columns is stored in the VdbeCursor.nField element.
  60029. */
  60030. u.am.pC = p->apCsr[u.am.p1];
  60031. assert( u.am.pC!=0 );
  60032. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60033. assert( u.am.pC->pVtabCursor==0 );
  60034. #endif
  60035. u.am.pCrsr = u.am.pC->pCursor;
  60036. if( u.am.pCrsr!=0 ){
  60037. /* The record is stored in a B-Tree */
  60038. rc = sqlite3VdbeCursorMoveto(u.am.pC);
  60039. if( rc ) goto abort_due_to_error;
  60040. if( u.am.pC->nullRow ){
  60041. u.am.payloadSize = 0;
  60042. }else if( u.am.pC->cacheStatus==p->cacheCtr ){
  60043. u.am.payloadSize = u.am.pC->payloadSize;
  60044. u.am.zRec = (char*)u.am.pC->aRow;
  60045. }else if( u.am.pC->isIndex ){
  60046. assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
  60047. rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
  60048. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  60049. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  60050. ** payload size, so it is impossible for u.am.payloadSize64 to be
  60051. ** larger than 32 bits. */
  60052. assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
  60053. u.am.payloadSize = (u32)u.am.payloadSize64;
  60054. }else{
  60055. assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
  60056. rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
  60057. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  60058. }
  60059. }else if( u.am.pC->pseudoTableReg>0 ){
  60060. u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
  60061. assert( u.am.pReg->flags & MEM_Blob );
  60062. assert( memIsValid(u.am.pReg) );
  60063. u.am.payloadSize = u.am.pReg->n;
  60064. u.am.zRec = u.am.pReg->z;
  60065. u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
  60066. assert( u.am.payloadSize==0 || u.am.zRec!=0 );
  60067. }else{
  60068. /* Consider the row to be NULL */
  60069. u.am.payloadSize = 0;
  60070. }
  60071. /* If u.am.payloadSize is 0, then just store a NULL */
  60072. if( u.am.payloadSize==0 ){
  60073. assert( u.am.pDest->flags&MEM_Null );
  60074. goto op_column_out;
  60075. }
  60076. assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  60077. if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  60078. goto too_big;
  60079. }
  60080. u.am.nField = u.am.pC->nField;
  60081. assert( u.am.p2<u.am.nField );
  60082. /* Read and parse the table header. Store the results of the parse
  60083. ** into the record header cache fields of the cursor.
  60084. */
  60085. u.am.aType = u.am.pC->aType;
  60086. if( u.am.pC->cacheStatus==p->cacheCtr ){
  60087. u.am.aOffset = u.am.pC->aOffset;
  60088. }else{
  60089. assert(u.am.aType);
  60090. u.am.avail = 0;
  60091. u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
  60092. u.am.pC->payloadSize = u.am.payloadSize;
  60093. u.am.pC->cacheStatus = p->cacheCtr;
  60094. /* Figure out how many bytes are in the header */
  60095. if( u.am.zRec ){
  60096. u.am.zData = u.am.zRec;
  60097. }else{
  60098. if( u.am.pC->isIndex ){
  60099. u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
  60100. }else{
  60101. u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
  60102. }
  60103. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  60104. ** save the payload in the u.am.pC->aRow cache. That will save us from
  60105. ** having to make additional calls to fetch the content portion of
  60106. ** the record.
  60107. */
  60108. assert( u.am.avail>=0 );
  60109. if( u.am.payloadSize <= (u32)u.am.avail ){
  60110. u.am.zRec = u.am.zData;
  60111. u.am.pC->aRow = (u8*)u.am.zData;
  60112. }else{
  60113. u.am.pC->aRow = 0;
  60114. }
  60115. }
  60116. /* The following assert is true in all cases accept when
  60117. ** the database file has been corrupted externally.
  60118. ** assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
  60119. u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
  60120. /* Make sure a corrupt database has not given us an oversize header.
  60121. ** Do this now to avoid an oversize memory allocation.
  60122. **
  60123. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  60124. ** types use so much data space that there can only be 4096 and 32 of
  60125. ** them, respectively. So the maximum header length results from a
  60126. ** 3-byte type for each of the maximum of 32768 columns plus three
  60127. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  60128. */
  60129. if( u.am.offset > 98307 ){
  60130. rc = SQLITE_CORRUPT_BKPT;
  60131. goto op_column_out;
  60132. }
  60133. /* Compute in u.am.len the number of bytes of data we need to read in order
  60134. ** to get u.am.nField type values. u.am.offset is an upper bound on this. But
  60135. ** u.am.nField might be significantly less than the true number of columns
  60136. ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
  60137. ** We want to minimize u.am.len in order to limit the size of the memory
  60138. ** allocation, especially if a corrupt database file has caused u.am.offset
  60139. ** to be oversized. Offset is limited to 98307 above. But 98307 might
  60140. ** still exceed Robson memory allocation limits on some configurations.
  60141. ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
  60142. ** will likely be much smaller since u.am.nField will likely be less than
  60143. ** 20 or so. This insures that Robson memory allocation limits are
  60144. ** not exceeded even for corrupt database files.
  60145. */
  60146. u.am.len = u.am.nField*5 + 3;
  60147. if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
  60148. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  60149. ** record header in most cases. But they will fail to get the complete
  60150. ** record header if the record header does not fit on a single page
  60151. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  60152. ** acquire the complete header text.
  60153. */
  60154. if( !u.am.zRec && u.am.avail<u.am.len ){
  60155. u.am.sMem.flags = 0;
  60156. u.am.sMem.db = 0;
  60157. rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
  60158. if( rc!=SQLITE_OK ){
  60159. goto op_column_out;
  60160. }
  60161. u.am.zData = u.am.sMem.z;
  60162. }
  60163. u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
  60164. u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
  60165. /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
  60166. ** arrays. u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
  60167. ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
  60168. ** of the record to the start of the data for the u.am.i-th column
  60169. */
  60170. for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
  60171. if( u.am.zIdx<u.am.zEndHdr ){
  60172. u.am.aOffset[u.am.i] = u.am.offset;
  60173. u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
  60174. u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
  60175. u.am.offset += u.am.szField;
  60176. if( u.am.offset<u.am.szField ){ /* True if u.am.offset overflows */
  60177. u.am.zIdx = &u.am.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  60178. break;
  60179. }
  60180. }else{
  60181. /* If u.am.i is less that u.am.nField, then there are less fields in this
  60182. ** record than SetNumColumns indicated there are columns in the
  60183. ** table. Set the u.am.offset for any extra columns not present in
  60184. ** the record to 0. This tells code below to store a NULL
  60185. ** instead of deserializing a value from the record.
  60186. */
  60187. u.am.aOffset[u.am.i] = 0;
  60188. }
  60189. }
  60190. sqlite3VdbeMemRelease(&u.am.sMem);
  60191. u.am.sMem.flags = MEM_Null;
  60192. /* If we have read more header data than was contained in the header,
  60193. ** or if the end of the last field appears to be past the end of the
  60194. ** record, or if the end of the last field appears to be before the end
  60195. ** of the record (when all fields present), then we must be dealing
  60196. ** with a corrupt database.
  60197. */
  60198. if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
  60199. || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
  60200. rc = SQLITE_CORRUPT_BKPT;
  60201. goto op_column_out;
  60202. }
  60203. }
  60204. /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
  60205. ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
  60206. ** then there are not enough fields in the record to satisfy the
  60207. ** request. In this case, set the value NULL or to P4 if P4 is
  60208. ** a pointer to a Mem object.
  60209. */
  60210. if( u.am.aOffset[u.am.p2] ){
  60211. assert( rc==SQLITE_OK );
  60212. if( u.am.zRec ){
  60213. sqlite3VdbeMemReleaseExternal(u.am.pDest);
  60214. sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
  60215. }else{
  60216. u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
  60217. sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
  60218. rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
  60219. if( rc!=SQLITE_OK ){
  60220. goto op_column_out;
  60221. }
  60222. u.am.zData = u.am.sMem.z;
  60223. sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
  60224. }
  60225. u.am.pDest->enc = encoding;
  60226. }else{
  60227. if( pOp->p4type==P4_MEM ){
  60228. sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
  60229. }else{
  60230. assert( u.am.pDest->flags&MEM_Null );
  60231. }
  60232. }
  60233. /* If we dynamically allocated space to hold the data (in the
  60234. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  60235. ** dynamically allocated space over to the u.am.pDest structure.
  60236. ** This prevents a memory copy.
  60237. */
  60238. if( u.am.sMem.zMalloc ){
  60239. assert( u.am.sMem.z==u.am.sMem.zMalloc );
  60240. assert( !(u.am.pDest->flags & MEM_Dyn) );
  60241. assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
  60242. u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
  60243. u.am.pDest->flags |= MEM_Term;
  60244. u.am.pDest->z = u.am.sMem.z;
  60245. u.am.pDest->zMalloc = u.am.sMem.zMalloc;
  60246. }
  60247. rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
  60248. op_column_out:
  60249. UPDATE_MAX_BLOBSIZE(u.am.pDest);
  60250. REGISTER_TRACE(pOp->p3, u.am.pDest);
  60251. break;
  60252. }
  60253. /* Opcode: Affinity P1 P2 * P4 *
  60254. **
  60255. ** Apply affinities to a range of P2 registers starting with P1.
  60256. **
  60257. ** P4 is a string that is P2 characters long. The nth character of the
  60258. ** string indicates the column affinity that should be used for the nth
  60259. ** memory cell in the range.
  60260. */
  60261. case OP_Affinity: {
  60262. #if 0 /* local variables moved into u.an */
  60263. const char *zAffinity; /* The affinity to be applied */
  60264. char cAff; /* A single character of affinity */
  60265. #endif /* local variables moved into u.an */
  60266. u.an.zAffinity = pOp->p4.z;
  60267. assert( u.an.zAffinity!=0 );
  60268. assert( u.an.zAffinity[pOp->p2]==0 );
  60269. pIn1 = &aMem[pOp->p1];
  60270. while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
  60271. assert( pIn1 <= &p->aMem[p->nMem] );
  60272. assert( memIsValid(pIn1) );
  60273. ExpandBlob(pIn1);
  60274. applyAffinity(pIn1, u.an.cAff, encoding);
  60275. pIn1++;
  60276. }
  60277. break;
  60278. }
  60279. /* Opcode: MakeRecord P1 P2 P3 P4 *
  60280. **
  60281. ** Convert P2 registers beginning with P1 into the [record format]
  60282. ** use as a data record in a database table or as a key
  60283. ** in an index. The OP_Column opcode can decode the record later.
  60284. **
  60285. ** P4 may be a string that is P2 characters long. The nth character of the
  60286. ** string indicates the column affinity that should be used for the nth
  60287. ** field of the index key.
  60288. **
  60289. ** The mapping from character to affinity is given by the SQLITE_AFF_
  60290. ** macros defined in sqliteInt.h.
  60291. **
  60292. ** If P4 is NULL then all index fields have the affinity NONE.
  60293. */
  60294. case OP_MakeRecord: {
  60295. #if 0 /* local variables moved into u.ao */
  60296. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  60297. Mem *pRec; /* The new record */
  60298. u64 nData; /* Number of bytes of data space */
  60299. int nHdr; /* Number of bytes of header space */
  60300. i64 nByte; /* Data space required for this record */
  60301. int nZero; /* Number of zero bytes at the end of the record */
  60302. int nVarint; /* Number of bytes in a varint */
  60303. u32 serial_type; /* Type field */
  60304. Mem *pData0; /* First field to be combined into the record */
  60305. Mem *pLast; /* Last field of the record */
  60306. int nField; /* Number of fields in the record */
  60307. char *zAffinity; /* The affinity string for the record */
  60308. int file_format; /* File format to use for encoding */
  60309. int i; /* Space used in zNewRecord[] */
  60310. int len; /* Length of a field */
  60311. #endif /* local variables moved into u.ao */
  60312. /* Assuming the record contains N fields, the record format looks
  60313. ** like this:
  60314. **
  60315. ** ------------------------------------------------------------------------
  60316. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  60317. ** ------------------------------------------------------------------------
  60318. **
  60319. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  60320. ** and so froth.
  60321. **
  60322. ** Each type field is a varint representing the serial type of the
  60323. ** corresponding data element (see sqlite3VdbeSerialType()). The
  60324. ** hdr-size field is also a varint which is the offset from the beginning
  60325. ** of the record to data0.
  60326. */
  60327. u.ao.nData = 0; /* Number of bytes of data space */
  60328. u.ao.nHdr = 0; /* Number of bytes of header space */
  60329. u.ao.nZero = 0; /* Number of zero bytes at the end of the record */
  60330. u.ao.nField = pOp->p1;
  60331. u.ao.zAffinity = pOp->p4.z;
  60332. assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
  60333. u.ao.pData0 = &aMem[u.ao.nField];
  60334. u.ao.nField = pOp->p2;
  60335. u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
  60336. u.ao.file_format = p->minWriteFileFormat;
  60337. /* Identify the output register */
  60338. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  60339. pOut = &aMem[pOp->p3];
  60340. memAboutToChange(p, pOut);
  60341. /* Loop through the elements that will make up the record to figure
  60342. ** out how much space is required for the new record.
  60343. */
  60344. for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
  60345. assert( memIsValid(u.ao.pRec) );
  60346. if( u.ao.zAffinity ){
  60347. applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
  60348. }
  60349. if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
  60350. sqlite3VdbeMemExpandBlob(u.ao.pRec);
  60351. }
  60352. u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
  60353. u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
  60354. u.ao.nData += u.ao.len;
  60355. u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
  60356. if( u.ao.pRec->flags & MEM_Zero ){
  60357. /* Only pure zero-filled BLOBs can be input to this Opcode.
  60358. ** We do not allow blobs with a prefix and a zero-filled tail. */
  60359. u.ao.nZero += u.ao.pRec->u.nZero;
  60360. }else if( u.ao.len ){
  60361. u.ao.nZero = 0;
  60362. }
  60363. }
  60364. /* Add the initial header varint and total the size */
  60365. u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
  60366. if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
  60367. u.ao.nHdr++;
  60368. }
  60369. u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
  60370. if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  60371. goto too_big;
  60372. }
  60373. /* Make sure the output register has a buffer large enough to store
  60374. ** the new record. The output register (pOp->p3) is not allowed to
  60375. ** be one of the input registers (because the following call to
  60376. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  60377. */
  60378. if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
  60379. goto no_mem;
  60380. }
  60381. u.ao.zNewRecord = (u8 *)pOut->z;
  60382. /* Write the record */
  60383. u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
  60384. for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
  60385. u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
  60386. u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type); /* serial type */
  60387. }
  60388. for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){ /* serial data */
  60389. u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
  60390. }
  60391. assert( u.ao.i==u.ao.nByte );
  60392. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  60393. pOut->n = (int)u.ao.nByte;
  60394. pOut->flags = MEM_Blob | MEM_Dyn;
  60395. pOut->xDel = 0;
  60396. if( u.ao.nZero ){
  60397. pOut->u.nZero = u.ao.nZero;
  60398. pOut->flags |= MEM_Zero;
  60399. }
  60400. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  60401. REGISTER_TRACE(pOp->p3, pOut);
  60402. UPDATE_MAX_BLOBSIZE(pOut);
  60403. break;
  60404. }
  60405. /* Opcode: Count P1 P2 * * *
  60406. **
  60407. ** Store the number of entries (an integer value) in the table or index
  60408. ** opened by cursor P1 in register P2
  60409. */
  60410. #ifndef SQLITE_OMIT_BTREECOUNT
  60411. case OP_Count: { /* out2-prerelease */
  60412. #if 0 /* local variables moved into u.ap */
  60413. i64 nEntry;
  60414. BtCursor *pCrsr;
  60415. #endif /* local variables moved into u.ap */
  60416. u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
  60417. if( u.ap.pCrsr ){
  60418. rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
  60419. }else{
  60420. u.ap.nEntry = 0;
  60421. }
  60422. pOut->u.i = u.ap.nEntry;
  60423. break;
  60424. }
  60425. #endif
  60426. /* Opcode: Savepoint P1 * * P4 *
  60427. **
  60428. ** Open, release or rollback the savepoint named by parameter P4, depending
  60429. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  60430. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  60431. */
  60432. case OP_Savepoint: {
  60433. #if 0 /* local variables moved into u.aq */
  60434. int p1; /* Value of P1 operand */
  60435. char *zName; /* Name of savepoint */
  60436. int nName;
  60437. Savepoint *pNew;
  60438. Savepoint *pSavepoint;
  60439. Savepoint *pTmp;
  60440. int iSavepoint;
  60441. int ii;
  60442. #endif /* local variables moved into u.aq */
  60443. u.aq.p1 = pOp->p1;
  60444. u.aq.zName = pOp->p4.z;
  60445. /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
  60446. ** transaction, then there cannot be any savepoints.
  60447. */
  60448. assert( db->pSavepoint==0 || db->autoCommit==0 );
  60449. assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
  60450. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  60451. assert( checkSavepointCount(db) );
  60452. if( u.aq.p1==SAVEPOINT_BEGIN ){
  60453. if( db->writeVdbeCnt>0 ){
  60454. /* A new savepoint cannot be created if there are active write
  60455. ** statements (i.e. open read/write incremental blob handles).
  60456. */
  60457. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  60458. "SQL statements in progress");
  60459. rc = SQLITE_BUSY;
  60460. }else{
  60461. u.aq.nName = sqlite3Strlen30(u.aq.zName);
  60462. /* Create a new savepoint structure. */
  60463. u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
  60464. if( u.aq.pNew ){
  60465. u.aq.pNew->zName = (char *)&u.aq.pNew[1];
  60466. memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
  60467. /* If there is no open transaction, then mark this as a special
  60468. ** "transaction savepoint". */
  60469. if( db->autoCommit ){
  60470. db->autoCommit = 0;
  60471. db->isTransactionSavepoint = 1;
  60472. }else{
  60473. db->nSavepoint++;
  60474. }
  60475. /* Link the new savepoint into the database handle's list. */
  60476. u.aq.pNew->pNext = db->pSavepoint;
  60477. db->pSavepoint = u.aq.pNew;
  60478. u.aq.pNew->nDeferredCons = db->nDeferredCons;
  60479. }
  60480. }
  60481. }else{
  60482. u.aq.iSavepoint = 0;
  60483. /* Find the named savepoint. If there is no such savepoint, then an
  60484. ** an error is returned to the user. */
  60485. for(
  60486. u.aq.pSavepoint = db->pSavepoint;
  60487. u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
  60488. u.aq.pSavepoint = u.aq.pSavepoint->pNext
  60489. ){
  60490. u.aq.iSavepoint++;
  60491. }
  60492. if( !u.aq.pSavepoint ){
  60493. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
  60494. rc = SQLITE_ERROR;
  60495. }else if(
  60496. db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
  60497. ){
  60498. /* It is not possible to release (commit) a savepoint if there are
  60499. ** active write statements. It is not possible to rollback a savepoint
  60500. ** if there are any active statements at all.
  60501. */
  60502. sqlite3SetString(&p->zErrMsg, db,
  60503. "cannot %s savepoint - SQL statements in progress",
  60504. (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
  60505. );
  60506. rc = SQLITE_BUSY;
  60507. }else{
  60508. /* Determine whether or not this is a transaction savepoint. If so,
  60509. ** and this is a RELEASE command, then the current transaction
  60510. ** is committed.
  60511. */
  60512. int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
  60513. if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
  60514. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  60515. goto vdbe_return;
  60516. }
  60517. db->autoCommit = 1;
  60518. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  60519. p->pc = pc;
  60520. db->autoCommit = 0;
  60521. p->rc = rc = SQLITE_BUSY;
  60522. goto vdbe_return;
  60523. }
  60524. db->isTransactionSavepoint = 0;
  60525. rc = p->rc;
  60526. }else{
  60527. u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
  60528. for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
  60529. rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
  60530. if( rc!=SQLITE_OK ){
  60531. goto abort_due_to_error;
  60532. }
  60533. }
  60534. if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  60535. sqlite3ExpirePreparedStatements(db);
  60536. sqlite3ResetInternalSchema(db, -1);
  60537. db->flags = (db->flags | SQLITE_InternChanges);
  60538. }
  60539. }
  60540. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  60541. ** savepoints nested inside of the savepoint being operated on. */
  60542. while( db->pSavepoint!=u.aq.pSavepoint ){
  60543. u.aq.pTmp = db->pSavepoint;
  60544. db->pSavepoint = u.aq.pTmp->pNext;
  60545. sqlite3DbFree(db, u.aq.pTmp);
  60546. db->nSavepoint--;
  60547. }
  60548. /* If it is a RELEASE, then destroy the savepoint being operated on
  60549. ** too. If it is a ROLLBACK TO, then set the number of deferred
  60550. ** constraint violations present in the database to the value stored
  60551. ** when the savepoint was created. */
  60552. if( u.aq.p1==SAVEPOINT_RELEASE ){
  60553. assert( u.aq.pSavepoint==db->pSavepoint );
  60554. db->pSavepoint = u.aq.pSavepoint->pNext;
  60555. sqlite3DbFree(db, u.aq.pSavepoint);
  60556. if( !isTransaction ){
  60557. db->nSavepoint--;
  60558. }
  60559. }else{
  60560. db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
  60561. }
  60562. }
  60563. }
  60564. break;
  60565. }
  60566. /* Opcode: AutoCommit P1 P2 * * *
  60567. **
  60568. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  60569. ** back any currently active btree transactions. If there are any active
  60570. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  60571. ** there are active writing VMs or active VMs that use shared cache.
  60572. **
  60573. ** This instruction causes the VM to halt.
  60574. */
  60575. case OP_AutoCommit: {
  60576. #if 0 /* local variables moved into u.ar */
  60577. int desiredAutoCommit;
  60578. int iRollback;
  60579. int turnOnAC;
  60580. #endif /* local variables moved into u.ar */
  60581. u.ar.desiredAutoCommit = pOp->p1;
  60582. u.ar.iRollback = pOp->p2;
  60583. u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
  60584. assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
  60585. assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
  60586. assert( db->activeVdbeCnt>0 ); /* At least this one VM is active */
  60587. if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
  60588. /* If this instruction implements a ROLLBACK and other VMs are
  60589. ** still running, and a transaction is active, return an error indicating
  60590. ** that the other VMs must complete first.
  60591. */
  60592. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  60593. "SQL statements in progress");
  60594. rc = SQLITE_BUSY;
  60595. }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
  60596. /* If this instruction implements a COMMIT and other VMs are writing
  60597. ** return an error indicating that the other VMs must complete first.
  60598. */
  60599. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  60600. "SQL statements in progress");
  60601. rc = SQLITE_BUSY;
  60602. }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
  60603. if( u.ar.iRollback ){
  60604. assert( u.ar.desiredAutoCommit==1 );
  60605. sqlite3RollbackAll(db);
  60606. db->autoCommit = 1;
  60607. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  60608. goto vdbe_return;
  60609. }else{
  60610. db->autoCommit = (u8)u.ar.desiredAutoCommit;
  60611. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  60612. p->pc = pc;
  60613. db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
  60614. p->rc = rc = SQLITE_BUSY;
  60615. goto vdbe_return;
  60616. }
  60617. }
  60618. assert( db->nStatement==0 );
  60619. sqlite3CloseSavepoints(db);
  60620. if( p->rc==SQLITE_OK ){
  60621. rc = SQLITE_DONE;
  60622. }else{
  60623. rc = SQLITE_ERROR;
  60624. }
  60625. goto vdbe_return;
  60626. }else{
  60627. sqlite3SetString(&p->zErrMsg, db,
  60628. (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
  60629. (u.ar.iRollback)?"cannot rollback - no transaction is active":
  60630. "cannot commit - no transaction is active"));
  60631. rc = SQLITE_ERROR;
  60632. }
  60633. break;
  60634. }
  60635. /* Opcode: Transaction P1 P2 * * *
  60636. **
  60637. ** Begin a transaction. The transaction ends when a Commit or Rollback
  60638. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  60639. ** transaction might also be rolled back if an error is encountered.
  60640. **
  60641. ** P1 is the index of the database file on which the transaction is
  60642. ** started. Index 0 is the main database file and index 1 is the
  60643. ** file used for temporary tables. Indices of 2 or more are used for
  60644. ** attached databases.
  60645. **
  60646. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  60647. ** obtained on the database file when a write-transaction is started. No
  60648. ** other process can start another write transaction while this transaction is
  60649. ** underway. Starting a write transaction also creates a rollback journal. A
  60650. ** write transaction must be started before any changes can be made to the
  60651. ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
  60652. ** on the file.
  60653. **
  60654. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  60655. ** true (this flag is set if the Vdbe may modify more than one row and may
  60656. ** throw an ABORT exception), a statement transaction may also be opened.
  60657. ** More specifically, a statement transaction is opened iff the database
  60658. ** connection is currently not in autocommit mode, or if there are other
  60659. ** active statements. A statement transaction allows the affects of this
  60660. ** VDBE to be rolled back after an error without having to roll back the
  60661. ** entire transaction. If no error is encountered, the statement transaction
  60662. ** will automatically commit when the VDBE halts.
  60663. **
  60664. ** If P2 is zero, then a read-lock is obtained on the database file.
  60665. */
  60666. case OP_Transaction: {
  60667. #if 0 /* local variables moved into u.as */
  60668. Btree *pBt;
  60669. #endif /* local variables moved into u.as */
  60670. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  60671. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  60672. u.as.pBt = db->aDb[pOp->p1].pBt;
  60673. if( u.as.pBt ){
  60674. rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
  60675. if( rc==SQLITE_BUSY ){
  60676. p->pc = pc;
  60677. p->rc = rc = SQLITE_BUSY;
  60678. goto vdbe_return;
  60679. }
  60680. if( rc!=SQLITE_OK ){
  60681. goto abort_due_to_error;
  60682. }
  60683. if( pOp->p2 && p->usesStmtJournal
  60684. && (db->autoCommit==0 || db->activeVdbeCnt>1)
  60685. ){
  60686. assert( sqlite3BtreeIsInTrans(u.as.pBt) );
  60687. if( p->iStatement==0 ){
  60688. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  60689. db->nStatement++;
  60690. p->iStatement = db->nSavepoint + db->nStatement;
  60691. }
  60692. rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
  60693. /* Store the current value of the database handles deferred constraint
  60694. ** counter. If the statement transaction needs to be rolled back,
  60695. ** the value of this counter needs to be restored too. */
  60696. p->nStmtDefCons = db->nDeferredCons;
  60697. }
  60698. }
  60699. break;
  60700. }
  60701. /* Opcode: ReadCookie P1 P2 P3 * *
  60702. **
  60703. ** Read cookie number P3 from database P1 and write it into register P2.
  60704. ** P3==1 is the schema version. P3==2 is the database format.
  60705. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  60706. ** the main database file and P1==1 is the database file used to store
  60707. ** temporary tables.
  60708. **
  60709. ** There must be a read-lock on the database (either a transaction
  60710. ** must be started or there must be an open cursor) before
  60711. ** executing this instruction.
  60712. */
  60713. case OP_ReadCookie: { /* out2-prerelease */
  60714. #if 0 /* local variables moved into u.at */
  60715. int iMeta;
  60716. int iDb;
  60717. int iCookie;
  60718. #endif /* local variables moved into u.at */
  60719. u.at.iDb = pOp->p1;
  60720. u.at.iCookie = pOp->p3;
  60721. assert( pOp->p3<SQLITE_N_BTREE_META );
  60722. assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
  60723. assert( db->aDb[u.at.iDb].pBt!=0 );
  60724. assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
  60725. sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
  60726. pOut->u.i = u.at.iMeta;
  60727. break;
  60728. }
  60729. /* Opcode: SetCookie P1 P2 P3 * *
  60730. **
  60731. ** Write the content of register P3 (interpreted as an integer)
  60732. ** into cookie number P2 of database P1. P2==1 is the schema version.
  60733. ** P2==2 is the database format. P2==3 is the recommended pager cache
  60734. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  60735. ** database file used to store temporary tables.
  60736. **
  60737. ** A transaction must be started before executing this opcode.
  60738. */
  60739. case OP_SetCookie: { /* in3 */
  60740. #if 0 /* local variables moved into u.au */
  60741. Db *pDb;
  60742. #endif /* local variables moved into u.au */
  60743. assert( pOp->p2<SQLITE_N_BTREE_META );
  60744. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  60745. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  60746. u.au.pDb = &db->aDb[pOp->p1];
  60747. assert( u.au.pDb->pBt!=0 );
  60748. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  60749. pIn3 = &aMem[pOp->p3];
  60750. sqlite3VdbeMemIntegerify(pIn3);
  60751. /* See note about index shifting on OP_ReadCookie */
  60752. rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
  60753. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  60754. /* When the schema cookie changes, record the new cookie internally */
  60755. u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  60756. db->flags |= SQLITE_InternChanges;
  60757. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  60758. /* Record changes in the file format */
  60759. u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
  60760. }
  60761. if( pOp->p1==1 ){
  60762. /* Invalidate all prepared statements whenever the TEMP database
  60763. ** schema is changed. Ticket #1644 */
  60764. sqlite3ExpirePreparedStatements(db);
  60765. p->expired = 0;
  60766. }
  60767. break;
  60768. }
  60769. /* Opcode: VerifyCookie P1 P2 P3 * *
  60770. **
  60771. ** Check the value of global database parameter number 0 (the
  60772. ** schema version) and make sure it is equal to P2 and that the
  60773. ** generation counter on the local schema parse equals P3.
  60774. **
  60775. ** P1 is the database number which is 0 for the main database file
  60776. ** and 1 for the file holding temporary tables and some higher number
  60777. ** for auxiliary databases.
  60778. **
  60779. ** The cookie changes its value whenever the database schema changes.
  60780. ** This operation is used to detect when that the cookie has changed
  60781. ** and that the current process needs to reread the schema.
  60782. **
  60783. ** Either a transaction needs to have been started or an OP_Open needs
  60784. ** to be executed (to establish a read lock) before this opcode is
  60785. ** invoked.
  60786. */
  60787. case OP_VerifyCookie: {
  60788. #if 0 /* local variables moved into u.av */
  60789. int iMeta;
  60790. int iGen;
  60791. Btree *pBt;
  60792. #endif /* local variables moved into u.av */
  60793. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  60794. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  60795. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  60796. u.av.pBt = db->aDb[pOp->p1].pBt;
  60797. if( u.av.pBt ){
  60798. sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
  60799. u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  60800. }else{
  60801. u.av.iGen = u.av.iMeta = 0;
  60802. }
  60803. if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
  60804. sqlite3DbFree(db, p->zErrMsg);
  60805. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  60806. /* If the schema-cookie from the database file matches the cookie
  60807. ** stored with the in-memory representation of the schema, do
  60808. ** not reload the schema from the database file.
  60809. **
  60810. ** If virtual-tables are in use, this is not just an optimization.
  60811. ** Often, v-tables store their data in other SQLite tables, which
  60812. ** are queried from within xNext() and other v-table methods using
  60813. ** prepared queries. If such a query is out-of-date, we do not want to
  60814. ** discard the database schema, as the user code implementing the
  60815. ** v-table would have to be ready for the sqlite3_vtab structure itself
  60816. ** to be invalidated whenever sqlite3_step() is called from within
  60817. ** a v-table method.
  60818. */
  60819. if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
  60820. sqlite3ResetInternalSchema(db, pOp->p1);
  60821. }
  60822. p->expired = 1;
  60823. rc = SQLITE_SCHEMA;
  60824. }
  60825. break;
  60826. }
  60827. /* Opcode: OpenRead P1 P2 P3 P4 P5
  60828. **
  60829. ** Open a read-only cursor for the database table whose root page is
  60830. ** P2 in a database file. The database file is determined by P3.
  60831. ** P3==0 means the main database, P3==1 means the database used for
  60832. ** temporary tables, and P3>1 means used the corresponding attached
  60833. ** database. Give the new cursor an identifier of P1. The P1
  60834. ** values need not be contiguous but all P1 values should be small integers.
  60835. ** It is an error for P1 to be negative.
  60836. **
  60837. ** If P5!=0 then use the content of register P2 as the root page, not
  60838. ** the value of P2 itself.
  60839. **
  60840. ** There will be a read lock on the database whenever there is an
  60841. ** open cursor. If the database was unlocked prior to this instruction
  60842. ** then a read lock is acquired as part of this instruction. A read
  60843. ** lock allows other processes to read the database but prohibits
  60844. ** any other process from modifying the database. The read lock is
  60845. ** released when all cursors are closed. If this instruction attempts
  60846. ** to get a read lock but fails, the script terminates with an
  60847. ** SQLITE_BUSY error code.
  60848. **
  60849. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  60850. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  60851. ** structure, then said structure defines the content and collating
  60852. ** sequence of the index being opened. Otherwise, if P4 is an integer
  60853. ** value, it is set to the number of columns in the table.
  60854. **
  60855. ** See also OpenWrite.
  60856. */
  60857. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  60858. **
  60859. ** Open a read/write cursor named P1 on the table or index whose root
  60860. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  60861. ** root page.
  60862. **
  60863. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  60864. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  60865. ** structure, then said structure defines the content and collating
  60866. ** sequence of the index being opened. Otherwise, if P4 is an integer
  60867. ** value, it is set to the number of columns in the table, or to the
  60868. ** largest index of any column of the table that is actually used.
  60869. **
  60870. ** This instruction works just like OpenRead except that it opens the cursor
  60871. ** in read/write mode. For a given table, there can be one or more read-only
  60872. ** cursors or a single read/write cursor but not both.
  60873. **
  60874. ** See also OpenRead.
  60875. */
  60876. case OP_OpenRead:
  60877. case OP_OpenWrite: {
  60878. #if 0 /* local variables moved into u.aw */
  60879. int nField;
  60880. KeyInfo *pKeyInfo;
  60881. int p2;
  60882. int iDb;
  60883. int wrFlag;
  60884. Btree *pX;
  60885. VdbeCursor *pCur;
  60886. Db *pDb;
  60887. #endif /* local variables moved into u.aw */
  60888. if( p->expired ){
  60889. rc = SQLITE_ABORT;
  60890. break;
  60891. }
  60892. u.aw.nField = 0;
  60893. u.aw.pKeyInfo = 0;
  60894. u.aw.p2 = pOp->p2;
  60895. u.aw.iDb = pOp->p3;
  60896. assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
  60897. assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
  60898. u.aw.pDb = &db->aDb[u.aw.iDb];
  60899. u.aw.pX = u.aw.pDb->pBt;
  60900. assert( u.aw.pX!=0 );
  60901. if( pOp->opcode==OP_OpenWrite ){
  60902. u.aw.wrFlag = 1;
  60903. assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
  60904. if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
  60905. p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
  60906. }
  60907. }else{
  60908. u.aw.wrFlag = 0;
  60909. }
  60910. if( pOp->p5 ){
  60911. assert( u.aw.p2>0 );
  60912. assert( u.aw.p2<=p->nMem );
  60913. pIn2 = &aMem[u.aw.p2];
  60914. assert( memIsValid(pIn2) );
  60915. assert( (pIn2->flags & MEM_Int)!=0 );
  60916. sqlite3VdbeMemIntegerify(pIn2);
  60917. u.aw.p2 = (int)pIn2->u.i;
  60918. /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
  60919. ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
  60920. ** If there were a failure, the prepared statement would have halted
  60921. ** before reaching this instruction. */
  60922. if( NEVER(u.aw.p2<2) ) {
  60923. rc = SQLITE_CORRUPT_BKPT;
  60924. goto abort_due_to_error;
  60925. }
  60926. }
  60927. if( pOp->p4type==P4_KEYINFO ){
  60928. u.aw.pKeyInfo = pOp->p4.pKeyInfo;
  60929. u.aw.pKeyInfo->enc = ENC(p->db);
  60930. u.aw.nField = u.aw.pKeyInfo->nField+1;
  60931. }else if( pOp->p4type==P4_INT32 ){
  60932. u.aw.nField = pOp->p4.i;
  60933. }
  60934. assert( pOp->p1>=0 );
  60935. u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
  60936. if( u.aw.pCur==0 ) goto no_mem;
  60937. u.aw.pCur->nullRow = 1;
  60938. u.aw.pCur->isOrdered = 1;
  60939. rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
  60940. u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
  60941. /* Since it performs no memory allocation or IO, the only values that
  60942. ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
  60943. ** SQLITE_EMPTY is only returned when attempting to open the table
  60944. ** rooted at page 1 of a zero-byte database. */
  60945. assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
  60946. if( rc==SQLITE_EMPTY ){
  60947. u.aw.pCur->pCursor = 0;
  60948. rc = SQLITE_OK;
  60949. }
  60950. /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  60951. ** SQLite used to check if the root-page flags were sane at this point
  60952. ** and report database corruption if they were not, but this check has
  60953. ** since moved into the btree layer. */
  60954. u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
  60955. u.aw.pCur->isIndex = !u.aw.pCur->isTable;
  60956. break;
  60957. }
  60958. /* Opcode: OpenEphemeral P1 P2 * P4 *
  60959. **
  60960. ** Open a new cursor P1 to a transient table.
  60961. ** The cursor is always opened read/write even if
  60962. ** the main database is read-only. The ephemeral
  60963. ** table is deleted automatically when the cursor is closed.
  60964. **
  60965. ** P2 is the number of columns in the ephemeral table.
  60966. ** The cursor points to a BTree table if P4==0 and to a BTree index
  60967. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  60968. ** that defines the format of keys in the index.
  60969. **
  60970. ** This opcode was once called OpenTemp. But that created
  60971. ** confusion because the term "temp table", might refer either
  60972. ** to a TEMP table at the SQL level, or to a table opened by
  60973. ** this opcode. Then this opcode was call OpenVirtual. But
  60974. ** that created confusion with the whole virtual-table idea.
  60975. */
  60976. /* Opcode: OpenAutoindex P1 P2 * P4 *
  60977. **
  60978. ** This opcode works the same as OP_OpenEphemeral. It has a
  60979. ** different name to distinguish its use. Tables created using
  60980. ** by this opcode will be used for automatically created transient
  60981. ** indices in joins.
  60982. */
  60983. case OP_OpenAutoindex:
  60984. case OP_OpenEphemeral: {
  60985. #if 0 /* local variables moved into u.ax */
  60986. VdbeCursor *pCx;
  60987. #endif /* local variables moved into u.ax */
  60988. static const int vfsFlags =
  60989. SQLITE_OPEN_READWRITE |
  60990. SQLITE_OPEN_CREATE |
  60991. SQLITE_OPEN_EXCLUSIVE |
  60992. SQLITE_OPEN_DELETEONCLOSE |
  60993. SQLITE_OPEN_TRANSIENT_DB;
  60994. assert( pOp->p1>=0 );
  60995. u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  60996. if( u.ax.pCx==0 ) goto no_mem;
  60997. u.ax.pCx->nullRow = 1;
  60998. rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
  60999. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  61000. if( rc==SQLITE_OK ){
  61001. rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
  61002. }
  61003. if( rc==SQLITE_OK ){
  61004. /* If a transient index is required, create it by calling
  61005. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  61006. ** opening it. If a transient table is required, just use the
  61007. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  61008. */
  61009. if( pOp->p4.pKeyInfo ){
  61010. int pgno;
  61011. assert( pOp->p4type==P4_KEYINFO );
  61012. rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
  61013. if( rc==SQLITE_OK ){
  61014. assert( pgno==MASTER_ROOT+1 );
  61015. rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
  61016. (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
  61017. u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  61018. u.ax.pCx->pKeyInfo->enc = ENC(p->db);
  61019. }
  61020. u.ax.pCx->isTable = 0;
  61021. }else{
  61022. rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
  61023. u.ax.pCx->isTable = 1;
  61024. }
  61025. }
  61026. u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  61027. u.ax.pCx->isIndex = !u.ax.pCx->isTable;
  61028. break;
  61029. }
  61030. /* Opcode: OpenPseudo P1 P2 P3 * *
  61031. **
  61032. ** Open a new cursor that points to a fake table that contains a single
  61033. ** row of data. The content of that one row in the content of memory
  61034. ** register P2. In other words, cursor P1 becomes an alias for the
  61035. ** MEM_Blob content contained in register P2.
  61036. **
  61037. ** A pseudo-table created by this opcode is used to hold a single
  61038. ** row output from the sorter so that the row can be decomposed into
  61039. ** individual columns using the OP_Column opcode. The OP_Column opcode
  61040. ** is the only cursor opcode that works with a pseudo-table.
  61041. **
  61042. ** P3 is the number of fields in the records that will be stored by
  61043. ** the pseudo-table.
  61044. */
  61045. case OP_OpenPseudo: {
  61046. #if 0 /* local variables moved into u.ay */
  61047. VdbeCursor *pCx;
  61048. #endif /* local variables moved into u.ay */
  61049. assert( pOp->p1>=0 );
  61050. u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  61051. if( u.ay.pCx==0 ) goto no_mem;
  61052. u.ay.pCx->nullRow = 1;
  61053. u.ay.pCx->pseudoTableReg = pOp->p2;
  61054. u.ay.pCx->isTable = 1;
  61055. u.ay.pCx->isIndex = 0;
  61056. break;
  61057. }
  61058. /* Opcode: Close P1 * * * *
  61059. **
  61060. ** Close a cursor previously opened as P1. If P1 is not
  61061. ** currently open, this instruction is a no-op.
  61062. */
  61063. case OP_Close: {
  61064. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61065. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  61066. p->apCsr[pOp->p1] = 0;
  61067. break;
  61068. }
  61069. /* Opcode: SeekGe P1 P2 P3 P4 *
  61070. **
  61071. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  61072. ** use the value in register P3 as the key. If cursor P1 refers
  61073. ** to an SQL index, then P3 is the first in an array of P4 registers
  61074. ** that are used as an unpacked index key.
  61075. **
  61076. ** Reposition cursor P1 so that it points to the smallest entry that
  61077. ** is greater than or equal to the key value. If there are no records
  61078. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  61079. **
  61080. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  61081. */
  61082. /* Opcode: SeekGt P1 P2 P3 P4 *
  61083. **
  61084. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  61085. ** use the value in register P3 as a key. If cursor P1 refers
  61086. ** to an SQL index, then P3 is the first in an array of P4 registers
  61087. ** that are used as an unpacked index key.
  61088. **
  61089. ** Reposition cursor P1 so that it points to the smallest entry that
  61090. ** is greater than the key value. If there are no records greater than
  61091. ** the key and P2 is not zero, then jump to P2.
  61092. **
  61093. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  61094. */
  61095. /* Opcode: SeekLt P1 P2 P3 P4 *
  61096. **
  61097. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  61098. ** use the value in register P3 as a key. If cursor P1 refers
  61099. ** to an SQL index, then P3 is the first in an array of P4 registers
  61100. ** that are used as an unpacked index key.
  61101. **
  61102. ** Reposition cursor P1 so that it points to the largest entry that
  61103. ** is less than the key value. If there are no records less than
  61104. ** the key and P2 is not zero, then jump to P2.
  61105. **
  61106. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  61107. */
  61108. /* Opcode: SeekLe P1 P2 P3 P4 *
  61109. **
  61110. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  61111. ** use the value in register P3 as a key. If cursor P1 refers
  61112. ** to an SQL index, then P3 is the first in an array of P4 registers
  61113. ** that are used as an unpacked index key.
  61114. **
  61115. ** Reposition cursor P1 so that it points to the largest entry that
  61116. ** is less than or equal to the key value. If there are no records
  61117. ** less than or equal to the key and P2 is not zero, then jump to P2.
  61118. **
  61119. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  61120. */
  61121. case OP_SeekLt: /* jump, in3 */
  61122. case OP_SeekLe: /* jump, in3 */
  61123. case OP_SeekGe: /* jump, in3 */
  61124. case OP_SeekGt: { /* jump, in3 */
  61125. #if 0 /* local variables moved into u.az */
  61126. int res;
  61127. int oc;
  61128. VdbeCursor *pC;
  61129. UnpackedRecord r;
  61130. int nField;
  61131. i64 iKey; /* The rowid we are to seek to */
  61132. #endif /* local variables moved into u.az */
  61133. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61134. assert( pOp->p2!=0 );
  61135. u.az.pC = p->apCsr[pOp->p1];
  61136. assert( u.az.pC!=0 );
  61137. assert( u.az.pC->pseudoTableReg==0 );
  61138. assert( OP_SeekLe == OP_SeekLt+1 );
  61139. assert( OP_SeekGe == OP_SeekLt+2 );
  61140. assert( OP_SeekGt == OP_SeekLt+3 );
  61141. assert( u.az.pC->isOrdered );
  61142. if( u.az.pC->pCursor!=0 ){
  61143. u.az.oc = pOp->opcode;
  61144. u.az.pC->nullRow = 0;
  61145. if( u.az.pC->isTable ){
  61146. /* The input value in P3 might be of any type: integer, real, string,
  61147. ** blob, or NULL. But it needs to be an integer before we can do
  61148. ** the seek, so covert it. */
  61149. pIn3 = &aMem[pOp->p3];
  61150. applyNumericAffinity(pIn3);
  61151. u.az.iKey = sqlite3VdbeIntValue(pIn3);
  61152. u.az.pC->rowidIsValid = 0;
  61153. /* If the P3 value could not be converted into an integer without
  61154. ** loss of information, then special processing is required... */
  61155. if( (pIn3->flags & MEM_Int)==0 ){
  61156. if( (pIn3->flags & MEM_Real)==0 ){
  61157. /* If the P3 value cannot be converted into any kind of a number,
  61158. ** then the seek is not possible, so jump to P2 */
  61159. pc = pOp->p2 - 1;
  61160. break;
  61161. }
  61162. /* If we reach this point, then the P3 value must be a floating
  61163. ** point number. */
  61164. assert( (pIn3->flags & MEM_Real)!=0 );
  61165. if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
  61166. /* The P3 value is too large in magnitude to be expressed as an
  61167. ** integer. */
  61168. u.az.res = 1;
  61169. if( pIn3->r<0 ){
  61170. if( u.az.oc>=OP_SeekGe ){ assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
  61171. rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
  61172. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  61173. }
  61174. }else{
  61175. if( u.az.oc<=OP_SeekLe ){ assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
  61176. rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
  61177. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  61178. }
  61179. }
  61180. if( u.az.res ){
  61181. pc = pOp->p2 - 1;
  61182. }
  61183. break;
  61184. }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
  61185. /* Use the ceiling() function to convert real->int */
  61186. if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
  61187. }else{
  61188. /* Use the floor() function to convert real->int */
  61189. assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
  61190. if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
  61191. }
  61192. }
  61193. rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
  61194. if( rc!=SQLITE_OK ){
  61195. goto abort_due_to_error;
  61196. }
  61197. if( u.az.res==0 ){
  61198. u.az.pC->rowidIsValid = 1;
  61199. u.az.pC->lastRowid = u.az.iKey;
  61200. }
  61201. }else{
  61202. u.az.nField = pOp->p4.i;
  61203. assert( pOp->p4type==P4_INT32 );
  61204. assert( u.az.nField>0 );
  61205. u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
  61206. u.az.r.nField = (u16)u.az.nField;
  61207. /* The next line of code computes as follows, only faster:
  61208. ** if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
  61209. ** u.az.r.flags = UNPACKED_INCRKEY;
  61210. ** }else{
  61211. ** u.az.r.flags = 0;
  61212. ** }
  61213. */
  61214. u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
  61215. assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
  61216. assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
  61217. assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
  61218. assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
  61219. u.az.r.aMem = &aMem[pOp->p3];
  61220. #ifdef SQLITE_DEBUG
  61221. { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
  61222. #endif
  61223. ExpandBlob(u.az.r.aMem);
  61224. rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
  61225. if( rc!=SQLITE_OK ){
  61226. goto abort_due_to_error;
  61227. }
  61228. u.az.pC->rowidIsValid = 0;
  61229. }
  61230. u.az.pC->deferredMoveto = 0;
  61231. u.az.pC->cacheStatus = CACHE_STALE;
  61232. #ifdef SQLITE_TEST
  61233. sqlite3_search_count++;
  61234. #endif
  61235. if( u.az.oc>=OP_SeekGe ){ assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
  61236. if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
  61237. rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
  61238. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  61239. u.az.pC->rowidIsValid = 0;
  61240. }else{
  61241. u.az.res = 0;
  61242. }
  61243. }else{
  61244. assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
  61245. if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
  61246. rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
  61247. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  61248. u.az.pC->rowidIsValid = 0;
  61249. }else{
  61250. /* u.az.res might be negative because the table is empty. Check to
  61251. ** see if this is the case.
  61252. */
  61253. u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
  61254. }
  61255. }
  61256. assert( pOp->p2>0 );
  61257. if( u.az.res ){
  61258. pc = pOp->p2 - 1;
  61259. }
  61260. }else{
  61261. /* This happens when attempting to open the sqlite3_master table
  61262. ** for read access returns SQLITE_EMPTY. In this case always
  61263. ** take the jump (since there are no records in the table).
  61264. */
  61265. pc = pOp->p2 - 1;
  61266. }
  61267. break;
  61268. }
  61269. /* Opcode: Seek P1 P2 * * *
  61270. **
  61271. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  61272. ** for P1 to move so that it points to the rowid given by P2.
  61273. **
  61274. ** This is actually a deferred seek. Nothing actually happens until
  61275. ** the cursor is used to read a record. That way, if no reads
  61276. ** occur, no unnecessary I/O happens.
  61277. */
  61278. case OP_Seek: { /* in2 */
  61279. #if 0 /* local variables moved into u.ba */
  61280. VdbeCursor *pC;
  61281. #endif /* local variables moved into u.ba */
  61282. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61283. u.ba.pC = p->apCsr[pOp->p1];
  61284. assert( u.ba.pC!=0 );
  61285. if( ALWAYS(u.ba.pC->pCursor!=0) ){
  61286. assert( u.ba.pC->isTable );
  61287. u.ba.pC->nullRow = 0;
  61288. pIn2 = &aMem[pOp->p2];
  61289. u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  61290. u.ba.pC->rowidIsValid = 0;
  61291. u.ba.pC->deferredMoveto = 1;
  61292. }
  61293. break;
  61294. }
  61295. /* Opcode: Found P1 P2 P3 P4 *
  61296. **
  61297. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  61298. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  61299. ** record.
  61300. **
  61301. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  61302. ** is a prefix of any entry in P1 then a jump is made to P2 and
  61303. ** P1 is left pointing at the matching entry.
  61304. */
  61305. /* Opcode: NotFound P1 P2 P3 P4 *
  61306. **
  61307. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  61308. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  61309. ** record.
  61310. **
  61311. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  61312. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  61313. ** does contain an entry whose prefix matches the P3/P4 record then control
  61314. ** falls through to the next instruction and P1 is left pointing at the
  61315. ** matching entry.
  61316. **
  61317. ** See also: Found, NotExists, IsUnique
  61318. */
  61319. case OP_NotFound: /* jump, in3 */
  61320. case OP_Found: { /* jump, in3 */
  61321. #if 0 /* local variables moved into u.bb */
  61322. int alreadyExists;
  61323. VdbeCursor *pC;
  61324. int res;
  61325. UnpackedRecord *pIdxKey;
  61326. UnpackedRecord r;
  61327. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  61328. #endif /* local variables moved into u.bb */
  61329. #ifdef SQLITE_TEST
  61330. sqlite3_found_count++;
  61331. #endif
  61332. u.bb.alreadyExists = 0;
  61333. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61334. assert( pOp->p4type==P4_INT32 );
  61335. u.bb.pC = p->apCsr[pOp->p1];
  61336. assert( u.bb.pC!=0 );
  61337. pIn3 = &aMem[pOp->p3];
  61338. if( ALWAYS(u.bb.pC->pCursor!=0) ){
  61339. assert( u.bb.pC->isTable==0 );
  61340. if( pOp->p4.i>0 ){
  61341. u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
  61342. u.bb.r.nField = (u16)pOp->p4.i;
  61343. u.bb.r.aMem = pIn3;
  61344. #ifdef SQLITE_DEBUG
  61345. { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
  61346. #endif
  61347. u.bb.r.flags = UNPACKED_PREFIX_MATCH;
  61348. u.bb.pIdxKey = &u.bb.r;
  61349. }else{
  61350. assert( pIn3->flags & MEM_Blob );
  61351. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  61352. u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
  61353. u.bb.aTempRec, sizeof(u.bb.aTempRec));
  61354. if( u.bb.pIdxKey==0 ){
  61355. goto no_mem;
  61356. }
  61357. u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  61358. }
  61359. rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
  61360. if( pOp->p4.i==0 ){
  61361. sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
  61362. }
  61363. if( rc!=SQLITE_OK ){
  61364. break;
  61365. }
  61366. u.bb.alreadyExists = (u.bb.res==0);
  61367. u.bb.pC->deferredMoveto = 0;
  61368. u.bb.pC->cacheStatus = CACHE_STALE;
  61369. }
  61370. if( pOp->opcode==OP_Found ){
  61371. if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
  61372. }else{
  61373. if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
  61374. }
  61375. break;
  61376. }
  61377. /* Opcode: IsUnique P1 P2 P3 P4 *
  61378. **
  61379. ** Cursor P1 is open on an index b-tree - that is to say, a btree which
  61380. ** no data and where the key are records generated by OP_MakeRecord with
  61381. ** the list field being the integer ROWID of the entry that the index
  61382. ** entry refers to.
  61383. **
  61384. ** The P3 register contains an integer record number. Call this record
  61385. ** number R. Register P4 is the first in a set of N contiguous registers
  61386. ** that make up an unpacked index key that can be used with cursor P1.
  61387. ** The value of N can be inferred from the cursor. N includes the rowid
  61388. ** value appended to the end of the index record. This rowid value may
  61389. ** or may not be the same as R.
  61390. **
  61391. ** If any of the N registers beginning with register P4 contains a NULL
  61392. ** value, jump immediately to P2.
  61393. **
  61394. ** Otherwise, this instruction checks if cursor P1 contains an entry
  61395. ** where the first (N-1) fields match but the rowid value at the end
  61396. ** of the index entry is not R. If there is no such entry, control jumps
  61397. ** to instruction P2. Otherwise, the rowid of the conflicting index
  61398. ** entry is copied to register P3 and control falls through to the next
  61399. ** instruction.
  61400. **
  61401. ** See also: NotFound, NotExists, Found
  61402. */
  61403. case OP_IsUnique: { /* jump, in3 */
  61404. #if 0 /* local variables moved into u.bc */
  61405. u16 ii;
  61406. VdbeCursor *pCx;
  61407. BtCursor *pCrsr;
  61408. u16 nField;
  61409. Mem *aMx;
  61410. UnpackedRecord r; /* B-Tree index search key */
  61411. i64 R; /* Rowid stored in register P3 */
  61412. #endif /* local variables moved into u.bc */
  61413. pIn3 = &aMem[pOp->p3];
  61414. u.bc.aMx = &aMem[pOp->p4.i];
  61415. /* Assert that the values of parameters P1 and P4 are in range. */
  61416. assert( pOp->p4type==P4_INT32 );
  61417. assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
  61418. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61419. /* Find the index cursor. */
  61420. u.bc.pCx = p->apCsr[pOp->p1];
  61421. assert( u.bc.pCx->deferredMoveto==0 );
  61422. u.bc.pCx->seekResult = 0;
  61423. u.bc.pCx->cacheStatus = CACHE_STALE;
  61424. u.bc.pCrsr = u.bc.pCx->pCursor;
  61425. /* If any of the values are NULL, take the jump. */
  61426. u.bc.nField = u.bc.pCx->pKeyInfo->nField;
  61427. for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
  61428. if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
  61429. pc = pOp->p2 - 1;
  61430. u.bc.pCrsr = 0;
  61431. break;
  61432. }
  61433. }
  61434. assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
  61435. if( u.bc.pCrsr!=0 ){
  61436. /* Populate the index search key. */
  61437. u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
  61438. u.bc.r.nField = u.bc.nField + 1;
  61439. u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
  61440. u.bc.r.aMem = u.bc.aMx;
  61441. #ifdef SQLITE_DEBUG
  61442. { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
  61443. #endif
  61444. /* Extract the value of u.bc.R from register P3. */
  61445. sqlite3VdbeMemIntegerify(pIn3);
  61446. u.bc.R = pIn3->u.i;
  61447. /* Search the B-Tree index. If no conflicting record is found, jump
  61448. ** to P2. Otherwise, copy the rowid of the conflicting record to
  61449. ** register P3 and fall through to the next instruction. */
  61450. rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
  61451. if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
  61452. pc = pOp->p2 - 1;
  61453. }else{
  61454. pIn3->u.i = u.bc.r.rowid;
  61455. }
  61456. }
  61457. break;
  61458. }
  61459. /* Opcode: NotExists P1 P2 P3 * *
  61460. **
  61461. ** Use the content of register P3 as a integer key. If a record
  61462. ** with that key does not exist in table of P1, then jump to P2.
  61463. ** If the record does exist, then fall through. The cursor is left
  61464. ** pointing to the record if it exists.
  61465. **
  61466. ** The difference between this operation and NotFound is that this
  61467. ** operation assumes the key is an integer and that P1 is a table whereas
  61468. ** NotFound assumes key is a blob constructed from MakeRecord and
  61469. ** P1 is an index.
  61470. **
  61471. ** See also: Found, NotFound, IsUnique
  61472. */
  61473. case OP_NotExists: { /* jump, in3 */
  61474. #if 0 /* local variables moved into u.bd */
  61475. VdbeCursor *pC;
  61476. BtCursor *pCrsr;
  61477. int res;
  61478. u64 iKey;
  61479. #endif /* local variables moved into u.bd */
  61480. pIn3 = &aMem[pOp->p3];
  61481. assert( pIn3->flags & MEM_Int );
  61482. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61483. u.bd.pC = p->apCsr[pOp->p1];
  61484. assert( u.bd.pC!=0 );
  61485. assert( u.bd.pC->isTable );
  61486. assert( u.bd.pC->pseudoTableReg==0 );
  61487. u.bd.pCrsr = u.bd.pC->pCursor;
  61488. if( u.bd.pCrsr!=0 ){
  61489. u.bd.res = 0;
  61490. u.bd.iKey = pIn3->u.i;
  61491. rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
  61492. u.bd.pC->lastRowid = pIn3->u.i;
  61493. u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
  61494. u.bd.pC->nullRow = 0;
  61495. u.bd.pC->cacheStatus = CACHE_STALE;
  61496. u.bd.pC->deferredMoveto = 0;
  61497. if( u.bd.res!=0 ){
  61498. pc = pOp->p2 - 1;
  61499. assert( u.bd.pC->rowidIsValid==0 );
  61500. }
  61501. u.bd.pC->seekResult = u.bd.res;
  61502. }else{
  61503. /* This happens when an attempt to open a read cursor on the
  61504. ** sqlite_master table returns SQLITE_EMPTY.
  61505. */
  61506. pc = pOp->p2 - 1;
  61507. assert( u.bd.pC->rowidIsValid==0 );
  61508. u.bd.pC->seekResult = 0;
  61509. }
  61510. break;
  61511. }
  61512. /* Opcode: Sequence P1 P2 * * *
  61513. **
  61514. ** Find the next available sequence number for cursor P1.
  61515. ** Write the sequence number into register P2.
  61516. ** The sequence number on the cursor is incremented after this
  61517. ** instruction.
  61518. */
  61519. case OP_Sequence: { /* out2-prerelease */
  61520. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61521. assert( p->apCsr[pOp->p1]!=0 );
  61522. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  61523. break;
  61524. }
  61525. /* Opcode: NewRowid P1 P2 P3 * *
  61526. **
  61527. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  61528. ** The record number is not previously used as a key in the database
  61529. ** table that cursor P1 points to. The new record number is written
  61530. ** written to register P2.
  61531. **
  61532. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  61533. ** the largest previously generated record number. No new record numbers are
  61534. ** allowed to be less than this value. When this value reaches its maximum,
  61535. ** a SQLITE_FULL error is generated. The P3 register is updated with the '
  61536. ** generated record number. This P3 mechanism is used to help implement the
  61537. ** AUTOINCREMENT feature.
  61538. */
  61539. case OP_NewRowid: { /* out2-prerelease */
  61540. #if 0 /* local variables moved into u.be */
  61541. i64 v; /* The new rowid */
  61542. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  61543. int res; /* Result of an sqlite3BtreeLast() */
  61544. int cnt; /* Counter to limit the number of searches */
  61545. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  61546. VdbeFrame *pFrame; /* Root frame of VDBE */
  61547. #endif /* local variables moved into u.be */
  61548. u.be.v = 0;
  61549. u.be.res = 0;
  61550. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61551. u.be.pC = p->apCsr[pOp->p1];
  61552. assert( u.be.pC!=0 );
  61553. if( NEVER(u.be.pC->pCursor==0) ){
  61554. /* The zero initialization above is all that is needed */
  61555. }else{
  61556. /* The next rowid or record number (different terms for the same
  61557. ** thing) is obtained in a two-step algorithm.
  61558. **
  61559. ** First we attempt to find the largest existing rowid and add one
  61560. ** to that. But if the largest existing rowid is already the maximum
  61561. ** positive integer, we have to fall through to the second
  61562. ** probabilistic algorithm
  61563. **
  61564. ** The second algorithm is to select a rowid at random and see if
  61565. ** it already exists in the table. If it does not exist, we have
  61566. ** succeeded. If the random rowid does exist, we select a new one
  61567. ** and try again, up to 100 times.
  61568. */
  61569. assert( u.be.pC->isTable );
  61570. #ifdef SQLITE_32BIT_ROWID
  61571. # define MAX_ROWID 0x7fffffff
  61572. #else
  61573. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  61574. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  61575. ** to provide the constant while making all compilers happy.
  61576. */
  61577. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  61578. #endif
  61579. if( !u.be.pC->useRandomRowid ){
  61580. u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
  61581. if( u.be.v==0 ){
  61582. rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
  61583. if( rc!=SQLITE_OK ){
  61584. goto abort_due_to_error;
  61585. }
  61586. if( u.be.res ){
  61587. u.be.v = 1; /* IMP: R-61914-48074 */
  61588. }else{
  61589. assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
  61590. rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
  61591. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  61592. if( u.be.v==MAX_ROWID ){
  61593. u.be.pC->useRandomRowid = 1;
  61594. }else{
  61595. u.be.v++; /* IMP: R-29538-34987 */
  61596. }
  61597. }
  61598. }
  61599. #ifndef SQLITE_OMIT_AUTOINCREMENT
  61600. if( pOp->p3 ){
  61601. /* Assert that P3 is a valid memory cell. */
  61602. assert( pOp->p3>0 );
  61603. if( p->pFrame ){
  61604. for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
  61605. /* Assert that P3 is a valid memory cell. */
  61606. assert( pOp->p3<=u.be.pFrame->nMem );
  61607. u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
  61608. }else{
  61609. /* Assert that P3 is a valid memory cell. */
  61610. assert( pOp->p3<=p->nMem );
  61611. u.be.pMem = &aMem[pOp->p3];
  61612. memAboutToChange(p, u.be.pMem);
  61613. }
  61614. assert( memIsValid(u.be.pMem) );
  61615. REGISTER_TRACE(pOp->p3, u.be.pMem);
  61616. sqlite3VdbeMemIntegerify(u.be.pMem);
  61617. assert( (u.be.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  61618. if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
  61619. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  61620. goto abort_due_to_error;
  61621. }
  61622. if( u.be.v<u.be.pMem->u.i+1 ){
  61623. u.be.v = u.be.pMem->u.i + 1;
  61624. }
  61625. u.be.pMem->u.i = u.be.v;
  61626. }
  61627. #endif
  61628. sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
  61629. }
  61630. if( u.be.pC->useRandomRowid ){
  61631. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  61632. ** largest possible integer (9223372036854775807) then the database
  61633. ** engine starts picking positive candidate ROWIDs at random until
  61634. ** it finds one that is not previously used. */
  61635. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  61636. ** an AUTOINCREMENT table. */
  61637. /* on the first attempt, simply do one more than previous */
  61638. u.be.v = db->lastRowid;
  61639. u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  61640. u.be.v++; /* ensure non-zero */
  61641. u.be.cnt = 0;
  61642. while( ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
  61643. 0, &u.be.res))==SQLITE_OK)
  61644. && (u.be.res==0)
  61645. && (++u.be.cnt<100)){
  61646. /* collision - try another random rowid */
  61647. sqlite3_randomness(sizeof(u.be.v), &u.be.v);
  61648. if( u.be.cnt<5 ){
  61649. /* try "small" random rowids for the initial attempts */
  61650. u.be.v &= 0xffffff;
  61651. }else{
  61652. u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  61653. }
  61654. u.be.v++; /* ensure non-zero */
  61655. }
  61656. if( rc==SQLITE_OK && u.be.res==0 ){
  61657. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  61658. goto abort_due_to_error;
  61659. }
  61660. assert( u.be.v>0 ); /* EV: R-40812-03570 */
  61661. }
  61662. u.be.pC->rowidIsValid = 0;
  61663. u.be.pC->deferredMoveto = 0;
  61664. u.be.pC->cacheStatus = CACHE_STALE;
  61665. }
  61666. pOut->u.i = u.be.v;
  61667. break;
  61668. }
  61669. /* Opcode: Insert P1 P2 P3 P4 P5
  61670. **
  61671. ** Write an entry into the table of cursor P1. A new entry is
  61672. ** created if it doesn't already exist or the data for an existing
  61673. ** entry is overwritten. The data is the value MEM_Blob stored in register
  61674. ** number P2. The key is stored in register P3. The key must
  61675. ** be a MEM_Int.
  61676. **
  61677. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  61678. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  61679. ** then rowid is stored for subsequent return by the
  61680. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  61681. **
  61682. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  61683. ** the last seek operation (OP_NotExists) was a success, then this
  61684. ** operation will not attempt to find the appropriate row before doing
  61685. ** the insert but will instead overwrite the row that the cursor is
  61686. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  61687. ** has already positioned the cursor correctly. This is an optimization
  61688. ** that boosts performance by avoiding redundant seeks.
  61689. **
  61690. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  61691. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  61692. ** is part of an INSERT operation. The difference is only important to
  61693. ** the update hook.
  61694. **
  61695. ** Parameter P4 may point to a string containing the table-name, or
  61696. ** may be NULL. If it is not NULL, then the update-hook
  61697. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  61698. **
  61699. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  61700. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  61701. ** and register P2 becomes ephemeral. If the cursor is changed, the
  61702. ** value of register P2 will then change. Make sure this does not
  61703. ** cause any problems.)
  61704. **
  61705. ** This instruction only works on tables. The equivalent instruction
  61706. ** for indices is OP_IdxInsert.
  61707. */
  61708. /* Opcode: InsertInt P1 P2 P3 P4 P5
  61709. **
  61710. ** This works exactly like OP_Insert except that the key is the
  61711. ** integer value P3, not the value of the integer stored in register P3.
  61712. */
  61713. case OP_Insert:
  61714. case OP_InsertInt: {
  61715. #if 0 /* local variables moved into u.bf */
  61716. Mem *pData; /* MEM cell holding data for the record to be inserted */
  61717. Mem *pKey; /* MEM cell holding key for the record */
  61718. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  61719. VdbeCursor *pC; /* Cursor to table into which insert is written */
  61720. int nZero; /* Number of zero-bytes to append */
  61721. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  61722. const char *zDb; /* database name - used by the update hook */
  61723. const char *zTbl; /* Table name - used by the opdate hook */
  61724. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  61725. #endif /* local variables moved into u.bf */
  61726. u.bf.pData = &aMem[pOp->p2];
  61727. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61728. assert( memIsValid(u.bf.pData) );
  61729. u.bf.pC = p->apCsr[pOp->p1];
  61730. assert( u.bf.pC!=0 );
  61731. assert( u.bf.pC->pCursor!=0 );
  61732. assert( u.bf.pC->pseudoTableReg==0 );
  61733. assert( u.bf.pC->isTable );
  61734. REGISTER_TRACE(pOp->p2, u.bf.pData);
  61735. if( pOp->opcode==OP_Insert ){
  61736. u.bf.pKey = &aMem[pOp->p3];
  61737. assert( u.bf.pKey->flags & MEM_Int );
  61738. assert( memIsValid(u.bf.pKey) );
  61739. REGISTER_TRACE(pOp->p3, u.bf.pKey);
  61740. u.bf.iKey = u.bf.pKey->u.i;
  61741. }else{
  61742. assert( pOp->opcode==OP_InsertInt );
  61743. u.bf.iKey = pOp->p3;
  61744. }
  61745. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  61746. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
  61747. if( u.bf.pData->flags & MEM_Null ){
  61748. u.bf.pData->z = 0;
  61749. u.bf.pData->n = 0;
  61750. }else{
  61751. assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
  61752. }
  61753. u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
  61754. if( u.bf.pData->flags & MEM_Zero ){
  61755. u.bf.nZero = u.bf.pData->u.nZero;
  61756. }else{
  61757. u.bf.nZero = 0;
  61758. }
  61759. sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
  61760. rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
  61761. u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
  61762. pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
  61763. );
  61764. u.bf.pC->rowidIsValid = 0;
  61765. u.bf.pC->deferredMoveto = 0;
  61766. u.bf.pC->cacheStatus = CACHE_STALE;
  61767. /* Invoke the update-hook if required. */
  61768. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  61769. u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
  61770. u.bf.zTbl = pOp->p4.z;
  61771. u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  61772. assert( u.bf.pC->isTable );
  61773. db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
  61774. assert( u.bf.pC->iDb>=0 );
  61775. }
  61776. break;
  61777. }
  61778. /* Opcode: Delete P1 P2 * P4 *
  61779. **
  61780. ** Delete the record at which the P1 cursor is currently pointing.
  61781. **
  61782. ** The cursor will be left pointing at either the next or the previous
  61783. ** record in the table. If it is left pointing at the next record, then
  61784. ** the next Next instruction will be a no-op. Hence it is OK to delete
  61785. ** a record from within an Next loop.
  61786. **
  61787. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  61788. ** incremented (otherwise not).
  61789. **
  61790. ** P1 must not be pseudo-table. It has to be a real table with
  61791. ** multiple rows.
  61792. **
  61793. ** If P4 is not NULL, then it is the name of the table that P1 is
  61794. ** pointing to. The update hook will be invoked, if it exists.
  61795. ** If P4 is not NULL then the P1 cursor must have been positioned
  61796. ** using OP_NotFound prior to invoking this opcode.
  61797. */
  61798. case OP_Delete: {
  61799. #if 0 /* local variables moved into u.bg */
  61800. i64 iKey;
  61801. VdbeCursor *pC;
  61802. #endif /* local variables moved into u.bg */
  61803. u.bg.iKey = 0;
  61804. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61805. u.bg.pC = p->apCsr[pOp->p1];
  61806. assert( u.bg.pC!=0 );
  61807. assert( u.bg.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  61808. /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
  61809. ** row being deleted.
  61810. */
  61811. if( db->xUpdateCallback && pOp->p4.z ){
  61812. assert( u.bg.pC->isTable );
  61813. assert( u.bg.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  61814. u.bg.iKey = u.bg.pC->lastRowid;
  61815. }
  61816. /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  61817. ** OP_Column on the same table without any intervening operations that
  61818. ** might move or invalidate the cursor. Hence cursor u.bg.pC is always pointing
  61819. ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  61820. ** below is always a no-op and cannot fail. We will run it anyhow, though,
  61821. ** to guard against future changes to the code generator.
  61822. **/
  61823. assert( u.bg.pC->deferredMoveto==0 );
  61824. rc = sqlite3VdbeCursorMoveto(u.bg.pC);
  61825. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  61826. sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
  61827. rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
  61828. u.bg.pC->cacheStatus = CACHE_STALE;
  61829. /* Invoke the update-hook if required. */
  61830. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  61831. const char *zDb = db->aDb[u.bg.pC->iDb].zName;
  61832. const char *zTbl = pOp->p4.z;
  61833. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
  61834. assert( u.bg.pC->iDb>=0 );
  61835. }
  61836. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  61837. break;
  61838. }
  61839. /* Opcode: ResetCount * * * * *
  61840. **
  61841. ** The value of the change counter is copied to the database handle
  61842. ** change counter (returned by subsequent calls to sqlite3_changes()).
  61843. ** Then the VMs internal change counter resets to 0.
  61844. ** This is used by trigger programs.
  61845. */
  61846. case OP_ResetCount: {
  61847. sqlite3VdbeSetChanges(db, p->nChange);
  61848. p->nChange = 0;
  61849. break;
  61850. }
  61851. /* Opcode: RowData P1 P2 * * *
  61852. **
  61853. ** Write into register P2 the complete row data for cursor P1.
  61854. ** There is no interpretation of the data.
  61855. ** It is just copied onto the P2 register exactly as
  61856. ** it is found in the database file.
  61857. **
  61858. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  61859. ** of a real table, not a pseudo-table.
  61860. */
  61861. /* Opcode: RowKey P1 P2 * * *
  61862. **
  61863. ** Write into register P2 the complete row key for cursor P1.
  61864. ** There is no interpretation of the data.
  61865. ** The key is copied onto the P3 register exactly as
  61866. ** it is found in the database file.
  61867. **
  61868. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  61869. ** of a real table, not a pseudo-table.
  61870. */
  61871. case OP_RowKey:
  61872. case OP_RowData: {
  61873. #if 0 /* local variables moved into u.bh */
  61874. VdbeCursor *pC;
  61875. BtCursor *pCrsr;
  61876. u32 n;
  61877. i64 n64;
  61878. #endif /* local variables moved into u.bh */
  61879. pOut = &aMem[pOp->p2];
  61880. memAboutToChange(p, pOut);
  61881. /* Note that RowKey and RowData are really exactly the same instruction */
  61882. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61883. u.bh.pC = p->apCsr[pOp->p1];
  61884. assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
  61885. assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
  61886. assert( u.bh.pC!=0 );
  61887. assert( u.bh.pC->nullRow==0 );
  61888. assert( u.bh.pC->pseudoTableReg==0 );
  61889. assert( u.bh.pC->pCursor!=0 );
  61890. u.bh.pCrsr = u.bh.pC->pCursor;
  61891. assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
  61892. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  61893. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  61894. ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
  61895. ** a no-op and can never fail. But we leave it in place as a safety.
  61896. */
  61897. assert( u.bh.pC->deferredMoveto==0 );
  61898. rc = sqlite3VdbeCursorMoveto(u.bh.pC);
  61899. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  61900. if( u.bh.pC->isIndex ){
  61901. assert( !u.bh.pC->isTable );
  61902. rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
  61903. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  61904. if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  61905. goto too_big;
  61906. }
  61907. u.bh.n = (u32)u.bh.n64;
  61908. }else{
  61909. rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
  61910. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  61911. if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  61912. goto too_big;
  61913. }
  61914. }
  61915. if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
  61916. goto no_mem;
  61917. }
  61918. pOut->n = u.bh.n;
  61919. MemSetTypeFlag(pOut, MEM_Blob);
  61920. if( u.bh.pC->isIndex ){
  61921. rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
  61922. }else{
  61923. rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
  61924. }
  61925. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  61926. UPDATE_MAX_BLOBSIZE(pOut);
  61927. break;
  61928. }
  61929. /* Opcode: Rowid P1 P2 * * *
  61930. **
  61931. ** Store in register P2 an integer which is the key of the table entry that
  61932. ** P1 is currently point to.
  61933. **
  61934. ** P1 can be either an ordinary table or a virtual table. There used to
  61935. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  61936. ** one opcode now works for both table types.
  61937. */
  61938. case OP_Rowid: { /* out2-prerelease */
  61939. #if 0 /* local variables moved into u.bi */
  61940. VdbeCursor *pC;
  61941. i64 v;
  61942. sqlite3_vtab *pVtab;
  61943. const sqlite3_module *pModule;
  61944. #endif /* local variables moved into u.bi */
  61945. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61946. u.bi.pC = p->apCsr[pOp->p1];
  61947. assert( u.bi.pC!=0 );
  61948. assert( u.bi.pC->pseudoTableReg==0 );
  61949. if( u.bi.pC->nullRow ){
  61950. pOut->flags = MEM_Null;
  61951. break;
  61952. }else if( u.bi.pC->deferredMoveto ){
  61953. u.bi.v = u.bi.pC->movetoTarget;
  61954. #ifndef SQLITE_OMIT_VIRTUALTABLE
  61955. }else if( u.bi.pC->pVtabCursor ){
  61956. u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
  61957. u.bi.pModule = u.bi.pVtab->pModule;
  61958. assert( u.bi.pModule->xRowid );
  61959. rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
  61960. importVtabErrMsg(p, u.bi.pVtab);
  61961. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  61962. }else{
  61963. assert( u.bi.pC->pCursor!=0 );
  61964. rc = sqlite3VdbeCursorMoveto(u.bi.pC);
  61965. if( rc ) goto abort_due_to_error;
  61966. if( u.bi.pC->rowidIsValid ){
  61967. u.bi.v = u.bi.pC->lastRowid;
  61968. }else{
  61969. rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
  61970. assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
  61971. }
  61972. }
  61973. pOut->u.i = u.bi.v;
  61974. break;
  61975. }
  61976. /* Opcode: NullRow P1 * * * *
  61977. **
  61978. ** Move the cursor P1 to a null row. Any OP_Column operations
  61979. ** that occur while the cursor is on the null row will always
  61980. ** write a NULL.
  61981. */
  61982. case OP_NullRow: {
  61983. #if 0 /* local variables moved into u.bj */
  61984. VdbeCursor *pC;
  61985. #endif /* local variables moved into u.bj */
  61986. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  61987. u.bj.pC = p->apCsr[pOp->p1];
  61988. assert( u.bj.pC!=0 );
  61989. u.bj.pC->nullRow = 1;
  61990. u.bj.pC->rowidIsValid = 0;
  61991. if( u.bj.pC->pCursor ){
  61992. sqlite3BtreeClearCursor(u.bj.pC->pCursor);
  61993. }
  61994. break;
  61995. }
  61996. /* Opcode: Last P1 P2 * * *
  61997. **
  61998. ** The next use of the Rowid or Column or Next instruction for P1
  61999. ** will refer to the last entry in the database table or index.
  62000. ** If the table or index is empty and P2>0, then jump immediately to P2.
  62001. ** If P2 is 0 or if the table or index is not empty, fall through
  62002. ** to the following instruction.
  62003. */
  62004. case OP_Last: { /* jump */
  62005. #if 0 /* local variables moved into u.bk */
  62006. VdbeCursor *pC;
  62007. BtCursor *pCrsr;
  62008. int res;
  62009. #endif /* local variables moved into u.bk */
  62010. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62011. u.bk.pC = p->apCsr[pOp->p1];
  62012. assert( u.bk.pC!=0 );
  62013. u.bk.pCrsr = u.bk.pC->pCursor;
  62014. if( u.bk.pCrsr==0 ){
  62015. u.bk.res = 1;
  62016. }else{
  62017. rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
  62018. }
  62019. u.bk.pC->nullRow = (u8)u.bk.res;
  62020. u.bk.pC->deferredMoveto = 0;
  62021. u.bk.pC->rowidIsValid = 0;
  62022. u.bk.pC->cacheStatus = CACHE_STALE;
  62023. if( pOp->p2>0 && u.bk.res ){
  62024. pc = pOp->p2 - 1;
  62025. }
  62026. break;
  62027. }
  62028. /* Opcode: Sort P1 P2 * * *
  62029. **
  62030. ** This opcode does exactly the same thing as OP_Rewind except that
  62031. ** it increments an undocumented global variable used for testing.
  62032. **
  62033. ** Sorting is accomplished by writing records into a sorting index,
  62034. ** then rewinding that index and playing it back from beginning to
  62035. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  62036. ** rewinding so that the global variable will be incremented and
  62037. ** regression tests can determine whether or not the optimizer is
  62038. ** correctly optimizing out sorts.
  62039. */
  62040. case OP_Sort: { /* jump */
  62041. #ifdef SQLITE_TEST
  62042. sqlite3_sort_count++;
  62043. sqlite3_search_count--;
  62044. #endif
  62045. p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
  62046. /* Fall through into OP_Rewind */
  62047. }
  62048. /* Opcode: Rewind P1 P2 * * *
  62049. **
  62050. ** The next use of the Rowid or Column or Next instruction for P1
  62051. ** will refer to the first entry in the database table or index.
  62052. ** If the table or index is empty and P2>0, then jump immediately to P2.
  62053. ** If P2 is 0 or if the table or index is not empty, fall through
  62054. ** to the following instruction.
  62055. */
  62056. case OP_Rewind: { /* jump */
  62057. #if 0 /* local variables moved into u.bl */
  62058. VdbeCursor *pC;
  62059. BtCursor *pCrsr;
  62060. int res;
  62061. #endif /* local variables moved into u.bl */
  62062. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62063. u.bl.pC = p->apCsr[pOp->p1];
  62064. assert( u.bl.pC!=0 );
  62065. u.bl.res = 1;
  62066. if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
  62067. rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
  62068. u.bl.pC->atFirst = u.bl.res==0 ?1:0;
  62069. u.bl.pC->deferredMoveto = 0;
  62070. u.bl.pC->cacheStatus = CACHE_STALE;
  62071. u.bl.pC->rowidIsValid = 0;
  62072. }
  62073. u.bl.pC->nullRow = (u8)u.bl.res;
  62074. assert( pOp->p2>0 && pOp->p2<p->nOp );
  62075. if( u.bl.res ){
  62076. pc = pOp->p2 - 1;
  62077. }
  62078. break;
  62079. }
  62080. /* Opcode: Next P1 P2 * * P5
  62081. **
  62082. ** Advance cursor P1 so that it points to the next key/data pair in its
  62083. ** table or index. If there are no more key/value pairs then fall through
  62084. ** to the following instruction. But if the cursor advance was successful,
  62085. ** jump immediately to P2.
  62086. **
  62087. ** The P1 cursor must be for a real table, not a pseudo-table.
  62088. **
  62089. ** If P5 is positive and the jump is taken, then event counter
  62090. ** number P5-1 in the prepared statement is incremented.
  62091. **
  62092. ** See also: Prev
  62093. */
  62094. /* Opcode: Prev P1 P2 * * P5
  62095. **
  62096. ** Back up cursor P1 so that it points to the previous key/data pair in its
  62097. ** table or index. If there is no previous key/value pairs then fall through
  62098. ** to the following instruction. But if the cursor backup was successful,
  62099. ** jump immediately to P2.
  62100. **
  62101. ** The P1 cursor must be for a real table, not a pseudo-table.
  62102. **
  62103. ** If P5 is positive and the jump is taken, then event counter
  62104. ** number P5-1 in the prepared statement is incremented.
  62105. */
  62106. case OP_Prev: /* jump */
  62107. case OP_Next: { /* jump */
  62108. #if 0 /* local variables moved into u.bm */
  62109. VdbeCursor *pC;
  62110. BtCursor *pCrsr;
  62111. int res;
  62112. #endif /* local variables moved into u.bm */
  62113. CHECK_FOR_INTERRUPT;
  62114. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62115. assert( pOp->p5<=ArraySize(p->aCounter) );
  62116. u.bm.pC = p->apCsr[pOp->p1];
  62117. if( u.bm.pC==0 ){
  62118. break; /* See ticket #2273 */
  62119. }
  62120. u.bm.pCrsr = u.bm.pC->pCursor;
  62121. if( u.bm.pCrsr==0 ){
  62122. u.bm.pC->nullRow = 1;
  62123. break;
  62124. }
  62125. u.bm.res = 1;
  62126. assert( u.bm.pC->deferredMoveto==0 );
  62127. rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
  62128. sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
  62129. u.bm.pC->nullRow = (u8)u.bm.res;
  62130. u.bm.pC->cacheStatus = CACHE_STALE;
  62131. if( u.bm.res==0 ){
  62132. pc = pOp->p2 - 1;
  62133. if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
  62134. #ifdef SQLITE_TEST
  62135. sqlite3_search_count++;
  62136. #endif
  62137. }
  62138. u.bm.pC->rowidIsValid = 0;
  62139. break;
  62140. }
  62141. /* Opcode: IdxInsert P1 P2 P3 * P5
  62142. **
  62143. ** Register P2 holds a SQL index key made using the
  62144. ** MakeRecord instructions. This opcode writes that key
  62145. ** into the index P1. Data for the entry is nil.
  62146. **
  62147. ** P3 is a flag that provides a hint to the b-tree layer that this
  62148. ** insert is likely to be an append.
  62149. **
  62150. ** This instruction only works for indices. The equivalent instruction
  62151. ** for tables is OP_Insert.
  62152. */
  62153. case OP_IdxInsert: { /* in2 */
  62154. #if 0 /* local variables moved into u.bn */
  62155. VdbeCursor *pC;
  62156. BtCursor *pCrsr;
  62157. int nKey;
  62158. const char *zKey;
  62159. #endif /* local variables moved into u.bn */
  62160. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62161. u.bn.pC = p->apCsr[pOp->p1];
  62162. assert( u.bn.pC!=0 );
  62163. pIn2 = &aMem[pOp->p2];
  62164. assert( pIn2->flags & MEM_Blob );
  62165. u.bn.pCrsr = u.bn.pC->pCursor;
  62166. if( ALWAYS(u.bn.pCrsr!=0) ){
  62167. assert( u.bn.pC->isTable==0 );
  62168. rc = ExpandBlob(pIn2);
  62169. if( rc==SQLITE_OK ){
  62170. u.bn.nKey = pIn2->n;
  62171. u.bn.zKey = pIn2->z;
  62172. rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
  62173. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
  62174. );
  62175. assert( u.bn.pC->deferredMoveto==0 );
  62176. u.bn.pC->cacheStatus = CACHE_STALE;
  62177. }
  62178. }
  62179. break;
  62180. }
  62181. /* Opcode: IdxDelete P1 P2 P3 * *
  62182. **
  62183. ** The content of P3 registers starting at register P2 form
  62184. ** an unpacked index key. This opcode removes that entry from the
  62185. ** index opened by cursor P1.
  62186. */
  62187. case OP_IdxDelete: {
  62188. #if 0 /* local variables moved into u.bo */
  62189. VdbeCursor *pC;
  62190. BtCursor *pCrsr;
  62191. int res;
  62192. UnpackedRecord r;
  62193. #endif /* local variables moved into u.bo */
  62194. assert( pOp->p3>0 );
  62195. assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
  62196. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62197. u.bo.pC = p->apCsr[pOp->p1];
  62198. assert( u.bo.pC!=0 );
  62199. u.bo.pCrsr = u.bo.pC->pCursor;
  62200. if( ALWAYS(u.bo.pCrsr!=0) ){
  62201. u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
  62202. u.bo.r.nField = (u16)pOp->p3;
  62203. u.bo.r.flags = 0;
  62204. u.bo.r.aMem = &aMem[pOp->p2];
  62205. #ifdef SQLITE_DEBUG
  62206. { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
  62207. #endif
  62208. rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
  62209. if( rc==SQLITE_OK && u.bo.res==0 ){
  62210. rc = sqlite3BtreeDelete(u.bo.pCrsr);
  62211. }
  62212. assert( u.bo.pC->deferredMoveto==0 );
  62213. u.bo.pC->cacheStatus = CACHE_STALE;
  62214. }
  62215. break;
  62216. }
  62217. /* Opcode: IdxRowid P1 P2 * * *
  62218. **
  62219. ** Write into register P2 an integer which is the last entry in the record at
  62220. ** the end of the index key pointed to by cursor P1. This integer should be
  62221. ** the rowid of the table entry to which this index entry points.
  62222. **
  62223. ** See also: Rowid, MakeRecord.
  62224. */
  62225. case OP_IdxRowid: { /* out2-prerelease */
  62226. #if 0 /* local variables moved into u.bp */
  62227. BtCursor *pCrsr;
  62228. VdbeCursor *pC;
  62229. i64 rowid;
  62230. #endif /* local variables moved into u.bp */
  62231. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62232. u.bp.pC = p->apCsr[pOp->p1];
  62233. assert( u.bp.pC!=0 );
  62234. u.bp.pCrsr = u.bp.pC->pCursor;
  62235. pOut->flags = MEM_Null;
  62236. if( ALWAYS(u.bp.pCrsr!=0) ){
  62237. rc = sqlite3VdbeCursorMoveto(u.bp.pC);
  62238. if( NEVER(rc) ) goto abort_due_to_error;
  62239. assert( u.bp.pC->deferredMoveto==0 );
  62240. assert( u.bp.pC->isTable==0 );
  62241. if( !u.bp.pC->nullRow ){
  62242. rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
  62243. if( rc!=SQLITE_OK ){
  62244. goto abort_due_to_error;
  62245. }
  62246. pOut->u.i = u.bp.rowid;
  62247. pOut->flags = MEM_Int;
  62248. }
  62249. }
  62250. break;
  62251. }
  62252. /* Opcode: IdxGE P1 P2 P3 P4 P5
  62253. **
  62254. ** The P4 register values beginning with P3 form an unpacked index
  62255. ** key that omits the ROWID. Compare this key value against the index
  62256. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  62257. **
  62258. ** If the P1 index entry is greater than or equal to the key value
  62259. ** then jump to P2. Otherwise fall through to the next instruction.
  62260. **
  62261. ** If P5 is non-zero then the key value is increased by an epsilon
  62262. ** prior to the comparison. This make the opcode work like IdxGT except
  62263. ** that if the key from register P3 is a prefix of the key in the cursor,
  62264. ** the result is false whereas it would be true with IdxGT.
  62265. */
  62266. /* Opcode: IdxLT P1 P2 P3 P4 P5
  62267. **
  62268. ** The P4 register values beginning with P3 form an unpacked index
  62269. ** key that omits the ROWID. Compare this key value against the index
  62270. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  62271. **
  62272. ** If the P1 index entry is less than the key value then jump to P2.
  62273. ** Otherwise fall through to the next instruction.
  62274. **
  62275. ** If P5 is non-zero then the key value is increased by an epsilon prior
  62276. ** to the comparison. This makes the opcode work like IdxLE.
  62277. */
  62278. case OP_IdxLT: /* jump */
  62279. case OP_IdxGE: { /* jump */
  62280. #if 0 /* local variables moved into u.bq */
  62281. VdbeCursor *pC;
  62282. int res;
  62283. UnpackedRecord r;
  62284. #endif /* local variables moved into u.bq */
  62285. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  62286. u.bq.pC = p->apCsr[pOp->p1];
  62287. assert( u.bq.pC!=0 );
  62288. assert( u.bq.pC->isOrdered );
  62289. if( ALWAYS(u.bq.pC->pCursor!=0) ){
  62290. assert( u.bq.pC->deferredMoveto==0 );
  62291. assert( pOp->p5==0 || pOp->p5==1 );
  62292. assert( pOp->p4type==P4_INT32 );
  62293. u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
  62294. u.bq.r.nField = (u16)pOp->p4.i;
  62295. if( pOp->p5 ){
  62296. u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
  62297. }else{
  62298. u.bq.r.flags = UNPACKED_IGNORE_ROWID;
  62299. }
  62300. u.bq.r.aMem = &aMem[pOp->p3];
  62301. #ifdef SQLITE_DEBUG
  62302. { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
  62303. #endif
  62304. rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
  62305. if( pOp->opcode==OP_IdxLT ){
  62306. u.bq.res = -u.bq.res;
  62307. }else{
  62308. assert( pOp->opcode==OP_IdxGE );
  62309. u.bq.res++;
  62310. }
  62311. if( u.bq.res>0 ){
  62312. pc = pOp->p2 - 1 ;
  62313. }
  62314. }
  62315. break;
  62316. }
  62317. /* Opcode: Destroy P1 P2 P3 * *
  62318. **
  62319. ** Delete an entire database table or index whose root page in the database
  62320. ** file is given by P1.
  62321. **
  62322. ** The table being destroyed is in the main database file if P3==0. If
  62323. ** P3==1 then the table to be clear is in the auxiliary database file
  62324. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  62325. **
  62326. ** If AUTOVACUUM is enabled then it is possible that another root page
  62327. ** might be moved into the newly deleted root page in order to keep all
  62328. ** root pages contiguous at the beginning of the database. The former
  62329. ** value of the root page that moved - its value before the move occurred -
  62330. ** is stored in register P2. If no page
  62331. ** movement was required (because the table being dropped was already
  62332. ** the last one in the database) then a zero is stored in register P2.
  62333. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  62334. **
  62335. ** See also: Clear
  62336. */
  62337. case OP_Destroy: { /* out2-prerelease */
  62338. #if 0 /* local variables moved into u.br */
  62339. int iMoved;
  62340. int iCnt;
  62341. Vdbe *pVdbe;
  62342. int iDb;
  62343. #endif /* local variables moved into u.br */
  62344. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62345. u.br.iCnt = 0;
  62346. for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
  62347. if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
  62348. u.br.iCnt++;
  62349. }
  62350. }
  62351. #else
  62352. u.br.iCnt = db->activeVdbeCnt;
  62353. #endif
  62354. pOut->flags = MEM_Null;
  62355. if( u.br.iCnt>1 ){
  62356. rc = SQLITE_LOCKED;
  62357. p->errorAction = OE_Abort;
  62358. }else{
  62359. u.br.iDb = pOp->p3;
  62360. assert( u.br.iCnt==1 );
  62361. assert( (p->btreeMask & (((yDbMask)1)<<u.br.iDb))!=0 );
  62362. rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
  62363. pOut->flags = MEM_Int;
  62364. pOut->u.i = u.br.iMoved;
  62365. #ifndef SQLITE_OMIT_AUTOVACUUM
  62366. if( rc==SQLITE_OK && u.br.iMoved!=0 ){
  62367. sqlite3RootPageMoved(db, u.br.iDb, u.br.iMoved, pOp->p1);
  62368. /* All OP_Destroy operations occur on the same btree */
  62369. assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.br.iDb+1 );
  62370. resetSchemaOnFault = u.br.iDb+1;
  62371. }
  62372. #endif
  62373. }
  62374. break;
  62375. }
  62376. /* Opcode: Clear P1 P2 P3
  62377. **
  62378. ** Delete all contents of the database table or index whose root page
  62379. ** in the database file is given by P1. But, unlike Destroy, do not
  62380. ** remove the table or index from the database file.
  62381. **
  62382. ** The table being clear is in the main database file if P2==0. If
  62383. ** P2==1 then the table to be clear is in the auxiliary database file
  62384. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  62385. **
  62386. ** If the P3 value is non-zero, then the table referred to must be an
  62387. ** intkey table (an SQL table, not an index). In this case the row change
  62388. ** count is incremented by the number of rows in the table being cleared.
  62389. ** If P3 is greater than zero, then the value stored in register P3 is
  62390. ** also incremented by the number of rows in the table being cleared.
  62391. **
  62392. ** See also: Destroy
  62393. */
  62394. case OP_Clear: {
  62395. #if 0 /* local variables moved into u.bs */
  62396. int nChange;
  62397. #endif /* local variables moved into u.bs */
  62398. u.bs.nChange = 0;
  62399. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  62400. rc = sqlite3BtreeClearTable(
  62401. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
  62402. );
  62403. if( pOp->p3 ){
  62404. p->nChange += u.bs.nChange;
  62405. if( pOp->p3>0 ){
  62406. assert( memIsValid(&aMem[pOp->p3]) );
  62407. memAboutToChange(p, &aMem[pOp->p3]);
  62408. aMem[pOp->p3].u.i += u.bs.nChange;
  62409. }
  62410. }
  62411. break;
  62412. }
  62413. /* Opcode: CreateTable P1 P2 * * *
  62414. **
  62415. ** Allocate a new table in the main database file if P1==0 or in the
  62416. ** auxiliary database file if P1==1 or in an attached database if
  62417. ** P1>1. Write the root page number of the new table into
  62418. ** register P2
  62419. **
  62420. ** The difference between a table and an index is this: A table must
  62421. ** have a 4-byte integer key and can have arbitrary data. An index
  62422. ** has an arbitrary key but no data.
  62423. **
  62424. ** See also: CreateIndex
  62425. */
  62426. /* Opcode: CreateIndex P1 P2 * * *
  62427. **
  62428. ** Allocate a new index in the main database file if P1==0 or in the
  62429. ** auxiliary database file if P1==1 or in an attached database if
  62430. ** P1>1. Write the root page number of the new table into
  62431. ** register P2.
  62432. **
  62433. ** See documentation on OP_CreateTable for additional information.
  62434. */
  62435. case OP_CreateIndex: /* out2-prerelease */
  62436. case OP_CreateTable: { /* out2-prerelease */
  62437. #if 0 /* local variables moved into u.bt */
  62438. int pgno;
  62439. int flags;
  62440. Db *pDb;
  62441. #endif /* local variables moved into u.bt */
  62442. u.bt.pgno = 0;
  62443. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  62444. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  62445. u.bt.pDb = &db->aDb[pOp->p1];
  62446. assert( u.bt.pDb->pBt!=0 );
  62447. if( pOp->opcode==OP_CreateTable ){
  62448. /* u.bt.flags = BTREE_INTKEY; */
  62449. u.bt.flags = BTREE_INTKEY;
  62450. }else{
  62451. u.bt.flags = BTREE_BLOBKEY;
  62452. }
  62453. rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
  62454. pOut->u.i = u.bt.pgno;
  62455. break;
  62456. }
  62457. /* Opcode: ParseSchema P1 * * P4 *
  62458. **
  62459. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  62460. ** that match the WHERE clause P4.
  62461. **
  62462. ** This opcode invokes the parser to create a new virtual machine,
  62463. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  62464. */
  62465. case OP_ParseSchema: {
  62466. #if 0 /* local variables moved into u.bu */
  62467. int iDb;
  62468. const char *zMaster;
  62469. char *zSql;
  62470. InitData initData;
  62471. #endif /* local variables moved into u.bu */
  62472. /* Any prepared statement that invokes this opcode will hold mutexes
  62473. ** on every btree. This is a prerequisite for invoking
  62474. ** sqlite3InitCallback().
  62475. */
  62476. #ifdef SQLITE_DEBUG
  62477. for(u.bu.iDb=0; u.bu.iDb<db->nDb; u.bu.iDb++){
  62478. assert( u.bu.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
  62479. }
  62480. #endif
  62481. u.bu.iDb = pOp->p1;
  62482. assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
  62483. assert( DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) );
  62484. /* Used to be a conditional */ {
  62485. u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
  62486. u.bu.initData.db = db;
  62487. u.bu.initData.iDb = pOp->p1;
  62488. u.bu.initData.pzErrMsg = &p->zErrMsg;
  62489. u.bu.zSql = sqlite3MPrintf(db,
  62490. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  62491. db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
  62492. if( u.bu.zSql==0 ){
  62493. rc = SQLITE_NOMEM;
  62494. }else{
  62495. assert( db->init.busy==0 );
  62496. db->init.busy = 1;
  62497. u.bu.initData.rc = SQLITE_OK;
  62498. assert( !db->mallocFailed );
  62499. rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
  62500. if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
  62501. sqlite3DbFree(db, u.bu.zSql);
  62502. db->init.busy = 0;
  62503. }
  62504. }
  62505. if( rc==SQLITE_NOMEM ){
  62506. goto no_mem;
  62507. }
  62508. break;
  62509. }
  62510. #if !defined(SQLITE_OMIT_ANALYZE)
  62511. /* Opcode: LoadAnalysis P1 * * * *
  62512. **
  62513. ** Read the sqlite_stat1 table for database P1 and load the content
  62514. ** of that table into the internal index hash table. This will cause
  62515. ** the analysis to be used when preparing all subsequent queries.
  62516. */
  62517. case OP_LoadAnalysis: {
  62518. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  62519. rc = sqlite3AnalysisLoad(db, pOp->p1);
  62520. break;
  62521. }
  62522. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  62523. /* Opcode: DropTable P1 * * P4 *
  62524. **
  62525. ** Remove the internal (in-memory) data structures that describe
  62526. ** the table named P4 in database P1. This is called after a table
  62527. ** is dropped in order to keep the internal representation of the
  62528. ** schema consistent with what is on disk.
  62529. */
  62530. case OP_DropTable: {
  62531. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  62532. break;
  62533. }
  62534. /* Opcode: DropIndex P1 * * P4 *
  62535. **
  62536. ** Remove the internal (in-memory) data structures that describe
  62537. ** the index named P4 in database P1. This is called after an index
  62538. ** is dropped in order to keep the internal representation of the
  62539. ** schema consistent with what is on disk.
  62540. */
  62541. case OP_DropIndex: {
  62542. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  62543. break;
  62544. }
  62545. /* Opcode: DropTrigger P1 * * P4 *
  62546. **
  62547. ** Remove the internal (in-memory) data structures that describe
  62548. ** the trigger named P4 in database P1. This is called after a trigger
  62549. ** is dropped in order to keep the internal representation of the
  62550. ** schema consistent with what is on disk.
  62551. */
  62552. case OP_DropTrigger: {
  62553. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  62554. break;
  62555. }
  62556. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  62557. /* Opcode: IntegrityCk P1 P2 P3 * P5
  62558. **
  62559. ** Do an analysis of the currently open database. Store in
  62560. ** register P1 the text of an error message describing any problems.
  62561. ** If no problems are found, store a NULL in register P1.
  62562. **
  62563. ** The register P3 contains the maximum number of allowed errors.
  62564. ** At most reg(P3) errors will be reported.
  62565. ** In other words, the analysis stops as soon as reg(P1) errors are
  62566. ** seen. Reg(P1) is updated with the number of errors remaining.
  62567. **
  62568. ** The root page numbers of all tables in the database are integer
  62569. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  62570. ** total.
  62571. **
  62572. ** If P5 is not zero, the check is done on the auxiliary database
  62573. ** file, not the main database file.
  62574. **
  62575. ** This opcode is used to implement the integrity_check pragma.
  62576. */
  62577. case OP_IntegrityCk: {
  62578. #if 0 /* local variables moved into u.bv */
  62579. int nRoot; /* Number of tables to check. (Number of root pages.) */
  62580. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  62581. int j; /* Loop counter */
  62582. int nErr; /* Number of errors reported */
  62583. char *z; /* Text of the error report */
  62584. Mem *pnErr; /* Register keeping track of errors remaining */
  62585. #endif /* local variables moved into u.bv */
  62586. u.bv.nRoot = pOp->p2;
  62587. assert( u.bv.nRoot>0 );
  62588. u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
  62589. if( u.bv.aRoot==0 ) goto no_mem;
  62590. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  62591. u.bv.pnErr = &aMem[pOp->p3];
  62592. assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
  62593. assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  62594. pIn1 = &aMem[pOp->p1];
  62595. for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
  62596. u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
  62597. }
  62598. u.bv.aRoot[u.bv.j] = 0;
  62599. assert( pOp->p5<db->nDb );
  62600. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
  62601. u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
  62602. (int)u.bv.pnErr->u.i, &u.bv.nErr);
  62603. sqlite3DbFree(db, u.bv.aRoot);
  62604. u.bv.pnErr->u.i -= u.bv.nErr;
  62605. sqlite3VdbeMemSetNull(pIn1);
  62606. if( u.bv.nErr==0 ){
  62607. assert( u.bv.z==0 );
  62608. }else if( u.bv.z==0 ){
  62609. goto no_mem;
  62610. }else{
  62611. sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
  62612. }
  62613. UPDATE_MAX_BLOBSIZE(pIn1);
  62614. sqlite3VdbeChangeEncoding(pIn1, encoding);
  62615. break;
  62616. }
  62617. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  62618. /* Opcode: RowSetAdd P1 P2 * * *
  62619. **
  62620. ** Insert the integer value held by register P2 into a boolean index
  62621. ** held in register P1.
  62622. **
  62623. ** An assertion fails if P2 is not an integer.
  62624. */
  62625. case OP_RowSetAdd: { /* in1, in2 */
  62626. pIn1 = &aMem[pOp->p1];
  62627. pIn2 = &aMem[pOp->p2];
  62628. assert( (pIn2->flags & MEM_Int)!=0 );
  62629. if( (pIn1->flags & MEM_RowSet)==0 ){
  62630. sqlite3VdbeMemSetRowSet(pIn1);
  62631. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  62632. }
  62633. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  62634. break;
  62635. }
  62636. /* Opcode: RowSetRead P1 P2 P3 * *
  62637. **
  62638. ** Extract the smallest value from boolean index P1 and put that value into
  62639. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  62640. ** unchanged and jump to instruction P2.
  62641. */
  62642. case OP_RowSetRead: { /* jump, in1, out3 */
  62643. #if 0 /* local variables moved into u.bw */
  62644. i64 val;
  62645. #endif /* local variables moved into u.bw */
  62646. CHECK_FOR_INTERRUPT;
  62647. pIn1 = &aMem[pOp->p1];
  62648. if( (pIn1->flags & MEM_RowSet)==0
  62649. || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
  62650. ){
  62651. /* The boolean index is empty */
  62652. sqlite3VdbeMemSetNull(pIn1);
  62653. pc = pOp->p2 - 1;
  62654. }else{
  62655. /* A value was pulled from the index */
  62656. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
  62657. }
  62658. break;
  62659. }
  62660. /* Opcode: RowSetTest P1 P2 P3 P4
  62661. **
  62662. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  62663. ** contains a RowSet object and that RowSet object contains
  62664. ** the value held in P3, jump to register P2. Otherwise, insert the
  62665. ** integer in P3 into the RowSet and continue on to the
  62666. ** next opcode.
  62667. **
  62668. ** The RowSet object is optimized for the case where successive sets
  62669. ** of integers, where each set contains no duplicates. Each set
  62670. ** of values is identified by a unique P4 value. The first set
  62671. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  62672. ** non-negative. For non-negative values of P4 only the lower 4
  62673. ** bits are significant.
  62674. **
  62675. ** This allows optimizations: (a) when P4==0 there is no need to test
  62676. ** the rowset object for P3, as it is guaranteed not to contain it,
  62677. ** (b) when P4==-1 there is no need to insert the value, as it will
  62678. ** never be tested for, and (c) when a value that is part of set X is
  62679. ** inserted, there is no need to search to see if the same value was
  62680. ** previously inserted as part of set X (only if it was previously
  62681. ** inserted as part of some other set).
  62682. */
  62683. case OP_RowSetTest: { /* jump, in1, in3 */
  62684. #if 0 /* local variables moved into u.bx */
  62685. int iSet;
  62686. int exists;
  62687. #endif /* local variables moved into u.bx */
  62688. pIn1 = &aMem[pOp->p1];
  62689. pIn3 = &aMem[pOp->p3];
  62690. u.bx.iSet = pOp->p4.i;
  62691. assert( pIn3->flags&MEM_Int );
  62692. /* If there is anything other than a rowset object in memory cell P1,
  62693. ** delete it now and initialize P1 with an empty rowset
  62694. */
  62695. if( (pIn1->flags & MEM_RowSet)==0 ){
  62696. sqlite3VdbeMemSetRowSet(pIn1);
  62697. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  62698. }
  62699. assert( pOp->p4type==P4_INT32 );
  62700. assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
  62701. if( u.bx.iSet ){
  62702. u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
  62703. (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
  62704. pIn3->u.i);
  62705. if( u.bx.exists ){
  62706. pc = pOp->p2 - 1;
  62707. break;
  62708. }
  62709. }
  62710. if( u.bx.iSet>=0 ){
  62711. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  62712. }
  62713. break;
  62714. }
  62715. #ifndef SQLITE_OMIT_TRIGGER
  62716. /* Opcode: Program P1 P2 P3 P4 *
  62717. **
  62718. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  62719. **
  62720. ** P1 contains the address of the memory cell that contains the first memory
  62721. ** cell in an array of values used as arguments to the sub-program. P2
  62722. ** contains the address to jump to if the sub-program throws an IGNORE
  62723. ** exception using the RAISE() function. Register P3 contains the address
  62724. ** of a memory cell in this (the parent) VM that is used to allocate the
  62725. ** memory required by the sub-vdbe at runtime.
  62726. **
  62727. ** P4 is a pointer to the VM containing the trigger program.
  62728. */
  62729. case OP_Program: { /* jump */
  62730. #if 0 /* local variables moved into u.by */
  62731. int nMem; /* Number of memory registers for sub-program */
  62732. int nByte; /* Bytes of runtime space required for sub-program */
  62733. Mem *pRt; /* Register to allocate runtime space */
  62734. Mem *pMem; /* Used to iterate through memory cells */
  62735. Mem *pEnd; /* Last memory cell in new array */
  62736. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  62737. SubProgram *pProgram; /* Sub-program to execute */
  62738. void *t; /* Token identifying trigger */
  62739. #endif /* local variables moved into u.by */
  62740. u.by.pProgram = pOp->p4.pProgram;
  62741. u.by.pRt = &aMem[pOp->p3];
  62742. assert( memIsValid(u.by.pRt) );
  62743. assert( u.by.pProgram->nOp>0 );
  62744. /* If the p5 flag is clear, then recursive invocation of triggers is
  62745. ** disabled for backwards compatibility (p5 is set if this sub-program
  62746. ** is really a trigger, not a foreign key action, and the flag set
  62747. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  62748. **
  62749. ** It is recursive invocation of triggers, at the SQL level, that is
  62750. ** disabled. In some cases a single trigger may generate more than one
  62751. ** SubProgram (if the trigger may be executed with more than one different
  62752. ** ON CONFLICT algorithm). SubProgram structures associated with a
  62753. ** single trigger all have the same value for the SubProgram.token
  62754. ** variable. */
  62755. if( pOp->p5 ){
  62756. u.by.t = u.by.pProgram->token;
  62757. for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
  62758. if( u.by.pFrame ) break;
  62759. }
  62760. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  62761. rc = SQLITE_ERROR;
  62762. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  62763. break;
  62764. }
  62765. /* Register u.by.pRt is used to store the memory required to save the state
  62766. ** of the current program, and the memory required at runtime to execute
  62767. ** the trigger program. If this trigger has been fired before, then u.by.pRt
  62768. ** is already allocated. Otherwise, it must be initialized. */
  62769. if( (u.by.pRt->flags&MEM_Frame)==0 ){
  62770. /* SubProgram.nMem is set to the number of memory cells used by the
  62771. ** program stored in SubProgram.aOp. As well as these, one memory
  62772. ** cell is required for each cursor used by the program. Set local
  62773. ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
  62774. */
  62775. u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
  62776. u.by.nByte = ROUND8(sizeof(VdbeFrame))
  62777. + u.by.nMem * sizeof(Mem)
  62778. + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
  62779. u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
  62780. if( !u.by.pFrame ){
  62781. goto no_mem;
  62782. }
  62783. sqlite3VdbeMemRelease(u.by.pRt);
  62784. u.by.pRt->flags = MEM_Frame;
  62785. u.by.pRt->u.pFrame = u.by.pFrame;
  62786. u.by.pFrame->v = p;
  62787. u.by.pFrame->nChildMem = u.by.nMem;
  62788. u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
  62789. u.by.pFrame->pc = pc;
  62790. u.by.pFrame->aMem = p->aMem;
  62791. u.by.pFrame->nMem = p->nMem;
  62792. u.by.pFrame->apCsr = p->apCsr;
  62793. u.by.pFrame->nCursor = p->nCursor;
  62794. u.by.pFrame->aOp = p->aOp;
  62795. u.by.pFrame->nOp = p->nOp;
  62796. u.by.pFrame->token = u.by.pProgram->token;
  62797. u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
  62798. for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
  62799. u.by.pMem->flags = MEM_Null;
  62800. u.by.pMem->db = db;
  62801. }
  62802. }else{
  62803. u.by.pFrame = u.by.pRt->u.pFrame;
  62804. assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
  62805. assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
  62806. assert( pc==u.by.pFrame->pc );
  62807. }
  62808. p->nFrame++;
  62809. u.by.pFrame->pParent = p->pFrame;
  62810. u.by.pFrame->lastRowid = db->lastRowid;
  62811. u.by.pFrame->nChange = p->nChange;
  62812. p->nChange = 0;
  62813. p->pFrame = u.by.pFrame;
  62814. p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
  62815. p->nMem = u.by.pFrame->nChildMem;
  62816. p->nCursor = (u16)u.by.pFrame->nChildCsr;
  62817. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  62818. p->aOp = aOp = u.by.pProgram->aOp;
  62819. p->nOp = u.by.pProgram->nOp;
  62820. pc = -1;
  62821. break;
  62822. }
  62823. /* Opcode: Param P1 P2 * * *
  62824. **
  62825. ** This opcode is only ever present in sub-programs called via the
  62826. ** OP_Program instruction. Copy a value currently stored in a memory
  62827. ** cell of the calling (parent) frame to cell P2 in the current frames
  62828. ** address space. This is used by trigger programs to access the new.*
  62829. ** and old.* values.
  62830. **
  62831. ** The address of the cell in the parent frame is determined by adding
  62832. ** the value of the P1 argument to the value of the P1 argument to the
  62833. ** calling OP_Program instruction.
  62834. */
  62835. case OP_Param: { /* out2-prerelease */
  62836. #if 0 /* local variables moved into u.bz */
  62837. VdbeFrame *pFrame;
  62838. Mem *pIn;
  62839. #endif /* local variables moved into u.bz */
  62840. u.bz.pFrame = p->pFrame;
  62841. u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
  62842. sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
  62843. break;
  62844. }
  62845. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  62846. #ifndef SQLITE_OMIT_FOREIGN_KEY
  62847. /* Opcode: FkCounter P1 P2 * * *
  62848. **
  62849. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  62850. ** If P1 is non-zero, the database constraint counter is incremented
  62851. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  62852. ** statement counter is incremented (immediate foreign key constraints).
  62853. */
  62854. case OP_FkCounter: {
  62855. if( pOp->p1 ){
  62856. db->nDeferredCons += pOp->p2;
  62857. }else{
  62858. p->nFkConstraint += pOp->p2;
  62859. }
  62860. break;
  62861. }
  62862. /* Opcode: FkIfZero P1 P2 * * *
  62863. **
  62864. ** This opcode tests if a foreign key constraint-counter is currently zero.
  62865. ** If so, jump to instruction P2. Otherwise, fall through to the next
  62866. ** instruction.
  62867. **
  62868. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  62869. ** is zero (the one that counts deferred constraint violations). If P1 is
  62870. ** zero, the jump is taken if the statement constraint-counter is zero
  62871. ** (immediate foreign key constraint violations).
  62872. */
  62873. case OP_FkIfZero: { /* jump */
  62874. if( pOp->p1 ){
  62875. if( db->nDeferredCons==0 ) pc = pOp->p2-1;
  62876. }else{
  62877. if( p->nFkConstraint==0 ) pc = pOp->p2-1;
  62878. }
  62879. break;
  62880. }
  62881. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  62882. #ifndef SQLITE_OMIT_AUTOINCREMENT
  62883. /* Opcode: MemMax P1 P2 * * *
  62884. **
  62885. ** P1 is a register in the root frame of this VM (the root frame is
  62886. ** different from the current frame if this instruction is being executed
  62887. ** within a sub-program). Set the value of register P1 to the maximum of
  62888. ** its current value and the value in register P2.
  62889. **
  62890. ** This instruction throws an error if the memory cell is not initially
  62891. ** an integer.
  62892. */
  62893. case OP_MemMax: { /* in2 */
  62894. #if 0 /* local variables moved into u.ca */
  62895. Mem *pIn1;
  62896. VdbeFrame *pFrame;
  62897. #endif /* local variables moved into u.ca */
  62898. if( p->pFrame ){
  62899. for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
  62900. u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
  62901. }else{
  62902. u.ca.pIn1 = &aMem[pOp->p1];
  62903. }
  62904. assert( memIsValid(u.ca.pIn1) );
  62905. sqlite3VdbeMemIntegerify(u.ca.pIn1);
  62906. pIn2 = &aMem[pOp->p2];
  62907. sqlite3VdbeMemIntegerify(pIn2);
  62908. if( u.ca.pIn1->u.i<pIn2->u.i){
  62909. u.ca.pIn1->u.i = pIn2->u.i;
  62910. }
  62911. break;
  62912. }
  62913. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  62914. /* Opcode: IfPos P1 P2 * * *
  62915. **
  62916. ** If the value of register P1 is 1 or greater, jump to P2.
  62917. **
  62918. ** It is illegal to use this instruction on a register that does
  62919. ** not contain an integer. An assertion fault will result if you try.
  62920. */
  62921. case OP_IfPos: { /* jump, in1 */
  62922. pIn1 = &aMem[pOp->p1];
  62923. assert( pIn1->flags&MEM_Int );
  62924. if( pIn1->u.i>0 ){
  62925. pc = pOp->p2 - 1;
  62926. }
  62927. break;
  62928. }
  62929. /* Opcode: IfNeg P1 P2 * * *
  62930. **
  62931. ** If the value of register P1 is less than zero, jump to P2.
  62932. **
  62933. ** It is illegal to use this instruction on a register that does
  62934. ** not contain an integer. An assertion fault will result if you try.
  62935. */
  62936. case OP_IfNeg: { /* jump, in1 */
  62937. pIn1 = &aMem[pOp->p1];
  62938. assert( pIn1->flags&MEM_Int );
  62939. if( pIn1->u.i<0 ){
  62940. pc = pOp->p2 - 1;
  62941. }
  62942. break;
  62943. }
  62944. /* Opcode: IfZero P1 P2 P3 * *
  62945. **
  62946. ** The register P1 must contain an integer. Add literal P3 to the
  62947. ** value in register P1. If the result is exactly 0, jump to P2.
  62948. **
  62949. ** It is illegal to use this instruction on a register that does
  62950. ** not contain an integer. An assertion fault will result if you try.
  62951. */
  62952. case OP_IfZero: { /* jump, in1 */
  62953. pIn1 = &aMem[pOp->p1];
  62954. assert( pIn1->flags&MEM_Int );
  62955. pIn1->u.i += pOp->p3;
  62956. if( pIn1->u.i==0 ){
  62957. pc = pOp->p2 - 1;
  62958. }
  62959. break;
  62960. }
  62961. /* Opcode: AggStep * P2 P3 P4 P5
  62962. **
  62963. ** Execute the step function for an aggregate. The
  62964. ** function has P5 arguments. P4 is a pointer to the FuncDef
  62965. ** structure that specifies the function. Use register
  62966. ** P3 as the accumulator.
  62967. **
  62968. ** The P5 arguments are taken from register P2 and its
  62969. ** successors.
  62970. */
  62971. case OP_AggStep: {
  62972. #if 0 /* local variables moved into u.cb */
  62973. int n;
  62974. int i;
  62975. Mem *pMem;
  62976. Mem *pRec;
  62977. sqlite3_context ctx;
  62978. sqlite3_value **apVal;
  62979. #endif /* local variables moved into u.cb */
  62980. u.cb.n = pOp->p5;
  62981. assert( u.cb.n>=0 );
  62982. u.cb.pRec = &aMem[pOp->p2];
  62983. u.cb.apVal = p->apArg;
  62984. assert( u.cb.apVal || u.cb.n==0 );
  62985. for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
  62986. assert( memIsValid(u.cb.pRec) );
  62987. u.cb.apVal[u.cb.i] = u.cb.pRec;
  62988. memAboutToChange(p, u.cb.pRec);
  62989. sqlite3VdbeMemStoreType(u.cb.pRec);
  62990. }
  62991. u.cb.ctx.pFunc = pOp->p4.pFunc;
  62992. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  62993. u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
  62994. u.cb.pMem->n++;
  62995. u.cb.ctx.s.flags = MEM_Null;
  62996. u.cb.ctx.s.z = 0;
  62997. u.cb.ctx.s.zMalloc = 0;
  62998. u.cb.ctx.s.xDel = 0;
  62999. u.cb.ctx.s.db = db;
  63000. u.cb.ctx.isError = 0;
  63001. u.cb.ctx.pColl = 0;
  63002. if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  63003. assert( pOp>p->aOp );
  63004. assert( pOp[-1].p4type==P4_COLLSEQ );
  63005. assert( pOp[-1].opcode==OP_CollSeq );
  63006. u.cb.ctx.pColl = pOp[-1].p4.pColl;
  63007. }
  63008. (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
  63009. if( u.cb.ctx.isError ){
  63010. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
  63011. rc = u.cb.ctx.isError;
  63012. }
  63013. sqlite3VdbeMemRelease(&u.cb.ctx.s);
  63014. break;
  63015. }
  63016. /* Opcode: AggFinal P1 P2 * P4 *
  63017. **
  63018. ** Execute the finalizer function for an aggregate. P1 is
  63019. ** the memory location that is the accumulator for the aggregate.
  63020. **
  63021. ** P2 is the number of arguments that the step function takes and
  63022. ** P4 is a pointer to the FuncDef for this function. The P2
  63023. ** argument is not used by this opcode. It is only there to disambiguate
  63024. ** functions that can take varying numbers of arguments. The
  63025. ** P4 argument is only needed for the degenerate case where
  63026. ** the step function was not previously called.
  63027. */
  63028. case OP_AggFinal: {
  63029. #if 0 /* local variables moved into u.cc */
  63030. Mem *pMem;
  63031. #endif /* local variables moved into u.cc */
  63032. assert( pOp->p1>0 && pOp->p1<=p->nMem );
  63033. u.cc.pMem = &aMem[pOp->p1];
  63034. assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  63035. rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
  63036. if( rc ){
  63037. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
  63038. }
  63039. sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
  63040. UPDATE_MAX_BLOBSIZE(u.cc.pMem);
  63041. if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
  63042. goto too_big;
  63043. }
  63044. break;
  63045. }
  63046. #ifndef SQLITE_OMIT_WAL
  63047. /* Opcode: Checkpoint P1 P2 P3 * *
  63048. **
  63049. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  63050. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  63051. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  63052. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  63053. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  63054. ** in the WAL that have been checkpointed after the checkpoint
  63055. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  63056. ** mem[P3+2] are initialized to -1.
  63057. */
  63058. case OP_Checkpoint: {
  63059. #if 0 /* local variables moved into u.cd */
  63060. int i; /* Loop counter */
  63061. int aRes[3]; /* Results */
  63062. Mem *pMem; /* Write results here */
  63063. #endif /* local variables moved into u.cd */
  63064. u.cd.aRes[0] = 0;
  63065. u.cd.aRes[1] = u.cd.aRes[2] = -1;
  63066. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  63067. || pOp->p2==SQLITE_CHECKPOINT_FULL
  63068. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  63069. );
  63070. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cd.aRes[1], &u.cd.aRes[2]);
  63071. if( rc==SQLITE_BUSY ){
  63072. rc = SQLITE_OK;
  63073. u.cd.aRes[0] = 1;
  63074. }
  63075. for(u.cd.i=0, u.cd.pMem = &aMem[pOp->p3]; u.cd.i<3; u.cd.i++, u.cd.pMem++){
  63076. sqlite3VdbeMemSetInt64(u.cd.pMem, (i64)u.cd.aRes[u.cd.i]);
  63077. }
  63078. break;
  63079. };
  63080. #endif
  63081. #ifndef SQLITE_OMIT_PRAGMA
  63082. /* Opcode: JournalMode P1 P2 P3 * P5
  63083. **
  63084. ** Change the journal mode of database P1 to P3. P3 must be one of the
  63085. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  63086. ** modes (delete, truncate, persist, off and memory), this is a simple
  63087. ** operation. No IO is required.
  63088. **
  63089. ** If changing into or out of WAL mode the procedure is more complicated.
  63090. **
  63091. ** Write a string containing the final journal-mode to register P2.
  63092. */
  63093. case OP_JournalMode: { /* out2-prerelease */
  63094. #if 0 /* local variables moved into u.ce */
  63095. Btree *pBt; /* Btree to change journal mode of */
  63096. Pager *pPager; /* Pager associated with pBt */
  63097. int eNew; /* New journal mode */
  63098. int eOld; /* The old journal mode */
  63099. const char *zFilename; /* Name of database file for pPager */
  63100. #endif /* local variables moved into u.ce */
  63101. u.ce.eNew = pOp->p3;
  63102. assert( u.ce.eNew==PAGER_JOURNALMODE_DELETE
  63103. || u.ce.eNew==PAGER_JOURNALMODE_TRUNCATE
  63104. || u.ce.eNew==PAGER_JOURNALMODE_PERSIST
  63105. || u.ce.eNew==PAGER_JOURNALMODE_OFF
  63106. || u.ce.eNew==PAGER_JOURNALMODE_MEMORY
  63107. || u.ce.eNew==PAGER_JOURNALMODE_WAL
  63108. || u.ce.eNew==PAGER_JOURNALMODE_QUERY
  63109. );
  63110. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  63111. u.ce.pBt = db->aDb[pOp->p1].pBt;
  63112. u.ce.pPager = sqlite3BtreePager(u.ce.pBt);
  63113. u.ce.eOld = sqlite3PagerGetJournalMode(u.ce.pPager);
  63114. if( u.ce.eNew==PAGER_JOURNALMODE_QUERY ) u.ce.eNew = u.ce.eOld;
  63115. if( !sqlite3PagerOkToChangeJournalMode(u.ce.pPager) ) u.ce.eNew = u.ce.eOld;
  63116. #ifndef SQLITE_OMIT_WAL
  63117. u.ce.zFilename = sqlite3PagerFilename(u.ce.pPager);
  63118. /* Do not allow a transition to journal_mode=WAL for a database
  63119. ** in temporary storage or if the VFS does not support shared memory
  63120. */
  63121. if( u.ce.eNew==PAGER_JOURNALMODE_WAL
  63122. && (u.ce.zFilename[0]==0 /* Temp file */
  63123. || !sqlite3PagerWalSupported(u.ce.pPager)) /* No shared-memory support */
  63124. ){
  63125. u.ce.eNew = u.ce.eOld;
  63126. }
  63127. if( (u.ce.eNew!=u.ce.eOld)
  63128. && (u.ce.eOld==PAGER_JOURNALMODE_WAL || u.ce.eNew==PAGER_JOURNALMODE_WAL)
  63129. ){
  63130. if( !db->autoCommit || db->activeVdbeCnt>1 ){
  63131. rc = SQLITE_ERROR;
  63132. sqlite3SetString(&p->zErrMsg, db,
  63133. "cannot change %s wal mode from within a transaction",
  63134. (u.ce.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  63135. );
  63136. break;
  63137. }else{
  63138. if( u.ce.eOld==PAGER_JOURNALMODE_WAL ){
  63139. /* If leaving WAL mode, close the log file. If successful, the call
  63140. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  63141. ** file. An EXCLUSIVE lock may still be held on the database file
  63142. ** after a successful return.
  63143. */
  63144. rc = sqlite3PagerCloseWal(u.ce.pPager);
  63145. if( rc==SQLITE_OK ){
  63146. sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
  63147. }
  63148. }else if( u.ce.eOld==PAGER_JOURNALMODE_MEMORY ){
  63149. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  63150. ** as an intermediate */
  63151. sqlite3PagerSetJournalMode(u.ce.pPager, PAGER_JOURNALMODE_OFF);
  63152. }
  63153. /* Open a transaction on the database file. Regardless of the journal
  63154. ** mode, this transaction always uses a rollback journal.
  63155. */
  63156. assert( sqlite3BtreeIsInTrans(u.ce.pBt)==0 );
  63157. if( rc==SQLITE_OK ){
  63158. rc = sqlite3BtreeSetVersion(u.ce.pBt, (u.ce.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  63159. }
  63160. }
  63161. }
  63162. #endif /* ifndef SQLITE_OMIT_WAL */
  63163. if( rc ){
  63164. u.ce.eNew = u.ce.eOld;
  63165. }
  63166. u.ce.eNew = sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
  63167. pOut = &aMem[pOp->p2];
  63168. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  63169. pOut->z = (char *)sqlite3JournalModename(u.ce.eNew);
  63170. pOut->n = sqlite3Strlen30(pOut->z);
  63171. pOut->enc = SQLITE_UTF8;
  63172. sqlite3VdbeChangeEncoding(pOut, encoding);
  63173. break;
  63174. };
  63175. #endif /* SQLITE_OMIT_PRAGMA */
  63176. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  63177. /* Opcode: Vacuum * * * * *
  63178. **
  63179. ** Vacuum the entire database. This opcode will cause other virtual
  63180. ** machines to be created and run. It may not be called from within
  63181. ** a transaction.
  63182. */
  63183. case OP_Vacuum: {
  63184. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  63185. break;
  63186. }
  63187. #endif
  63188. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  63189. /* Opcode: IncrVacuum P1 P2 * * *
  63190. **
  63191. ** Perform a single step of the incremental vacuum procedure on
  63192. ** the P1 database. If the vacuum has finished, jump to instruction
  63193. ** P2. Otherwise, fall through to the next instruction.
  63194. */
  63195. case OP_IncrVacuum: { /* jump */
  63196. #if 0 /* local variables moved into u.cf */
  63197. Btree *pBt;
  63198. #endif /* local variables moved into u.cf */
  63199. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  63200. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  63201. u.cf.pBt = db->aDb[pOp->p1].pBt;
  63202. rc = sqlite3BtreeIncrVacuum(u.cf.pBt);
  63203. if( rc==SQLITE_DONE ){
  63204. pc = pOp->p2 - 1;
  63205. rc = SQLITE_OK;
  63206. }
  63207. break;
  63208. }
  63209. #endif
  63210. /* Opcode: Expire P1 * * * *
  63211. **
  63212. ** Cause precompiled statements to become expired. An expired statement
  63213. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  63214. ** (via sqlite3_step()).
  63215. **
  63216. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  63217. ** then only the currently executing statement is affected.
  63218. */
  63219. case OP_Expire: {
  63220. if( !pOp->p1 ){
  63221. sqlite3ExpirePreparedStatements(db);
  63222. }else{
  63223. p->expired = 1;
  63224. }
  63225. break;
  63226. }
  63227. #ifndef SQLITE_OMIT_SHARED_CACHE
  63228. /* Opcode: TableLock P1 P2 P3 P4 *
  63229. **
  63230. ** Obtain a lock on a particular table. This instruction is only used when
  63231. ** the shared-cache feature is enabled.
  63232. **
  63233. ** P1 is the index of the database in sqlite3.aDb[] of the database
  63234. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  63235. ** a write lock if P3==1.
  63236. **
  63237. ** P2 contains the root-page of the table to lock.
  63238. **
  63239. ** P4 contains a pointer to the name of the table being locked. This is only
  63240. ** used to generate an error message if the lock cannot be obtained.
  63241. */
  63242. case OP_TableLock: {
  63243. u8 isWriteLock = (u8)pOp->p3;
  63244. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  63245. int p1 = pOp->p1;
  63246. assert( p1>=0 && p1<db->nDb );
  63247. assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
  63248. assert( isWriteLock==0 || isWriteLock==1 );
  63249. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  63250. if( (rc&0xFF)==SQLITE_LOCKED ){
  63251. const char *z = pOp->p4.z;
  63252. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  63253. }
  63254. }
  63255. break;
  63256. }
  63257. #endif /* SQLITE_OMIT_SHARED_CACHE */
  63258. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63259. /* Opcode: VBegin * * * P4 *
  63260. **
  63261. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  63262. ** xBegin method for that table.
  63263. **
  63264. ** Also, whether or not P4 is set, check that this is not being called from
  63265. ** within a callback to a virtual table xSync() method. If it is, the error
  63266. ** code will be set to SQLITE_LOCKED.
  63267. */
  63268. case OP_VBegin: {
  63269. #if 0 /* local variables moved into u.cg */
  63270. VTable *pVTab;
  63271. #endif /* local variables moved into u.cg */
  63272. u.cg.pVTab = pOp->p4.pVtab;
  63273. rc = sqlite3VtabBegin(db, u.cg.pVTab);
  63274. if( u.cg.pVTab ) importVtabErrMsg(p, u.cg.pVTab->pVtab);
  63275. break;
  63276. }
  63277. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63278. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63279. /* Opcode: VCreate P1 * * P4 *
  63280. **
  63281. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  63282. ** for that table.
  63283. */
  63284. case OP_VCreate: {
  63285. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  63286. break;
  63287. }
  63288. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63289. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63290. /* Opcode: VDestroy P1 * * P4 *
  63291. **
  63292. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  63293. ** of that table.
  63294. */
  63295. case OP_VDestroy: {
  63296. p->inVtabMethod = 2;
  63297. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  63298. p->inVtabMethod = 0;
  63299. break;
  63300. }
  63301. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63302. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63303. /* Opcode: VOpen P1 * * P4 *
  63304. **
  63305. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  63306. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  63307. ** table and stores that cursor in P1.
  63308. */
  63309. case OP_VOpen: {
  63310. #if 0 /* local variables moved into u.ch */
  63311. VdbeCursor *pCur;
  63312. sqlite3_vtab_cursor *pVtabCursor;
  63313. sqlite3_vtab *pVtab;
  63314. sqlite3_module *pModule;
  63315. #endif /* local variables moved into u.ch */
  63316. u.ch.pCur = 0;
  63317. u.ch.pVtabCursor = 0;
  63318. u.ch.pVtab = pOp->p4.pVtab->pVtab;
  63319. u.ch.pModule = (sqlite3_module *)u.ch.pVtab->pModule;
  63320. assert(u.ch.pVtab && u.ch.pModule);
  63321. rc = u.ch.pModule->xOpen(u.ch.pVtab, &u.ch.pVtabCursor);
  63322. importVtabErrMsg(p, u.ch.pVtab);
  63323. if( SQLITE_OK==rc ){
  63324. /* Initialize sqlite3_vtab_cursor base class */
  63325. u.ch.pVtabCursor->pVtab = u.ch.pVtab;
  63326. /* Initialise vdbe cursor object */
  63327. u.ch.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  63328. if( u.ch.pCur ){
  63329. u.ch.pCur->pVtabCursor = u.ch.pVtabCursor;
  63330. u.ch.pCur->pModule = u.ch.pVtabCursor->pVtab->pModule;
  63331. }else{
  63332. db->mallocFailed = 1;
  63333. u.ch.pModule->xClose(u.ch.pVtabCursor);
  63334. }
  63335. }
  63336. break;
  63337. }
  63338. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63339. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63340. /* Opcode: VFilter P1 P2 P3 P4 *
  63341. **
  63342. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  63343. ** the filtered result set is empty.
  63344. **
  63345. ** P4 is either NULL or a string that was generated by the xBestIndex
  63346. ** method of the module. The interpretation of the P4 string is left
  63347. ** to the module implementation.
  63348. **
  63349. ** This opcode invokes the xFilter method on the virtual table specified
  63350. ** by P1. The integer query plan parameter to xFilter is stored in register
  63351. ** P3. Register P3+1 stores the argc parameter to be passed to the
  63352. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  63353. ** additional parameters which are passed to
  63354. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  63355. **
  63356. ** A jump is made to P2 if the result set after filtering would be empty.
  63357. */
  63358. case OP_VFilter: { /* jump */
  63359. #if 0 /* local variables moved into u.ci */
  63360. int nArg;
  63361. int iQuery;
  63362. const sqlite3_module *pModule;
  63363. Mem *pQuery;
  63364. Mem *pArgc;
  63365. sqlite3_vtab_cursor *pVtabCursor;
  63366. sqlite3_vtab *pVtab;
  63367. VdbeCursor *pCur;
  63368. int res;
  63369. int i;
  63370. Mem **apArg;
  63371. #endif /* local variables moved into u.ci */
  63372. u.ci.pQuery = &aMem[pOp->p3];
  63373. u.ci.pArgc = &u.ci.pQuery[1];
  63374. u.ci.pCur = p->apCsr[pOp->p1];
  63375. assert( memIsValid(u.ci.pQuery) );
  63376. REGISTER_TRACE(pOp->p3, u.ci.pQuery);
  63377. assert( u.ci.pCur->pVtabCursor );
  63378. u.ci.pVtabCursor = u.ci.pCur->pVtabCursor;
  63379. u.ci.pVtab = u.ci.pVtabCursor->pVtab;
  63380. u.ci.pModule = u.ci.pVtab->pModule;
  63381. /* Grab the index number and argc parameters */
  63382. assert( (u.ci.pQuery->flags&MEM_Int)!=0 && u.ci.pArgc->flags==MEM_Int );
  63383. u.ci.nArg = (int)u.ci.pArgc->u.i;
  63384. u.ci.iQuery = (int)u.ci.pQuery->u.i;
  63385. /* Invoke the xFilter method */
  63386. {
  63387. u.ci.res = 0;
  63388. u.ci.apArg = p->apArg;
  63389. for(u.ci.i = 0; u.ci.i<u.ci.nArg; u.ci.i++){
  63390. u.ci.apArg[u.ci.i] = &u.ci.pArgc[u.ci.i+1];
  63391. sqlite3VdbeMemStoreType(u.ci.apArg[u.ci.i]);
  63392. }
  63393. p->inVtabMethod = 1;
  63394. rc = u.ci.pModule->xFilter(u.ci.pVtabCursor, u.ci.iQuery, pOp->p4.z, u.ci.nArg, u.ci.apArg);
  63395. p->inVtabMethod = 0;
  63396. importVtabErrMsg(p, u.ci.pVtab);
  63397. if( rc==SQLITE_OK ){
  63398. u.ci.res = u.ci.pModule->xEof(u.ci.pVtabCursor);
  63399. }
  63400. if( u.ci.res ){
  63401. pc = pOp->p2 - 1;
  63402. }
  63403. }
  63404. u.ci.pCur->nullRow = 0;
  63405. break;
  63406. }
  63407. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63408. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63409. /* Opcode: VColumn P1 P2 P3 * *
  63410. **
  63411. ** Store the value of the P2-th column of
  63412. ** the row of the virtual-table that the
  63413. ** P1 cursor is pointing to into register P3.
  63414. */
  63415. case OP_VColumn: {
  63416. #if 0 /* local variables moved into u.cj */
  63417. sqlite3_vtab *pVtab;
  63418. const sqlite3_module *pModule;
  63419. Mem *pDest;
  63420. sqlite3_context sContext;
  63421. #endif /* local variables moved into u.cj */
  63422. VdbeCursor *pCur = p->apCsr[pOp->p1];
  63423. assert( pCur->pVtabCursor );
  63424. assert( pOp->p3>0 && pOp->p3<=p->nMem );
  63425. u.cj.pDest = &aMem[pOp->p3];
  63426. memAboutToChange(p, u.cj.pDest);
  63427. if( pCur->nullRow ){
  63428. sqlite3VdbeMemSetNull(u.cj.pDest);
  63429. break;
  63430. }
  63431. u.cj.pVtab = pCur->pVtabCursor->pVtab;
  63432. u.cj.pModule = u.cj.pVtab->pModule;
  63433. assert( u.cj.pModule->xColumn );
  63434. memset(&u.cj.sContext, 0, sizeof(u.cj.sContext));
  63435. /* The output cell may already have a buffer allocated. Move
  63436. ** the current contents to u.cj.sContext.s so in case the user-function
  63437. ** can use the already allocated buffer instead of allocating a
  63438. ** new one.
  63439. */
  63440. sqlite3VdbeMemMove(&u.cj.sContext.s, u.cj.pDest);
  63441. MemSetTypeFlag(&u.cj.sContext.s, MEM_Null);
  63442. rc = u.cj.pModule->xColumn(pCur->pVtabCursor, &u.cj.sContext, pOp->p2);
  63443. importVtabErrMsg(p, u.cj.pVtab);
  63444. if( u.cj.sContext.isError ){
  63445. rc = u.cj.sContext.isError;
  63446. }
  63447. /* Copy the result of the function to the P3 register. We
  63448. ** do this regardless of whether or not an error occurred to ensure any
  63449. ** dynamic allocation in u.cj.sContext.s (a Mem struct) is released.
  63450. */
  63451. sqlite3VdbeChangeEncoding(&u.cj.sContext.s, encoding);
  63452. sqlite3VdbeMemMove(u.cj.pDest, &u.cj.sContext.s);
  63453. REGISTER_TRACE(pOp->p3, u.cj.pDest);
  63454. UPDATE_MAX_BLOBSIZE(u.cj.pDest);
  63455. if( sqlite3VdbeMemTooBig(u.cj.pDest) ){
  63456. goto too_big;
  63457. }
  63458. break;
  63459. }
  63460. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63461. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63462. /* Opcode: VNext P1 P2 * * *
  63463. **
  63464. ** Advance virtual table P1 to the next row in its result set and
  63465. ** jump to instruction P2. Or, if the virtual table has reached
  63466. ** the end of its result set, then fall through to the next instruction.
  63467. */
  63468. case OP_VNext: { /* jump */
  63469. #if 0 /* local variables moved into u.ck */
  63470. sqlite3_vtab *pVtab;
  63471. const sqlite3_module *pModule;
  63472. int res;
  63473. VdbeCursor *pCur;
  63474. #endif /* local variables moved into u.ck */
  63475. u.ck.res = 0;
  63476. u.ck.pCur = p->apCsr[pOp->p1];
  63477. assert( u.ck.pCur->pVtabCursor );
  63478. if( u.ck.pCur->nullRow ){
  63479. break;
  63480. }
  63481. u.ck.pVtab = u.ck.pCur->pVtabCursor->pVtab;
  63482. u.ck.pModule = u.ck.pVtab->pModule;
  63483. assert( u.ck.pModule->xNext );
  63484. /* Invoke the xNext() method of the module. There is no way for the
  63485. ** underlying implementation to return an error if one occurs during
  63486. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  63487. ** data is available) and the error code returned when xColumn or
  63488. ** some other method is next invoked on the save virtual table cursor.
  63489. */
  63490. p->inVtabMethod = 1;
  63491. rc = u.ck.pModule->xNext(u.ck.pCur->pVtabCursor);
  63492. p->inVtabMethod = 0;
  63493. importVtabErrMsg(p, u.ck.pVtab);
  63494. if( rc==SQLITE_OK ){
  63495. u.ck.res = u.ck.pModule->xEof(u.ck.pCur->pVtabCursor);
  63496. }
  63497. if( !u.ck.res ){
  63498. /* If there is data, jump to P2 */
  63499. pc = pOp->p2 - 1;
  63500. }
  63501. break;
  63502. }
  63503. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63504. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63505. /* Opcode: VRename P1 * * P4 *
  63506. **
  63507. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  63508. ** This opcode invokes the corresponding xRename method. The value
  63509. ** in register P1 is passed as the zName argument to the xRename method.
  63510. */
  63511. case OP_VRename: {
  63512. #if 0 /* local variables moved into u.cl */
  63513. sqlite3_vtab *pVtab;
  63514. Mem *pName;
  63515. #endif /* local variables moved into u.cl */
  63516. u.cl.pVtab = pOp->p4.pVtab->pVtab;
  63517. u.cl.pName = &aMem[pOp->p1];
  63518. assert( u.cl.pVtab->pModule->xRename );
  63519. assert( memIsValid(u.cl.pName) );
  63520. REGISTER_TRACE(pOp->p1, u.cl.pName);
  63521. assert( u.cl.pName->flags & MEM_Str );
  63522. rc = u.cl.pVtab->pModule->xRename(u.cl.pVtab, u.cl.pName->z);
  63523. importVtabErrMsg(p, u.cl.pVtab);
  63524. p->expired = 0;
  63525. break;
  63526. }
  63527. #endif
  63528. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63529. /* Opcode: VUpdate P1 P2 P3 P4 *
  63530. **
  63531. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  63532. ** This opcode invokes the corresponding xUpdate method. P2 values
  63533. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  63534. ** invocation. The value in register (P3+P2-1) corresponds to the
  63535. ** p2th element of the argv array passed to xUpdate.
  63536. **
  63537. ** The xUpdate method will do a DELETE or an INSERT or both.
  63538. ** The argv[0] element (which corresponds to memory cell P3)
  63539. ** is the rowid of a row to delete. If argv[0] is NULL then no
  63540. ** deletion occurs. The argv[1] element is the rowid of the new
  63541. ** row. This can be NULL to have the virtual table select the new
  63542. ** rowid for itself. The subsequent elements in the array are
  63543. ** the values of columns in the new row.
  63544. **
  63545. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  63546. ** a row to delete.
  63547. **
  63548. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  63549. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  63550. ** is set to the value of the rowid for the row just inserted.
  63551. */
  63552. case OP_VUpdate: {
  63553. #if 0 /* local variables moved into u.cm */
  63554. sqlite3_vtab *pVtab;
  63555. sqlite3_module *pModule;
  63556. int nArg;
  63557. int i;
  63558. sqlite_int64 rowid;
  63559. Mem **apArg;
  63560. Mem *pX;
  63561. #endif /* local variables moved into u.cm */
  63562. u.cm.pVtab = pOp->p4.pVtab->pVtab;
  63563. u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
  63564. u.cm.nArg = pOp->p2;
  63565. assert( pOp->p4type==P4_VTAB );
  63566. if( ALWAYS(u.cm.pModule->xUpdate) ){
  63567. u.cm.apArg = p->apArg;
  63568. u.cm.pX = &aMem[pOp->p3];
  63569. for(u.cm.i=0; u.cm.i<u.cm.nArg; u.cm.i++){
  63570. assert( memIsValid(u.cm.pX) );
  63571. memAboutToChange(p, u.cm.pX);
  63572. sqlite3VdbeMemStoreType(u.cm.pX);
  63573. u.cm.apArg[u.cm.i] = u.cm.pX;
  63574. u.cm.pX++;
  63575. }
  63576. rc = u.cm.pModule->xUpdate(u.cm.pVtab, u.cm.nArg, u.cm.apArg, &u.cm.rowid);
  63577. importVtabErrMsg(p, u.cm.pVtab);
  63578. if( rc==SQLITE_OK && pOp->p1 ){
  63579. assert( u.cm.nArg>1 && u.cm.apArg[0] && (u.cm.apArg[0]->flags&MEM_Null) );
  63580. db->lastRowid = u.cm.rowid;
  63581. }
  63582. p->nChange++;
  63583. }
  63584. break;
  63585. }
  63586. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  63587. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  63588. /* Opcode: Pagecount P1 P2 * * *
  63589. **
  63590. ** Write the current number of pages in database P1 to memory cell P2.
  63591. */
  63592. case OP_Pagecount: { /* out2-prerelease */
  63593. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  63594. break;
  63595. }
  63596. #endif
  63597. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  63598. /* Opcode: MaxPgcnt P1 P2 P3 * *
  63599. **
  63600. ** Try to set the maximum page count for database P1 to the value in P3.
  63601. ** Do not let the maximum page count fall below the current page count and
  63602. ** do not change the maximum page count value if P3==0.
  63603. **
  63604. ** Store the maximum page count after the change in register P2.
  63605. */
  63606. case OP_MaxPgcnt: { /* out2-prerelease */
  63607. unsigned int newMax;
  63608. Btree *pBt;
  63609. pBt = db->aDb[pOp->p1].pBt;
  63610. newMax = 0;
  63611. if( pOp->p3 ){
  63612. newMax = sqlite3BtreeLastPage(pBt);
  63613. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  63614. }
  63615. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  63616. break;
  63617. }
  63618. #endif
  63619. #ifndef SQLITE_OMIT_TRACE
  63620. /* Opcode: Trace * * * P4 *
  63621. **
  63622. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  63623. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  63624. */
  63625. case OP_Trace: {
  63626. #if 0 /* local variables moved into u.cn */
  63627. char *zTrace;
  63628. #endif /* local variables moved into u.cn */
  63629. u.cn.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  63630. if( u.cn.zTrace ){
  63631. if( db->xTrace ){
  63632. char *z = sqlite3VdbeExpandSql(p, u.cn.zTrace);
  63633. db->xTrace(db->pTraceArg, z);
  63634. sqlite3DbFree(db, z);
  63635. }
  63636. #ifdef SQLITE_DEBUG
  63637. if( (db->flags & SQLITE_SqlTrace)!=0 ){
  63638. sqlite3DebugPrintf("SQL-trace: %s\n", u.cn.zTrace);
  63639. }
  63640. #endif /* SQLITE_DEBUG */
  63641. }
  63642. break;
  63643. }
  63644. #endif
  63645. /* Opcode: Noop * * * * *
  63646. **
  63647. ** Do nothing. This instruction is often useful as a jump
  63648. ** destination.
  63649. */
  63650. /*
  63651. ** The magic Explain opcode are only inserted when explain==2 (which
  63652. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  63653. ** This opcode records information from the optimizer. It is the
  63654. ** the same as a no-op. This opcodesnever appears in a real VM program.
  63655. */
  63656. default: { /* This is really OP_Noop and OP_Explain */
  63657. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  63658. break;
  63659. }
  63660. /*****************************************************************************
  63661. ** The cases of the switch statement above this line should all be indented
  63662. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  63663. ** readability. From this point on down, the normal indentation rules are
  63664. ** restored.
  63665. *****************************************************************************/
  63666. }
  63667. #ifdef VDBE_PROFILE
  63668. {
  63669. u64 elapsed = sqlite3Hwtime() - start;
  63670. pOp->cycles += elapsed;
  63671. pOp->cnt++;
  63672. #if 0
  63673. fprintf(stdout, "%10llu ", elapsed);
  63674. sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  63675. #endif
  63676. }
  63677. #endif
  63678. /* The following code adds nothing to the actual functionality
  63679. ** of the program. It is only here for testing and debugging.
  63680. ** On the other hand, it does burn CPU cycles every time through
  63681. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  63682. */
  63683. #ifndef NDEBUG
  63684. assert( pc>=-1 && pc<p->nOp );
  63685. #ifdef SQLITE_DEBUG
  63686. if( p->trace ){
  63687. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  63688. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  63689. registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
  63690. }
  63691. if( pOp->opflags & OPFLG_OUT3 ){
  63692. registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
  63693. }
  63694. }
  63695. #endif /* SQLITE_DEBUG */
  63696. #endif /* NDEBUG */
  63697. } /* The end of the for(;;) loop the loops through opcodes */
  63698. /* If we reach this point, it means that execution is finished with
  63699. ** an error of some kind.
  63700. */
  63701. vdbe_error_halt:
  63702. assert( rc );
  63703. p->rc = rc;
  63704. testcase( sqlite3GlobalConfig.xLog!=0 );
  63705. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  63706. pc, p->zSql, p->zErrMsg);
  63707. sqlite3VdbeHalt(p);
  63708. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  63709. rc = SQLITE_ERROR;
  63710. if( resetSchemaOnFault>0 ){
  63711. sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
  63712. }
  63713. /* This is the only way out of this procedure. We have to
  63714. ** release the mutexes on btrees that were acquired at the
  63715. ** top. */
  63716. vdbe_return:
  63717. sqlite3VdbeLeave(p);
  63718. return rc;
  63719. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  63720. ** is encountered.
  63721. */
  63722. too_big:
  63723. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  63724. rc = SQLITE_TOOBIG;
  63725. goto vdbe_error_halt;
  63726. /* Jump to here if a malloc() fails.
  63727. */
  63728. no_mem:
  63729. db->mallocFailed = 1;
  63730. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  63731. rc = SQLITE_NOMEM;
  63732. goto vdbe_error_halt;
  63733. /* Jump to here for any other kind of fatal error. The "rc" variable
  63734. ** should hold the error number.
  63735. */
  63736. abort_due_to_error:
  63737. assert( p->zErrMsg==0 );
  63738. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  63739. if( rc!=SQLITE_IOERR_NOMEM ){
  63740. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  63741. }
  63742. goto vdbe_error_halt;
  63743. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  63744. ** flag.
  63745. */
  63746. abort_due_to_interrupt:
  63747. assert( db->u1.isInterrupted );
  63748. rc = SQLITE_INTERRUPT;
  63749. p->rc = rc;
  63750. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  63751. goto vdbe_error_halt;
  63752. }
  63753. /************** End of vdbe.c ************************************************/
  63754. /************** Begin file vdbeblob.c ****************************************/
  63755. /*
  63756. ** 2007 May 1
  63757. **
  63758. ** The author disclaims copyright to this source code. In place of
  63759. ** a legal notice, here is a blessing:
  63760. **
  63761. ** May you do good and not evil.
  63762. ** May you find forgiveness for yourself and forgive others.
  63763. ** May you share freely, never taking more than you give.
  63764. **
  63765. *************************************************************************
  63766. **
  63767. ** This file contains code used to implement incremental BLOB I/O.
  63768. */
  63769. #ifndef SQLITE_OMIT_INCRBLOB
  63770. /*
  63771. ** Valid sqlite3_blob* handles point to Incrblob structures.
  63772. */
  63773. typedef struct Incrblob Incrblob;
  63774. struct Incrblob {
  63775. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  63776. int nByte; /* Size of open blob, in bytes */
  63777. int iOffset; /* Byte offset of blob in cursor data */
  63778. int iCol; /* Table column this handle is open on */
  63779. BtCursor *pCsr; /* Cursor pointing at blob row */
  63780. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  63781. sqlite3 *db; /* The associated database */
  63782. };
  63783. /*
  63784. ** This function is used by both blob_open() and blob_reopen(). It seeks
  63785. ** the b-tree cursor associated with blob handle p to point to row iRow.
  63786. ** If successful, SQLITE_OK is returned and subsequent calls to
  63787. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  63788. **
  63789. ** If an error occurs, or if the specified row does not exist or does not
  63790. ** contain a value of type TEXT or BLOB in the column nominated when the
  63791. ** blob handle was opened, then an error code is returned and *pzErr may
  63792. ** be set to point to a buffer containing an error message. It is the
  63793. ** responsibility of the caller to free the error message buffer using
  63794. ** sqlite3DbFree().
  63795. **
  63796. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  63797. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  63798. ** immediately return SQLITE_ABORT.
  63799. */
  63800. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  63801. int rc; /* Error code */
  63802. char *zErr = 0; /* Error message */
  63803. Vdbe *v = (Vdbe *)p->pStmt;
  63804. /* Set the value of the SQL statements only variable to integer iRow.
  63805. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  63806. ** triggering asserts related to mutexes.
  63807. */
  63808. assert( v->aVar[0].flags&MEM_Int );
  63809. v->aVar[0].u.i = iRow;
  63810. rc = sqlite3_step(p->pStmt);
  63811. if( rc==SQLITE_ROW ){
  63812. u32 type = v->apCsr[0]->aType[p->iCol];
  63813. if( type<12 ){
  63814. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  63815. type==0?"null": type==7?"real": "integer"
  63816. );
  63817. rc = SQLITE_ERROR;
  63818. sqlite3_finalize(p->pStmt);
  63819. p->pStmt = 0;
  63820. }else{
  63821. p->iOffset = v->apCsr[0]->aOffset[p->iCol];
  63822. p->nByte = sqlite3VdbeSerialTypeLen(type);
  63823. p->pCsr = v->apCsr[0]->pCursor;
  63824. sqlite3BtreeEnterCursor(p->pCsr);
  63825. sqlite3BtreeCacheOverflow(p->pCsr);
  63826. sqlite3BtreeLeaveCursor(p->pCsr);
  63827. }
  63828. }
  63829. if( rc==SQLITE_ROW ){
  63830. rc = SQLITE_OK;
  63831. }else if( p->pStmt ){
  63832. rc = sqlite3_finalize(p->pStmt);
  63833. p->pStmt = 0;
  63834. if( rc==SQLITE_OK ){
  63835. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  63836. rc = SQLITE_ERROR;
  63837. }else{
  63838. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  63839. }
  63840. }
  63841. assert( rc!=SQLITE_OK || zErr==0 );
  63842. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  63843. *pzErr = zErr;
  63844. return rc;
  63845. }
  63846. /*
  63847. ** Open a blob handle.
  63848. */
  63849. SQLITE_API int sqlite3_blob_open(
  63850. sqlite3* db, /* The database connection */
  63851. const char *zDb, /* The attached database containing the blob */
  63852. const char *zTable, /* The table containing the blob */
  63853. const char *zColumn, /* The column containing the blob */
  63854. sqlite_int64 iRow, /* The row containing the glob */
  63855. int flags, /* True -> read/write access, false -> read-only */
  63856. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  63857. ){
  63858. int nAttempt = 0;
  63859. int iCol; /* Index of zColumn in row-record */
  63860. /* This VDBE program seeks a btree cursor to the identified
  63861. ** db/table/row entry. The reason for using a vdbe program instead
  63862. ** of writing code to use the b-tree layer directly is that the
  63863. ** vdbe program will take advantage of the various transaction,
  63864. ** locking and error handling infrastructure built into the vdbe.
  63865. **
  63866. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  63867. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  63868. ** uses it to implement the blob_read(), blob_write() and
  63869. ** blob_bytes() functions.
  63870. **
  63871. ** The sqlite3_blob_close() function finalizes the vdbe program,
  63872. ** which closes the b-tree cursor and (possibly) commits the
  63873. ** transaction.
  63874. */
  63875. static const VdbeOpList openBlob[] = {
  63876. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  63877. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  63878. {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
  63879. /* One of the following two instructions is replaced by an OP_Noop. */
  63880. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  63881. {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
  63882. {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
  63883. {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
  63884. {OP_Column, 0, 0, 1}, /* 7 */
  63885. {OP_ResultRow, 1, 0, 0}, /* 8 */
  63886. {OP_Goto, 0, 5, 0}, /* 9 */
  63887. {OP_Close, 0, 0, 0}, /* 10 */
  63888. {OP_Halt, 0, 0, 0}, /* 11 */
  63889. };
  63890. int rc = SQLITE_OK;
  63891. char *zErr = 0;
  63892. Table *pTab;
  63893. Parse *pParse = 0;
  63894. Incrblob *pBlob = 0;
  63895. flags = !!flags; /* flags = (flags ? 1 : 0); */
  63896. *ppBlob = 0;
  63897. sqlite3_mutex_enter(db->mutex);
  63898. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  63899. if( !pBlob ) goto blob_open_out;
  63900. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  63901. if( !pParse ) goto blob_open_out;
  63902. do {
  63903. memset(pParse, 0, sizeof(Parse));
  63904. pParse->db = db;
  63905. sqlite3DbFree(db, zErr);
  63906. zErr = 0;
  63907. sqlite3BtreeEnterAll(db);
  63908. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  63909. if( pTab && IsVirtual(pTab) ){
  63910. pTab = 0;
  63911. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  63912. }
  63913. #ifndef SQLITE_OMIT_VIEW
  63914. if( pTab && pTab->pSelect ){
  63915. pTab = 0;
  63916. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  63917. }
  63918. #endif
  63919. if( !pTab ){
  63920. if( pParse->zErrMsg ){
  63921. sqlite3DbFree(db, zErr);
  63922. zErr = pParse->zErrMsg;
  63923. pParse->zErrMsg = 0;
  63924. }
  63925. rc = SQLITE_ERROR;
  63926. sqlite3BtreeLeaveAll(db);
  63927. goto blob_open_out;
  63928. }
  63929. /* Now search pTab for the exact column. */
  63930. for(iCol=0; iCol<pTab->nCol; iCol++) {
  63931. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  63932. break;
  63933. }
  63934. }
  63935. if( iCol==pTab->nCol ){
  63936. sqlite3DbFree(db, zErr);
  63937. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  63938. rc = SQLITE_ERROR;
  63939. sqlite3BtreeLeaveAll(db);
  63940. goto blob_open_out;
  63941. }
  63942. /* If the value is being opened for writing, check that the
  63943. ** column is not indexed, and that it is not part of a foreign key.
  63944. ** It is against the rules to open a column to which either of these
  63945. ** descriptions applies for writing. */
  63946. if( flags ){
  63947. const char *zFault = 0;
  63948. Index *pIdx;
  63949. #ifndef SQLITE_OMIT_FOREIGN_KEY
  63950. if( db->flags&SQLITE_ForeignKeys ){
  63951. /* Check that the column is not part of an FK child key definition. It
  63952. ** is not necessary to check if it is part of a parent key, as parent
  63953. ** key columns must be indexed. The check below will pick up this
  63954. ** case. */
  63955. FKey *pFKey;
  63956. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  63957. int j;
  63958. for(j=0; j<pFKey->nCol; j++){
  63959. if( pFKey->aCol[j].iFrom==iCol ){
  63960. zFault = "foreign key";
  63961. }
  63962. }
  63963. }
  63964. }
  63965. #endif
  63966. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  63967. int j;
  63968. for(j=0; j<pIdx->nColumn; j++){
  63969. if( pIdx->aiColumn[j]==iCol ){
  63970. zFault = "indexed";
  63971. }
  63972. }
  63973. }
  63974. if( zFault ){
  63975. sqlite3DbFree(db, zErr);
  63976. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  63977. rc = SQLITE_ERROR;
  63978. sqlite3BtreeLeaveAll(db);
  63979. goto blob_open_out;
  63980. }
  63981. }
  63982. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
  63983. assert( pBlob->pStmt || db->mallocFailed );
  63984. if( pBlob->pStmt ){
  63985. Vdbe *v = (Vdbe *)pBlob->pStmt;
  63986. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  63987. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  63988. /* Configure the OP_Transaction */
  63989. sqlite3VdbeChangeP1(v, 0, iDb);
  63990. sqlite3VdbeChangeP2(v, 0, flags);
  63991. /* Configure the OP_VerifyCookie */
  63992. sqlite3VdbeChangeP1(v, 1, iDb);
  63993. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  63994. sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
  63995. /* Make sure a mutex is held on the table to be accessed */
  63996. sqlite3VdbeUsesBtree(v, iDb);
  63997. /* Configure the OP_TableLock instruction */
  63998. #ifdef SQLITE_OMIT_SHARED_CACHE
  63999. sqlite3VdbeChangeToNoop(v, 2, 1);
  64000. #else
  64001. sqlite3VdbeChangeP1(v, 2, iDb);
  64002. sqlite3VdbeChangeP2(v, 2, pTab->tnum);
  64003. sqlite3VdbeChangeP3(v, 2, flags);
  64004. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  64005. #endif
  64006. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  64007. ** parameter of the other to pTab->tnum. */
  64008. sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
  64009. sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
  64010. sqlite3VdbeChangeP3(v, 3 + flags, iDb);
  64011. /* Configure the number of columns. Configure the cursor to
  64012. ** think that the table has one more column than it really
  64013. ** does. An OP_Column to retrieve this imaginary column will
  64014. ** always return an SQL NULL. This is useful because it means
  64015. ** we can invoke OP_Column to fill in the vdbe cursors type
  64016. ** and offset cache without causing any IO.
  64017. */
  64018. sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  64019. sqlite3VdbeChangeP2(v, 7, pTab->nCol);
  64020. if( !db->mallocFailed ){
  64021. sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
  64022. }
  64023. }
  64024. pBlob->flags = flags;
  64025. pBlob->iCol = iCol;
  64026. pBlob->db = db;
  64027. sqlite3BtreeLeaveAll(db);
  64028. if( db->mallocFailed ){
  64029. goto blob_open_out;
  64030. }
  64031. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  64032. rc = blobSeekToRow(pBlob, iRow, &zErr);
  64033. } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
  64034. blob_open_out:
  64035. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  64036. *ppBlob = (sqlite3_blob *)pBlob;
  64037. }else{
  64038. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  64039. sqlite3DbFree(db, pBlob);
  64040. }
  64041. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  64042. sqlite3DbFree(db, zErr);
  64043. sqlite3StackFree(db, pParse);
  64044. rc = sqlite3ApiExit(db, rc);
  64045. sqlite3_mutex_leave(db->mutex);
  64046. return rc;
  64047. }
  64048. /*
  64049. ** Close a blob handle that was previously created using
  64050. ** sqlite3_blob_open().
  64051. */
  64052. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  64053. Incrblob *p = (Incrblob *)pBlob;
  64054. int rc;
  64055. sqlite3 *db;
  64056. if( p ){
  64057. db = p->db;
  64058. sqlite3_mutex_enter(db->mutex);
  64059. rc = sqlite3_finalize(p->pStmt);
  64060. sqlite3DbFree(db, p);
  64061. sqlite3_mutex_leave(db->mutex);
  64062. }else{
  64063. rc = SQLITE_OK;
  64064. }
  64065. return rc;
  64066. }
  64067. /*
  64068. ** Perform a read or write operation on a blob
  64069. */
  64070. static int blobReadWrite(
  64071. sqlite3_blob *pBlob,
  64072. void *z,
  64073. int n,
  64074. int iOffset,
  64075. int (*xCall)(BtCursor*, u32, u32, void*)
  64076. ){
  64077. int rc;
  64078. Incrblob *p = (Incrblob *)pBlob;
  64079. Vdbe *v;
  64080. sqlite3 *db;
  64081. if( p==0 ) return SQLITE_MISUSE_BKPT;
  64082. db = p->db;
  64083. sqlite3_mutex_enter(db->mutex);
  64084. v = (Vdbe*)p->pStmt;
  64085. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  64086. /* Request is out of range. Return a transient error. */
  64087. rc = SQLITE_ERROR;
  64088. sqlite3Error(db, SQLITE_ERROR, 0);
  64089. }else if( v==0 ){
  64090. /* If there is no statement handle, then the blob-handle has
  64091. ** already been invalidated. Return SQLITE_ABORT in this case.
  64092. */
  64093. rc = SQLITE_ABORT;
  64094. }else{
  64095. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  64096. ** returned, clean-up the statement handle.
  64097. */
  64098. assert( db == v->db );
  64099. sqlite3BtreeEnterCursor(p->pCsr);
  64100. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  64101. sqlite3BtreeLeaveCursor(p->pCsr);
  64102. if( rc==SQLITE_ABORT ){
  64103. sqlite3VdbeFinalize(v);
  64104. p->pStmt = 0;
  64105. }else{
  64106. db->errCode = rc;
  64107. v->rc = rc;
  64108. }
  64109. }
  64110. rc = sqlite3ApiExit(db, rc);
  64111. sqlite3_mutex_leave(db->mutex);
  64112. return rc;
  64113. }
  64114. /*
  64115. ** Read data from a blob handle.
  64116. */
  64117. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  64118. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  64119. }
  64120. /*
  64121. ** Write data to a blob handle.
  64122. */
  64123. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  64124. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  64125. }
  64126. /*
  64127. ** Query a blob handle for the size of the data.
  64128. **
  64129. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  64130. ** so no mutex is required for access.
  64131. */
  64132. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  64133. Incrblob *p = (Incrblob *)pBlob;
  64134. return (p && p->pStmt) ? p->nByte : 0;
  64135. }
  64136. /*
  64137. ** Move an existing blob handle to point to a different row of the same
  64138. ** database table.
  64139. **
  64140. ** If an error occurs, or if the specified row does not exist or does not
  64141. ** contain a blob or text value, then an error code is returned and the
  64142. ** database handle error code and message set. If this happens, then all
  64143. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  64144. ** immediately return SQLITE_ABORT.
  64145. */
  64146. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  64147. int rc;
  64148. Incrblob *p = (Incrblob *)pBlob;
  64149. sqlite3 *db;
  64150. if( p==0 ) return SQLITE_MISUSE_BKPT;
  64151. db = p->db;
  64152. sqlite3_mutex_enter(db->mutex);
  64153. if( p->pStmt==0 ){
  64154. /* If there is no statement handle, then the blob-handle has
  64155. ** already been invalidated. Return SQLITE_ABORT in this case.
  64156. */
  64157. rc = SQLITE_ABORT;
  64158. }else{
  64159. char *zErr;
  64160. rc = blobSeekToRow(p, iRow, &zErr);
  64161. if( rc!=SQLITE_OK ){
  64162. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  64163. sqlite3DbFree(db, zErr);
  64164. }
  64165. assert( rc!=SQLITE_SCHEMA );
  64166. }
  64167. rc = sqlite3ApiExit(db, rc);
  64168. assert( rc==SQLITE_OK || p->pStmt==0 );
  64169. sqlite3_mutex_leave(db->mutex);
  64170. return rc;
  64171. }
  64172. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  64173. /************** End of vdbeblob.c ********************************************/
  64174. /************** Begin file journal.c *****************************************/
  64175. /*
  64176. ** 2007 August 22
  64177. **
  64178. ** The author disclaims copyright to this source code. In place of
  64179. ** a legal notice, here is a blessing:
  64180. **
  64181. ** May you do good and not evil.
  64182. ** May you find forgiveness for yourself and forgive others.
  64183. ** May you share freely, never taking more than you give.
  64184. **
  64185. *************************************************************************
  64186. **
  64187. ** This file implements a special kind of sqlite3_file object used
  64188. ** by SQLite to create journal files if the atomic-write optimization
  64189. ** is enabled.
  64190. **
  64191. ** The distinctive characteristic of this sqlite3_file is that the
  64192. ** actual on disk file is created lazily. When the file is created,
  64193. ** the caller specifies a buffer size for an in-memory buffer to
  64194. ** be used to service read() and write() requests. The actual file
  64195. ** on disk is not created or populated until either:
  64196. **
  64197. ** 1) The in-memory representation grows too large for the allocated
  64198. ** buffer, or
  64199. ** 2) The sqlite3JournalCreate() function is called.
  64200. */
  64201. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  64202. /*
  64203. ** A JournalFile object is a subclass of sqlite3_file used by
  64204. ** as an open file handle for journal files.
  64205. */
  64206. struct JournalFile {
  64207. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  64208. int nBuf; /* Size of zBuf[] in bytes */
  64209. char *zBuf; /* Space to buffer journal writes */
  64210. int iSize; /* Amount of zBuf[] currently used */
  64211. int flags; /* xOpen flags */
  64212. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  64213. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  64214. const char *zJournal; /* Name of the journal file */
  64215. };
  64216. typedef struct JournalFile JournalFile;
  64217. /*
  64218. ** If it does not already exists, create and populate the on-disk file
  64219. ** for JournalFile p.
  64220. */
  64221. static int createFile(JournalFile *p){
  64222. int rc = SQLITE_OK;
  64223. if( !p->pReal ){
  64224. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  64225. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  64226. if( rc==SQLITE_OK ){
  64227. p->pReal = pReal;
  64228. if( p->iSize>0 ){
  64229. assert(p->iSize<=p->nBuf);
  64230. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  64231. }
  64232. }
  64233. }
  64234. return rc;
  64235. }
  64236. /*
  64237. ** Close the file.
  64238. */
  64239. static int jrnlClose(sqlite3_file *pJfd){
  64240. JournalFile *p = (JournalFile *)pJfd;
  64241. if( p->pReal ){
  64242. sqlite3OsClose(p->pReal);
  64243. }
  64244. sqlite3_free(p->zBuf);
  64245. return SQLITE_OK;
  64246. }
  64247. /*
  64248. ** Read data from the file.
  64249. */
  64250. static int jrnlRead(
  64251. sqlite3_file *pJfd, /* The journal file from which to read */
  64252. void *zBuf, /* Put the results here */
  64253. int iAmt, /* Number of bytes to read */
  64254. sqlite_int64 iOfst /* Begin reading at this offset */
  64255. ){
  64256. int rc = SQLITE_OK;
  64257. JournalFile *p = (JournalFile *)pJfd;
  64258. if( p->pReal ){
  64259. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  64260. }else if( (iAmt+iOfst)>p->iSize ){
  64261. rc = SQLITE_IOERR_SHORT_READ;
  64262. }else{
  64263. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  64264. }
  64265. return rc;
  64266. }
  64267. /*
  64268. ** Write data to the file.
  64269. */
  64270. static int jrnlWrite(
  64271. sqlite3_file *pJfd, /* The journal file into which to write */
  64272. const void *zBuf, /* Take data to be written from here */
  64273. int iAmt, /* Number of bytes to write */
  64274. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  64275. ){
  64276. int rc = SQLITE_OK;
  64277. JournalFile *p = (JournalFile *)pJfd;
  64278. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  64279. rc = createFile(p);
  64280. }
  64281. if( rc==SQLITE_OK ){
  64282. if( p->pReal ){
  64283. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  64284. }else{
  64285. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  64286. if( p->iSize<(iOfst+iAmt) ){
  64287. p->iSize = (iOfst+iAmt);
  64288. }
  64289. }
  64290. }
  64291. return rc;
  64292. }
  64293. /*
  64294. ** Truncate the file.
  64295. */
  64296. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  64297. int rc = SQLITE_OK;
  64298. JournalFile *p = (JournalFile *)pJfd;
  64299. if( p->pReal ){
  64300. rc = sqlite3OsTruncate(p->pReal, size);
  64301. }else if( size<p->iSize ){
  64302. p->iSize = size;
  64303. }
  64304. return rc;
  64305. }
  64306. /*
  64307. ** Sync the file.
  64308. */
  64309. static int jrnlSync(sqlite3_file *pJfd, int flags){
  64310. int rc;
  64311. JournalFile *p = (JournalFile *)pJfd;
  64312. if( p->pReal ){
  64313. rc = sqlite3OsSync(p->pReal, flags);
  64314. }else{
  64315. rc = SQLITE_OK;
  64316. }
  64317. return rc;
  64318. }
  64319. /*
  64320. ** Query the size of the file in bytes.
  64321. */
  64322. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  64323. int rc = SQLITE_OK;
  64324. JournalFile *p = (JournalFile *)pJfd;
  64325. if( p->pReal ){
  64326. rc = sqlite3OsFileSize(p->pReal, pSize);
  64327. }else{
  64328. *pSize = (sqlite_int64) p->iSize;
  64329. }
  64330. return rc;
  64331. }
  64332. /*
  64333. ** Table of methods for JournalFile sqlite3_file object.
  64334. */
  64335. static struct sqlite3_io_methods JournalFileMethods = {
  64336. 1, /* iVersion */
  64337. jrnlClose, /* xClose */
  64338. jrnlRead, /* xRead */
  64339. jrnlWrite, /* xWrite */
  64340. jrnlTruncate, /* xTruncate */
  64341. jrnlSync, /* xSync */
  64342. jrnlFileSize, /* xFileSize */
  64343. 0, /* xLock */
  64344. 0, /* xUnlock */
  64345. 0, /* xCheckReservedLock */
  64346. 0, /* xFileControl */
  64347. 0, /* xSectorSize */
  64348. 0, /* xDeviceCharacteristics */
  64349. 0, /* xShmMap */
  64350. 0, /* xShmLock */
  64351. 0, /* xShmBarrier */
  64352. 0 /* xShmUnmap */
  64353. };
  64354. /*
  64355. ** Open a journal file.
  64356. */
  64357. SQLITE_PRIVATE int sqlite3JournalOpen(
  64358. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  64359. const char *zName, /* Name of the journal file */
  64360. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  64361. int flags, /* Opening flags */
  64362. int nBuf /* Bytes buffered before opening the file */
  64363. ){
  64364. JournalFile *p = (JournalFile *)pJfd;
  64365. memset(p, 0, sqlite3JournalSize(pVfs));
  64366. if( nBuf>0 ){
  64367. p->zBuf = sqlite3MallocZero(nBuf);
  64368. if( !p->zBuf ){
  64369. return SQLITE_NOMEM;
  64370. }
  64371. }else{
  64372. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  64373. }
  64374. p->pMethod = &JournalFileMethods;
  64375. p->nBuf = nBuf;
  64376. p->flags = flags;
  64377. p->zJournal = zName;
  64378. p->pVfs = pVfs;
  64379. return SQLITE_OK;
  64380. }
  64381. /*
  64382. ** If the argument p points to a JournalFile structure, and the underlying
  64383. ** file has not yet been created, create it now.
  64384. */
  64385. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  64386. if( p->pMethods!=&JournalFileMethods ){
  64387. return SQLITE_OK;
  64388. }
  64389. return createFile((JournalFile *)p);
  64390. }
  64391. /*
  64392. ** Return the number of bytes required to store a JournalFile that uses vfs
  64393. ** pVfs to create the underlying on-disk files.
  64394. */
  64395. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  64396. return (pVfs->szOsFile+sizeof(JournalFile));
  64397. }
  64398. #endif
  64399. /************** End of journal.c *********************************************/
  64400. /************** Begin file memjournal.c **************************************/
  64401. /*
  64402. ** 2008 October 7
  64403. **
  64404. ** The author disclaims copyright to this source code. In place of
  64405. ** a legal notice, here is a blessing:
  64406. **
  64407. ** May you do good and not evil.
  64408. ** May you find forgiveness for yourself and forgive others.
  64409. ** May you share freely, never taking more than you give.
  64410. **
  64411. *************************************************************************
  64412. **
  64413. ** This file contains code use to implement an in-memory rollback journal.
  64414. ** The in-memory rollback journal is used to journal transactions for
  64415. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  64416. */
  64417. /* Forward references to internal structures */
  64418. typedef struct MemJournal MemJournal;
  64419. typedef struct FilePoint FilePoint;
  64420. typedef struct FileChunk FileChunk;
  64421. /* Space to hold the rollback journal is allocated in increments of
  64422. ** this many bytes.
  64423. **
  64424. ** The size chosen is a little less than a power of two. That way,
  64425. ** the FileChunk object will have a size that almost exactly fills
  64426. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  64427. ** memory allocators.
  64428. */
  64429. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  64430. /* Macro to find the minimum of two numeric values.
  64431. */
  64432. #ifndef MIN
  64433. # define MIN(x,y) ((x)<(y)?(x):(y))
  64434. #endif
  64435. /*
  64436. ** The rollback journal is composed of a linked list of these structures.
  64437. */
  64438. struct FileChunk {
  64439. FileChunk *pNext; /* Next chunk in the journal */
  64440. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  64441. };
  64442. /*
  64443. ** An instance of this object serves as a cursor into the rollback journal.
  64444. ** The cursor can be either for reading or writing.
  64445. */
  64446. struct FilePoint {
  64447. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  64448. FileChunk *pChunk; /* Specific chunk into which cursor points */
  64449. };
  64450. /*
  64451. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  64452. ** is an instance of this class.
  64453. */
  64454. struct MemJournal {
  64455. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  64456. FileChunk *pFirst; /* Head of in-memory chunk-list */
  64457. FilePoint endpoint; /* Pointer to the end of the file */
  64458. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  64459. };
  64460. /*
  64461. ** Read data from the in-memory journal file. This is the implementation
  64462. ** of the sqlite3_vfs.xRead method.
  64463. */
  64464. static int memjrnlRead(
  64465. sqlite3_file *pJfd, /* The journal file from which to read */
  64466. void *zBuf, /* Put the results here */
  64467. int iAmt, /* Number of bytes to read */
  64468. sqlite_int64 iOfst /* Begin reading at this offset */
  64469. ){
  64470. MemJournal *p = (MemJournal *)pJfd;
  64471. u8 *zOut = zBuf;
  64472. int nRead = iAmt;
  64473. int iChunkOffset;
  64474. FileChunk *pChunk;
  64475. /* SQLite never tries to read past the end of a rollback journal file */
  64476. assert( iOfst+iAmt<=p->endpoint.iOffset );
  64477. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  64478. sqlite3_int64 iOff = 0;
  64479. for(pChunk=p->pFirst;
  64480. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  64481. pChunk=pChunk->pNext
  64482. ){
  64483. iOff += JOURNAL_CHUNKSIZE;
  64484. }
  64485. }else{
  64486. pChunk = p->readpoint.pChunk;
  64487. }
  64488. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  64489. do {
  64490. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  64491. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  64492. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  64493. zOut += nCopy;
  64494. nRead -= iSpace;
  64495. iChunkOffset = 0;
  64496. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  64497. p->readpoint.iOffset = iOfst+iAmt;
  64498. p->readpoint.pChunk = pChunk;
  64499. return SQLITE_OK;
  64500. }
  64501. /*
  64502. ** Write data to the file.
  64503. */
  64504. static int memjrnlWrite(
  64505. sqlite3_file *pJfd, /* The journal file into which to write */
  64506. const void *zBuf, /* Take data to be written from here */
  64507. int iAmt, /* Number of bytes to write */
  64508. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  64509. ){
  64510. MemJournal *p = (MemJournal *)pJfd;
  64511. int nWrite = iAmt;
  64512. u8 *zWrite = (u8 *)zBuf;
  64513. /* An in-memory journal file should only ever be appended to. Random
  64514. ** access writes are not required by sqlite.
  64515. */
  64516. assert( iOfst==p->endpoint.iOffset );
  64517. UNUSED_PARAMETER(iOfst);
  64518. while( nWrite>0 ){
  64519. FileChunk *pChunk = p->endpoint.pChunk;
  64520. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  64521. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  64522. if( iChunkOffset==0 ){
  64523. /* New chunk is required to extend the file. */
  64524. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  64525. if( !pNew ){
  64526. return SQLITE_IOERR_NOMEM;
  64527. }
  64528. pNew->pNext = 0;
  64529. if( pChunk ){
  64530. assert( p->pFirst );
  64531. pChunk->pNext = pNew;
  64532. }else{
  64533. assert( !p->pFirst );
  64534. p->pFirst = pNew;
  64535. }
  64536. p->endpoint.pChunk = pNew;
  64537. }
  64538. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  64539. zWrite += iSpace;
  64540. nWrite -= iSpace;
  64541. p->endpoint.iOffset += iSpace;
  64542. }
  64543. return SQLITE_OK;
  64544. }
  64545. /*
  64546. ** Truncate the file.
  64547. */
  64548. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  64549. MemJournal *p = (MemJournal *)pJfd;
  64550. FileChunk *pChunk;
  64551. assert(size==0);
  64552. UNUSED_PARAMETER(size);
  64553. pChunk = p->pFirst;
  64554. while( pChunk ){
  64555. FileChunk *pTmp = pChunk;
  64556. pChunk = pChunk->pNext;
  64557. sqlite3_free(pTmp);
  64558. }
  64559. sqlite3MemJournalOpen(pJfd);
  64560. return SQLITE_OK;
  64561. }
  64562. /*
  64563. ** Close the file.
  64564. */
  64565. static int memjrnlClose(sqlite3_file *pJfd){
  64566. memjrnlTruncate(pJfd, 0);
  64567. return SQLITE_OK;
  64568. }
  64569. /*
  64570. ** Sync the file.
  64571. **
  64572. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  64573. ** is never called in a working implementation. This implementation
  64574. ** exists purely as a contingency, in case some malfunction in some other
  64575. ** part of SQLite causes Sync to be called by mistake.
  64576. */
  64577. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  64578. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  64579. return SQLITE_OK;
  64580. }
  64581. /*
  64582. ** Query the size of the file in bytes.
  64583. */
  64584. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  64585. MemJournal *p = (MemJournal *)pJfd;
  64586. *pSize = (sqlite_int64) p->endpoint.iOffset;
  64587. return SQLITE_OK;
  64588. }
  64589. /*
  64590. ** Table of methods for MemJournal sqlite3_file object.
  64591. */
  64592. static const struct sqlite3_io_methods MemJournalMethods = {
  64593. 1, /* iVersion */
  64594. memjrnlClose, /* xClose */
  64595. memjrnlRead, /* xRead */
  64596. memjrnlWrite, /* xWrite */
  64597. memjrnlTruncate, /* xTruncate */
  64598. memjrnlSync, /* xSync */
  64599. memjrnlFileSize, /* xFileSize */
  64600. 0, /* xLock */
  64601. 0, /* xUnlock */
  64602. 0, /* xCheckReservedLock */
  64603. 0, /* xFileControl */
  64604. 0, /* xSectorSize */
  64605. 0, /* xDeviceCharacteristics */
  64606. 0, /* xShmMap */
  64607. 0, /* xShmLock */
  64608. 0, /* xShmBarrier */
  64609. 0 /* xShmUnlock */
  64610. };
  64611. /*
  64612. ** Open a journal file.
  64613. */
  64614. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  64615. MemJournal *p = (MemJournal *)pJfd;
  64616. assert( EIGHT_BYTE_ALIGNMENT(p) );
  64617. memset(p, 0, sqlite3MemJournalSize());
  64618. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  64619. }
  64620. /*
  64621. ** Return true if the file-handle passed as an argument is
  64622. ** an in-memory journal
  64623. */
  64624. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  64625. return pJfd->pMethods==&MemJournalMethods;
  64626. }
  64627. /*
  64628. ** Return the number of bytes required to store a MemJournal file descriptor.
  64629. */
  64630. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  64631. return sizeof(MemJournal);
  64632. }
  64633. /************** End of memjournal.c ******************************************/
  64634. /************** Begin file walker.c ******************************************/
  64635. /*
  64636. ** 2008 August 16
  64637. **
  64638. ** The author disclaims copyright to this source code. In place of
  64639. ** a legal notice, here is a blessing:
  64640. **
  64641. ** May you do good and not evil.
  64642. ** May you find forgiveness for yourself and forgive others.
  64643. ** May you share freely, never taking more than you give.
  64644. **
  64645. *************************************************************************
  64646. ** This file contains routines used for walking the parser tree for
  64647. ** an SQL statement.
  64648. */
  64649. /*
  64650. ** Walk an expression tree. Invoke the callback once for each node
  64651. ** of the expression, while decending. (In other words, the callback
  64652. ** is invoked before visiting children.)
  64653. **
  64654. ** The return value from the callback should be one of the WRC_*
  64655. ** constants to specify how to proceed with the walk.
  64656. **
  64657. ** WRC_Continue Continue descending down the tree.
  64658. **
  64659. ** WRC_Prune Do not descend into child nodes. But allow
  64660. ** the walk to continue with sibling nodes.
  64661. **
  64662. ** WRC_Abort Do no more callbacks. Unwind the stack and
  64663. ** return the top-level walk call.
  64664. **
  64665. ** The return value from this routine is WRC_Abort to abandon the tree walk
  64666. ** and WRC_Continue to continue.
  64667. */
  64668. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  64669. int rc;
  64670. if( pExpr==0 ) return WRC_Continue;
  64671. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  64672. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  64673. rc = pWalker->xExprCallback(pWalker, pExpr);
  64674. if( rc==WRC_Continue
  64675. && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
  64676. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  64677. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  64678. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  64679. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  64680. }else{
  64681. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  64682. }
  64683. }
  64684. return rc & WRC_Abort;
  64685. }
  64686. /*
  64687. ** Call sqlite3WalkExpr() for every expression in list p or until
  64688. ** an abort request is seen.
  64689. */
  64690. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  64691. int i;
  64692. struct ExprList_item *pItem;
  64693. if( p ){
  64694. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  64695. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  64696. }
  64697. }
  64698. return WRC_Continue;
  64699. }
  64700. /*
  64701. ** Walk all expressions associated with SELECT statement p. Do
  64702. ** not invoke the SELECT callback on p, but do (of course) invoke
  64703. ** any expr callbacks and SELECT callbacks that come from subqueries.
  64704. ** Return WRC_Abort or WRC_Continue.
  64705. */
  64706. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  64707. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  64708. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  64709. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  64710. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  64711. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  64712. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  64713. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  64714. return WRC_Continue;
  64715. }
  64716. /*
  64717. ** Walk the parse trees associated with all subqueries in the
  64718. ** FROM clause of SELECT statement p. Do not invoke the select
  64719. ** callback on p, but do invoke it on each FROM clause subquery
  64720. ** and on any subqueries further down in the tree. Return
  64721. ** WRC_Abort or WRC_Continue;
  64722. */
  64723. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  64724. SrcList *pSrc;
  64725. int i;
  64726. struct SrcList_item *pItem;
  64727. pSrc = p->pSrc;
  64728. if( ALWAYS(pSrc) ){
  64729. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  64730. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  64731. return WRC_Abort;
  64732. }
  64733. }
  64734. }
  64735. return WRC_Continue;
  64736. }
  64737. /*
  64738. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  64739. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  64740. ** on the compound select chain, p->pPrior.
  64741. **
  64742. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  64743. ** there is an abort request.
  64744. **
  64745. ** If the Walker does not have an xSelectCallback() then this routine
  64746. ** is a no-op returning WRC_Continue.
  64747. */
  64748. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  64749. int rc;
  64750. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  64751. rc = WRC_Continue;
  64752. while( p ){
  64753. rc = pWalker->xSelectCallback(pWalker, p);
  64754. if( rc ) break;
  64755. if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
  64756. if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
  64757. p = p->pPrior;
  64758. }
  64759. return rc & WRC_Abort;
  64760. }
  64761. /************** End of walker.c **********************************************/
  64762. /************** Begin file resolve.c *****************************************/
  64763. /*
  64764. ** 2008 August 18
  64765. **
  64766. ** The author disclaims copyright to this source code. In place of
  64767. ** a legal notice, here is a blessing:
  64768. **
  64769. ** May you do good and not evil.
  64770. ** May you find forgiveness for yourself and forgive others.
  64771. ** May you share freely, never taking more than you give.
  64772. **
  64773. *************************************************************************
  64774. **
  64775. ** This file contains routines used for walking the parser tree and
  64776. ** resolve all identifiers by associating them with a particular
  64777. ** table and column.
  64778. */
  64779. /*
  64780. ** Turn the pExpr expression into an alias for the iCol-th column of the
  64781. ** result set in pEList.
  64782. **
  64783. ** If the result set column is a simple column reference, then this routine
  64784. ** makes an exact copy. But for any other kind of expression, this
  64785. ** routine make a copy of the result set column as the argument to the
  64786. ** TK_AS operator. The TK_AS operator causes the expression to be
  64787. ** evaluated just once and then reused for each alias.
  64788. **
  64789. ** The reason for suppressing the TK_AS term when the expression is a simple
  64790. ** column reference is so that the column reference will be recognized as
  64791. ** usable by indices within the WHERE clause processing logic.
  64792. **
  64793. ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
  64794. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  64795. **
  64796. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  64797. **
  64798. ** Is equivalent to:
  64799. **
  64800. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  64801. **
  64802. ** The result of random()%5 in the GROUP BY clause is probably different
  64803. ** from the result in the result-set. We might fix this someday. Or
  64804. ** then again, we might not...
  64805. */
  64806. static void resolveAlias(
  64807. Parse *pParse, /* Parsing context */
  64808. ExprList *pEList, /* A result set */
  64809. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  64810. Expr *pExpr, /* Transform this into an alias to the result set */
  64811. const char *zType /* "GROUP" or "ORDER" or "" */
  64812. ){
  64813. Expr *pOrig; /* The iCol-th column of the result set */
  64814. Expr *pDup; /* Copy of pOrig */
  64815. sqlite3 *db; /* The database connection */
  64816. assert( iCol>=0 && iCol<pEList->nExpr );
  64817. pOrig = pEList->a[iCol].pExpr;
  64818. assert( pOrig!=0 );
  64819. assert( pOrig->flags & EP_Resolved );
  64820. db = pParse->db;
  64821. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  64822. pDup = sqlite3ExprDup(db, pOrig, 0);
  64823. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  64824. if( pDup==0 ) return;
  64825. if( pEList->a[iCol].iAlias==0 ){
  64826. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  64827. }
  64828. pDup->iTable = pEList->a[iCol].iAlias;
  64829. }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
  64830. pDup = sqlite3ExprDup(db, pOrig, 0);
  64831. if( pDup==0 ) return;
  64832. }else{
  64833. char *zToken = pOrig->u.zToken;
  64834. assert( zToken!=0 );
  64835. pOrig->u.zToken = 0;
  64836. pDup = sqlite3ExprDup(db, pOrig, 0);
  64837. pOrig->u.zToken = zToken;
  64838. if( pDup==0 ) return;
  64839. assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
  64840. pDup->flags2 |= EP2_MallocedToken;
  64841. pDup->u.zToken = sqlite3DbStrDup(db, zToken);
  64842. }
  64843. if( pExpr->flags & EP_ExpCollate ){
  64844. pDup->pColl = pExpr->pColl;
  64845. pDup->flags |= EP_ExpCollate;
  64846. }
  64847. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  64848. ** prevents ExprDelete() from deleting the Expr structure itself,
  64849. ** allowing it to be repopulated by the memcpy() on the following line.
  64850. */
  64851. ExprSetProperty(pExpr, EP_Static);
  64852. sqlite3ExprDelete(db, pExpr);
  64853. memcpy(pExpr, pDup, sizeof(*pExpr));
  64854. sqlite3DbFree(db, pDup);
  64855. }
  64856. /*
  64857. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  64858. ** that name in the set of source tables in pSrcList and make the pExpr
  64859. ** expression node refer back to that source column. The following changes
  64860. ** are made to pExpr:
  64861. **
  64862. ** pExpr->iDb Set the index in db->aDb[] of the database X
  64863. ** (even if X is implied).
  64864. ** pExpr->iTable Set to the cursor number for the table obtained
  64865. ** from pSrcList.
  64866. ** pExpr->pTab Points to the Table structure of X.Y (even if
  64867. ** X and/or Y are implied.)
  64868. ** pExpr->iColumn Set to the column number within the table.
  64869. ** pExpr->op Set to TK_COLUMN.
  64870. ** pExpr->pLeft Any expression this points to is deleted
  64871. ** pExpr->pRight Any expression this points to is deleted.
  64872. **
  64873. ** The zDb variable is the name of the database (the "X"). This value may be
  64874. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  64875. ** can be used. The zTable variable is the name of the table (the "Y"). This
  64876. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  64877. ** means that the form of the name is Z and that columns from any table
  64878. ** can be used.
  64879. **
  64880. ** If the name cannot be resolved unambiguously, leave an error message
  64881. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  64882. */
  64883. static int lookupName(
  64884. Parse *pParse, /* The parsing context */
  64885. const char *zDb, /* Name of the database containing table, or NULL */
  64886. const char *zTab, /* Name of table containing column, or NULL */
  64887. const char *zCol, /* Name of the column. */
  64888. NameContext *pNC, /* The name context used to resolve the name */
  64889. Expr *pExpr /* Make this EXPR node point to the selected column */
  64890. ){
  64891. int i, j; /* Loop counters */
  64892. int cnt = 0; /* Number of matching column names */
  64893. int cntTab = 0; /* Number of matching table names */
  64894. sqlite3 *db = pParse->db; /* The database connection */
  64895. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  64896. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  64897. NameContext *pTopNC = pNC; /* First namecontext in the list */
  64898. Schema *pSchema = 0; /* Schema of the expression */
  64899. int isTrigger = 0;
  64900. assert( pNC ); /* the name context cannot be NULL. */
  64901. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  64902. assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  64903. /* Initialize the node to no-match */
  64904. pExpr->iTable = -1;
  64905. pExpr->pTab = 0;
  64906. ExprSetIrreducible(pExpr);
  64907. /* Start at the inner-most context and move outward until a match is found */
  64908. while( pNC && cnt==0 ){
  64909. ExprList *pEList;
  64910. SrcList *pSrcList = pNC->pSrcList;
  64911. if( pSrcList ){
  64912. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  64913. Table *pTab;
  64914. int iDb;
  64915. Column *pCol;
  64916. pTab = pItem->pTab;
  64917. assert( pTab!=0 && pTab->zName!=0 );
  64918. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  64919. assert( pTab->nCol>0 );
  64920. if( zTab ){
  64921. if( pItem->zAlias ){
  64922. char *zTabName = pItem->zAlias;
  64923. if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
  64924. }else{
  64925. char *zTabName = pTab->zName;
  64926. if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
  64927. continue;
  64928. }
  64929. if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
  64930. continue;
  64931. }
  64932. }
  64933. }
  64934. if( 0==(cntTab++) ){
  64935. pExpr->iTable = pItem->iCursor;
  64936. pExpr->pTab = pTab;
  64937. pSchema = pTab->pSchema;
  64938. pMatch = pItem;
  64939. }
  64940. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  64941. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  64942. IdList *pUsing;
  64943. cnt++;
  64944. pExpr->iTable = pItem->iCursor;
  64945. pExpr->pTab = pTab;
  64946. pMatch = pItem;
  64947. pSchema = pTab->pSchema;
  64948. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  64949. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  64950. if( i<pSrcList->nSrc-1 ){
  64951. if( pItem[1].jointype & JT_NATURAL ){
  64952. /* If this match occurred in the left table of a natural join,
  64953. ** then skip the right table to avoid a duplicate match */
  64954. pItem++;
  64955. i++;
  64956. }else if( (pUsing = pItem[1].pUsing)!=0 ){
  64957. /* If this match occurs on a column that is in the USING clause
  64958. ** of a join, skip the search of the right table of the join
  64959. ** to avoid a duplicate match there. */
  64960. int k;
  64961. for(k=0; k<pUsing->nId; k++){
  64962. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
  64963. pItem++;
  64964. i++;
  64965. break;
  64966. }
  64967. }
  64968. }
  64969. }
  64970. break;
  64971. }
  64972. }
  64973. }
  64974. }
  64975. #ifndef SQLITE_OMIT_TRIGGER
  64976. /* If we have not already resolved the name, then maybe
  64977. ** it is a new.* or old.* trigger argument reference
  64978. */
  64979. if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
  64980. int op = pParse->eTriggerOp;
  64981. Table *pTab = 0;
  64982. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  64983. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  64984. pExpr->iTable = 1;
  64985. pTab = pParse->pTriggerTab;
  64986. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  64987. pExpr->iTable = 0;
  64988. pTab = pParse->pTriggerTab;
  64989. }
  64990. if( pTab ){
  64991. int iCol;
  64992. pSchema = pTab->pSchema;
  64993. cntTab++;
  64994. for(iCol=0; iCol<pTab->nCol; iCol++){
  64995. Column *pCol = &pTab->aCol[iCol];
  64996. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  64997. if( iCol==pTab->iPKey ){
  64998. iCol = -1;
  64999. }
  65000. break;
  65001. }
  65002. }
  65003. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
  65004. iCol = -1; /* IMP: R-44911-55124 */
  65005. }
  65006. if( iCol<pTab->nCol ){
  65007. cnt++;
  65008. if( iCol<0 ){
  65009. pExpr->affinity = SQLITE_AFF_INTEGER;
  65010. }else if( pExpr->iTable==0 ){
  65011. testcase( iCol==31 );
  65012. testcase( iCol==32 );
  65013. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  65014. }else{
  65015. testcase( iCol==31 );
  65016. testcase( iCol==32 );
  65017. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  65018. }
  65019. pExpr->iColumn = (i16)iCol;
  65020. pExpr->pTab = pTab;
  65021. isTrigger = 1;
  65022. }
  65023. }
  65024. }
  65025. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  65026. /*
  65027. ** Perhaps the name is a reference to the ROWID
  65028. */
  65029. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  65030. cnt = 1;
  65031. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  65032. pExpr->affinity = SQLITE_AFF_INTEGER;
  65033. }
  65034. /*
  65035. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  65036. ** might refer to an result-set alias. This happens, for example, when
  65037. ** we are resolving names in the WHERE clause of the following command:
  65038. **
  65039. ** SELECT a+b AS x FROM table WHERE x<10;
  65040. **
  65041. ** In cases like this, replace pExpr with a copy of the expression that
  65042. ** forms the result set entry ("a+b" in the example) and return immediately.
  65043. ** Note that the expression in the result set should have already been
  65044. ** resolved by the time the WHERE clause is resolved.
  65045. */
  65046. if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
  65047. for(j=0; j<pEList->nExpr; j++){
  65048. char *zAs = pEList->a[j].zName;
  65049. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  65050. Expr *pOrig;
  65051. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  65052. assert( pExpr->x.pList==0 );
  65053. assert( pExpr->x.pSelect==0 );
  65054. pOrig = pEList->a[j].pExpr;
  65055. if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
  65056. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  65057. return WRC_Abort;
  65058. }
  65059. resolveAlias(pParse, pEList, j, pExpr, "");
  65060. cnt = 1;
  65061. pMatch = 0;
  65062. assert( zTab==0 && zDb==0 );
  65063. goto lookupname_end;
  65064. }
  65065. }
  65066. }
  65067. /* Advance to the next name context. The loop will exit when either
  65068. ** we have a match (cnt>0) or when we run out of name contexts.
  65069. */
  65070. if( cnt==0 ){
  65071. pNC = pNC->pNext;
  65072. }
  65073. }
  65074. /*
  65075. ** If X and Y are NULL (in other words if only the column name Z is
  65076. ** supplied) and the value of Z is enclosed in double-quotes, then
  65077. ** Z is a string literal if it doesn't match any column names. In that
  65078. ** case, we need to return right away and not make any changes to
  65079. ** pExpr.
  65080. **
  65081. ** Because no reference was made to outer contexts, the pNC->nRef
  65082. ** fields are not changed in any context.
  65083. */
  65084. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  65085. pExpr->op = TK_STRING;
  65086. pExpr->pTab = 0;
  65087. return WRC_Prune;
  65088. }
  65089. /*
  65090. ** cnt==0 means there was not match. cnt>1 means there were two or
  65091. ** more matches. Either way, we have an error.
  65092. */
  65093. if( cnt!=1 ){
  65094. const char *zErr;
  65095. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  65096. if( zDb ){
  65097. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  65098. }else if( zTab ){
  65099. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  65100. }else{
  65101. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  65102. }
  65103. pParse->checkSchema = 1;
  65104. pTopNC->nErr++;
  65105. }
  65106. /* If a column from a table in pSrcList is referenced, then record
  65107. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  65108. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  65109. ** column number is greater than the number of bits in the bitmask
  65110. ** then set the high-order bit of the bitmask.
  65111. */
  65112. if( pExpr->iColumn>=0 && pMatch!=0 ){
  65113. int n = pExpr->iColumn;
  65114. testcase( n==BMS-1 );
  65115. if( n>=BMS ){
  65116. n = BMS-1;
  65117. }
  65118. assert( pMatch->iCursor==pExpr->iTable );
  65119. pMatch->colUsed |= ((Bitmask)1)<<n;
  65120. }
  65121. /* Clean up and return
  65122. */
  65123. sqlite3ExprDelete(db, pExpr->pLeft);
  65124. pExpr->pLeft = 0;
  65125. sqlite3ExprDelete(db, pExpr->pRight);
  65126. pExpr->pRight = 0;
  65127. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  65128. lookupname_end:
  65129. if( cnt==1 ){
  65130. assert( pNC!=0 );
  65131. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  65132. /* Increment the nRef value on all name contexts from TopNC up to
  65133. ** the point where the name matched. */
  65134. for(;;){
  65135. assert( pTopNC!=0 );
  65136. pTopNC->nRef++;
  65137. if( pTopNC==pNC ) break;
  65138. pTopNC = pTopNC->pNext;
  65139. }
  65140. return WRC_Prune;
  65141. } else {
  65142. return WRC_Abort;
  65143. }
  65144. }
  65145. /*
  65146. ** Allocate and return a pointer to an expression to load the column iCol
  65147. ** from datasource iSrc in SrcList pSrc.
  65148. */
  65149. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  65150. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  65151. if( p ){
  65152. struct SrcList_item *pItem = &pSrc->a[iSrc];
  65153. p->pTab = pItem->pTab;
  65154. p->iTable = pItem->iCursor;
  65155. if( p->pTab->iPKey==iCol ){
  65156. p->iColumn = -1;
  65157. }else{
  65158. p->iColumn = (ynVar)iCol;
  65159. testcase( iCol==BMS );
  65160. testcase( iCol==BMS-1 );
  65161. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  65162. }
  65163. ExprSetProperty(p, EP_Resolved);
  65164. }
  65165. return p;
  65166. }
  65167. /*
  65168. ** This routine is callback for sqlite3WalkExpr().
  65169. **
  65170. ** Resolve symbolic names into TK_COLUMN operators for the current
  65171. ** node in the expression tree. Return 0 to continue the search down
  65172. ** the tree or 2 to abort the tree walk.
  65173. **
  65174. ** This routine also does error checking and name resolution for
  65175. ** function names. The operator for aggregate functions is changed
  65176. ** to TK_AGG_FUNCTION.
  65177. */
  65178. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  65179. NameContext *pNC;
  65180. Parse *pParse;
  65181. pNC = pWalker->u.pNC;
  65182. assert( pNC!=0 );
  65183. pParse = pNC->pParse;
  65184. assert( pParse==pWalker->pParse );
  65185. if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  65186. ExprSetProperty(pExpr, EP_Resolved);
  65187. #ifndef NDEBUG
  65188. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  65189. SrcList *pSrcList = pNC->pSrcList;
  65190. int i;
  65191. for(i=0; i<pNC->pSrcList->nSrc; i++){
  65192. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  65193. }
  65194. }
  65195. #endif
  65196. switch( pExpr->op ){
  65197. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  65198. /* The special operator TK_ROW means use the rowid for the first
  65199. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  65200. ** clause processing on UPDATE and DELETE statements.
  65201. */
  65202. case TK_ROW: {
  65203. SrcList *pSrcList = pNC->pSrcList;
  65204. struct SrcList_item *pItem;
  65205. assert( pSrcList && pSrcList->nSrc==1 );
  65206. pItem = pSrcList->a;
  65207. pExpr->op = TK_COLUMN;
  65208. pExpr->pTab = pItem->pTab;
  65209. pExpr->iTable = pItem->iCursor;
  65210. pExpr->iColumn = -1;
  65211. pExpr->affinity = SQLITE_AFF_INTEGER;
  65212. break;
  65213. }
  65214. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  65215. /* A lone identifier is the name of a column.
  65216. */
  65217. case TK_ID: {
  65218. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  65219. }
  65220. /* A table name and column name: ID.ID
  65221. ** Or a database, table and column: ID.ID.ID
  65222. */
  65223. case TK_DOT: {
  65224. const char *zColumn;
  65225. const char *zTable;
  65226. const char *zDb;
  65227. Expr *pRight;
  65228. /* if( pSrcList==0 ) break; */
  65229. pRight = pExpr->pRight;
  65230. if( pRight->op==TK_ID ){
  65231. zDb = 0;
  65232. zTable = pExpr->pLeft->u.zToken;
  65233. zColumn = pRight->u.zToken;
  65234. }else{
  65235. assert( pRight->op==TK_DOT );
  65236. zDb = pExpr->pLeft->u.zToken;
  65237. zTable = pRight->pLeft->u.zToken;
  65238. zColumn = pRight->pRight->u.zToken;
  65239. }
  65240. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  65241. }
  65242. /* Resolve function names
  65243. */
  65244. case TK_CONST_FUNC:
  65245. case TK_FUNCTION: {
  65246. ExprList *pList = pExpr->x.pList; /* The argument list */
  65247. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  65248. int no_such_func = 0; /* True if no such function exists */
  65249. int wrong_num_args = 0; /* True if wrong number of arguments */
  65250. int is_agg = 0; /* True if is an aggregate function */
  65251. int auth; /* Authorization to use the function */
  65252. int nId; /* Number of characters in function name */
  65253. const char *zId; /* The function name. */
  65254. FuncDef *pDef; /* Information about the function */
  65255. u8 enc = ENC(pParse->db); /* The database encoding */
  65256. testcase( pExpr->op==TK_CONST_FUNC );
  65257. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  65258. zId = pExpr->u.zToken;
  65259. nId = sqlite3Strlen30(zId);
  65260. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  65261. if( pDef==0 ){
  65262. pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
  65263. if( pDef==0 ){
  65264. no_such_func = 1;
  65265. }else{
  65266. wrong_num_args = 1;
  65267. }
  65268. }else{
  65269. is_agg = pDef->xFunc==0;
  65270. }
  65271. #ifndef SQLITE_OMIT_AUTHORIZATION
  65272. if( pDef ){
  65273. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  65274. if( auth!=SQLITE_OK ){
  65275. if( auth==SQLITE_DENY ){
  65276. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  65277. pDef->zName);
  65278. pNC->nErr++;
  65279. }
  65280. pExpr->op = TK_NULL;
  65281. return WRC_Prune;
  65282. }
  65283. }
  65284. #endif
  65285. if( is_agg && !pNC->allowAgg ){
  65286. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  65287. pNC->nErr++;
  65288. is_agg = 0;
  65289. }else if( no_such_func ){
  65290. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  65291. pNC->nErr++;
  65292. }else if( wrong_num_args ){
  65293. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  65294. nId, zId);
  65295. pNC->nErr++;
  65296. }
  65297. if( is_agg ){
  65298. pExpr->op = TK_AGG_FUNCTION;
  65299. pNC->hasAgg = 1;
  65300. }
  65301. if( is_agg ) pNC->allowAgg = 0;
  65302. sqlite3WalkExprList(pWalker, pList);
  65303. if( is_agg ) pNC->allowAgg = 1;
  65304. /* FIX ME: Compute pExpr->affinity based on the expected return
  65305. ** type of the function
  65306. */
  65307. return WRC_Prune;
  65308. }
  65309. #ifndef SQLITE_OMIT_SUBQUERY
  65310. case TK_SELECT:
  65311. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  65312. #endif
  65313. case TK_IN: {
  65314. testcase( pExpr->op==TK_IN );
  65315. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  65316. int nRef = pNC->nRef;
  65317. #ifndef SQLITE_OMIT_CHECK
  65318. if( pNC->isCheck ){
  65319. sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
  65320. }
  65321. #endif
  65322. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  65323. assert( pNC->nRef>=nRef );
  65324. if( nRef!=pNC->nRef ){
  65325. ExprSetProperty(pExpr, EP_VarSelect);
  65326. }
  65327. }
  65328. break;
  65329. }
  65330. #ifndef SQLITE_OMIT_CHECK
  65331. case TK_VARIABLE: {
  65332. if( pNC->isCheck ){
  65333. sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
  65334. }
  65335. break;
  65336. }
  65337. #endif
  65338. }
  65339. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  65340. }
  65341. /*
  65342. ** pEList is a list of expressions which are really the result set of the
  65343. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  65344. ** This routine checks to see if pE is a simple identifier which corresponds
  65345. ** to the AS-name of one of the terms of the expression list. If it is,
  65346. ** this routine return an integer between 1 and N where N is the number of
  65347. ** elements in pEList, corresponding to the matching entry. If there is
  65348. ** no match, or if pE is not a simple identifier, then this routine
  65349. ** return 0.
  65350. **
  65351. ** pEList has been resolved. pE has not.
  65352. */
  65353. static int resolveAsName(
  65354. Parse *pParse, /* Parsing context for error messages */
  65355. ExprList *pEList, /* List of expressions to scan */
  65356. Expr *pE /* Expression we are trying to match */
  65357. ){
  65358. int i; /* Loop counter */
  65359. UNUSED_PARAMETER(pParse);
  65360. if( pE->op==TK_ID ){
  65361. char *zCol = pE->u.zToken;
  65362. for(i=0; i<pEList->nExpr; i++){
  65363. char *zAs = pEList->a[i].zName;
  65364. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  65365. return i+1;
  65366. }
  65367. }
  65368. }
  65369. return 0;
  65370. }
  65371. /*
  65372. ** pE is a pointer to an expression which is a single term in the
  65373. ** ORDER BY of a compound SELECT. The expression has not been
  65374. ** name resolved.
  65375. **
  65376. ** At the point this routine is called, we already know that the
  65377. ** ORDER BY term is not an integer index into the result set. That
  65378. ** case is handled by the calling routine.
  65379. **
  65380. ** Attempt to match pE against result set columns in the left-most
  65381. ** SELECT statement. Return the index i of the matching column,
  65382. ** as an indication to the caller that it should sort by the i-th column.
  65383. ** The left-most column is 1. In other words, the value returned is the
  65384. ** same integer value that would be used in the SQL statement to indicate
  65385. ** the column.
  65386. **
  65387. ** If there is no match, return 0. Return -1 if an error occurs.
  65388. */
  65389. static int resolveOrderByTermToExprList(
  65390. Parse *pParse, /* Parsing context for error messages */
  65391. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  65392. Expr *pE /* The specific ORDER BY term */
  65393. ){
  65394. int i; /* Loop counter */
  65395. ExprList *pEList; /* The columns of the result set */
  65396. NameContext nc; /* Name context for resolving pE */
  65397. sqlite3 *db; /* Database connection */
  65398. int rc; /* Return code from subprocedures */
  65399. u8 savedSuppErr; /* Saved value of db->suppressErr */
  65400. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  65401. pEList = pSelect->pEList;
  65402. /* Resolve all names in the ORDER BY term expression
  65403. */
  65404. memset(&nc, 0, sizeof(nc));
  65405. nc.pParse = pParse;
  65406. nc.pSrcList = pSelect->pSrc;
  65407. nc.pEList = pEList;
  65408. nc.allowAgg = 1;
  65409. nc.nErr = 0;
  65410. db = pParse->db;
  65411. savedSuppErr = db->suppressErr;
  65412. db->suppressErr = 1;
  65413. rc = sqlite3ResolveExprNames(&nc, pE);
  65414. db->suppressErr = savedSuppErr;
  65415. if( rc ) return 0;
  65416. /* Try to match the ORDER BY expression against an expression
  65417. ** in the result set. Return an 1-based index of the matching
  65418. ** result-set entry.
  65419. */
  65420. for(i=0; i<pEList->nExpr; i++){
  65421. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
  65422. return i+1;
  65423. }
  65424. }
  65425. /* If no match, return 0. */
  65426. return 0;
  65427. }
  65428. /*
  65429. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  65430. */
  65431. static void resolveOutOfRangeError(
  65432. Parse *pParse, /* The error context into which to write the error */
  65433. const char *zType, /* "ORDER" or "GROUP" */
  65434. int i, /* The index (1-based) of the term out of range */
  65435. int mx /* Largest permissible value of i */
  65436. ){
  65437. sqlite3ErrorMsg(pParse,
  65438. "%r %s BY term out of range - should be "
  65439. "between 1 and %d", i, zType, mx);
  65440. }
  65441. /*
  65442. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  65443. ** each term of the ORDER BY clause is a constant integer between 1
  65444. ** and N where N is the number of columns in the compound SELECT.
  65445. **
  65446. ** ORDER BY terms that are already an integer between 1 and N are
  65447. ** unmodified. ORDER BY terms that are integers outside the range of
  65448. ** 1 through N generate an error. ORDER BY terms that are expressions
  65449. ** are matched against result set expressions of compound SELECT
  65450. ** beginning with the left-most SELECT and working toward the right.
  65451. ** At the first match, the ORDER BY expression is transformed into
  65452. ** the integer column number.
  65453. **
  65454. ** Return the number of errors seen.
  65455. */
  65456. static int resolveCompoundOrderBy(
  65457. Parse *pParse, /* Parsing context. Leave error messages here */
  65458. Select *pSelect /* The SELECT statement containing the ORDER BY */
  65459. ){
  65460. int i;
  65461. ExprList *pOrderBy;
  65462. ExprList *pEList;
  65463. sqlite3 *db;
  65464. int moreToDo = 1;
  65465. pOrderBy = pSelect->pOrderBy;
  65466. if( pOrderBy==0 ) return 0;
  65467. db = pParse->db;
  65468. #if SQLITE_MAX_COLUMN
  65469. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  65470. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  65471. return 1;
  65472. }
  65473. #endif
  65474. for(i=0; i<pOrderBy->nExpr; i++){
  65475. pOrderBy->a[i].done = 0;
  65476. }
  65477. pSelect->pNext = 0;
  65478. while( pSelect->pPrior ){
  65479. pSelect->pPrior->pNext = pSelect;
  65480. pSelect = pSelect->pPrior;
  65481. }
  65482. while( pSelect && moreToDo ){
  65483. struct ExprList_item *pItem;
  65484. moreToDo = 0;
  65485. pEList = pSelect->pEList;
  65486. assert( pEList!=0 );
  65487. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  65488. int iCol = -1;
  65489. Expr *pE, *pDup;
  65490. if( pItem->done ) continue;
  65491. pE = pItem->pExpr;
  65492. if( sqlite3ExprIsInteger(pE, &iCol) ){
  65493. if( iCol<=0 || iCol>pEList->nExpr ){
  65494. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  65495. return 1;
  65496. }
  65497. }else{
  65498. iCol = resolveAsName(pParse, pEList, pE);
  65499. if( iCol==0 ){
  65500. pDup = sqlite3ExprDup(db, pE, 0);
  65501. if( !db->mallocFailed ){
  65502. assert(pDup);
  65503. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  65504. }
  65505. sqlite3ExprDelete(db, pDup);
  65506. }
  65507. }
  65508. if( iCol>0 ){
  65509. CollSeq *pColl = pE->pColl;
  65510. int flags = pE->flags & EP_ExpCollate;
  65511. sqlite3ExprDelete(db, pE);
  65512. pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
  65513. if( pE==0 ) return 1;
  65514. pE->pColl = pColl;
  65515. pE->flags |= EP_IntValue | flags;
  65516. pE->u.iValue = iCol;
  65517. pItem->iCol = (u16)iCol;
  65518. pItem->done = 1;
  65519. }else{
  65520. moreToDo = 1;
  65521. }
  65522. }
  65523. pSelect = pSelect->pNext;
  65524. }
  65525. for(i=0; i<pOrderBy->nExpr; i++){
  65526. if( pOrderBy->a[i].done==0 ){
  65527. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  65528. "column in the result set", i+1);
  65529. return 1;
  65530. }
  65531. }
  65532. return 0;
  65533. }
  65534. /*
  65535. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  65536. ** the SELECT statement pSelect. If any term is reference to a
  65537. ** result set expression (as determined by the ExprList.a.iCol field)
  65538. ** then convert that term into a copy of the corresponding result set
  65539. ** column.
  65540. **
  65541. ** If any errors are detected, add an error message to pParse and
  65542. ** return non-zero. Return zero if no errors are seen.
  65543. */
  65544. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  65545. Parse *pParse, /* Parsing context. Leave error messages here */
  65546. Select *pSelect, /* The SELECT statement containing the clause */
  65547. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  65548. const char *zType /* "ORDER" or "GROUP" */
  65549. ){
  65550. int i;
  65551. sqlite3 *db = pParse->db;
  65552. ExprList *pEList;
  65553. struct ExprList_item *pItem;
  65554. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  65555. #if SQLITE_MAX_COLUMN
  65556. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  65557. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  65558. return 1;
  65559. }
  65560. #endif
  65561. pEList = pSelect->pEList;
  65562. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  65563. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  65564. if( pItem->iCol ){
  65565. if( pItem->iCol>pEList->nExpr ){
  65566. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  65567. return 1;
  65568. }
  65569. resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
  65570. }
  65571. }
  65572. return 0;
  65573. }
  65574. /*
  65575. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  65576. ** The Name context of the SELECT statement is pNC. zType is either
  65577. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  65578. **
  65579. ** This routine resolves each term of the clause into an expression.
  65580. ** If the order-by term is an integer I between 1 and N (where N is the
  65581. ** number of columns in the result set of the SELECT) then the expression
  65582. ** in the resolution is a copy of the I-th result-set expression. If
  65583. ** the order-by term is an identify that corresponds to the AS-name of
  65584. ** a result-set expression, then the term resolves to a copy of the
  65585. ** result-set expression. Otherwise, the expression is resolved in
  65586. ** the usual way - using sqlite3ResolveExprNames().
  65587. **
  65588. ** This routine returns the number of errors. If errors occur, then
  65589. ** an appropriate error message might be left in pParse. (OOM errors
  65590. ** excepted.)
  65591. */
  65592. static int resolveOrderGroupBy(
  65593. NameContext *pNC, /* The name context of the SELECT statement */
  65594. Select *pSelect, /* The SELECT statement holding pOrderBy */
  65595. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  65596. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  65597. ){
  65598. int i; /* Loop counter */
  65599. int iCol; /* Column number */
  65600. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  65601. Parse *pParse; /* Parsing context */
  65602. int nResult; /* Number of terms in the result set */
  65603. if( pOrderBy==0 ) return 0;
  65604. nResult = pSelect->pEList->nExpr;
  65605. pParse = pNC->pParse;
  65606. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  65607. Expr *pE = pItem->pExpr;
  65608. iCol = resolveAsName(pParse, pSelect->pEList, pE);
  65609. if( iCol>0 ){
  65610. /* If an AS-name match is found, mark this ORDER BY column as being
  65611. ** a copy of the iCol-th result-set column. The subsequent call to
  65612. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  65613. ** copy of the iCol-th result-set expression. */
  65614. pItem->iCol = (u16)iCol;
  65615. continue;
  65616. }
  65617. if( sqlite3ExprIsInteger(pE, &iCol) ){
  65618. /* The ORDER BY term is an integer constant. Again, set the column
  65619. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  65620. ** order-by term to a copy of the result-set expression */
  65621. if( iCol<1 ){
  65622. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  65623. return 1;
  65624. }
  65625. pItem->iCol = (u16)iCol;
  65626. continue;
  65627. }
  65628. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  65629. pItem->iCol = 0;
  65630. if( sqlite3ResolveExprNames(pNC, pE) ){
  65631. return 1;
  65632. }
  65633. }
  65634. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  65635. }
  65636. /*
  65637. ** Resolve names in the SELECT statement p and all of its descendents.
  65638. */
  65639. static int resolveSelectStep(Walker *pWalker, Select *p){
  65640. NameContext *pOuterNC; /* Context that contains this SELECT */
  65641. NameContext sNC; /* Name context of this SELECT */
  65642. int isCompound; /* True if p is a compound select */
  65643. int nCompound; /* Number of compound terms processed so far */
  65644. Parse *pParse; /* Parsing context */
  65645. ExprList *pEList; /* Result set expression list */
  65646. int i; /* Loop counter */
  65647. ExprList *pGroupBy; /* The GROUP BY clause */
  65648. Select *pLeftmost; /* Left-most of SELECT of a compound */
  65649. sqlite3 *db; /* Database connection */
  65650. assert( p!=0 );
  65651. if( p->selFlags & SF_Resolved ){
  65652. return WRC_Prune;
  65653. }
  65654. pOuterNC = pWalker->u.pNC;
  65655. pParse = pWalker->pParse;
  65656. db = pParse->db;
  65657. /* Normally sqlite3SelectExpand() will be called first and will have
  65658. ** already expanded this SELECT. However, if this is a subquery within
  65659. ** an expression, sqlite3ResolveExprNames() will be called without a
  65660. ** prior call to sqlite3SelectExpand(). When that happens, let
  65661. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  65662. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  65663. ** this routine in the correct order.
  65664. */
  65665. if( (p->selFlags & SF_Expanded)==0 ){
  65666. sqlite3SelectPrep(pParse, p, pOuterNC);
  65667. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  65668. }
  65669. isCompound = p->pPrior!=0;
  65670. nCompound = 0;
  65671. pLeftmost = p;
  65672. while( p ){
  65673. assert( (p->selFlags & SF_Expanded)!=0 );
  65674. assert( (p->selFlags & SF_Resolved)==0 );
  65675. p->selFlags |= SF_Resolved;
  65676. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  65677. ** are not allowed to refer to any names, so pass an empty NameContext.
  65678. */
  65679. memset(&sNC, 0, sizeof(sNC));
  65680. sNC.pParse = pParse;
  65681. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  65682. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  65683. return WRC_Abort;
  65684. }
  65685. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  65686. ** resolve the result-set expression list.
  65687. */
  65688. sNC.allowAgg = 1;
  65689. sNC.pSrcList = p->pSrc;
  65690. sNC.pNext = pOuterNC;
  65691. /* Resolve names in the result set. */
  65692. pEList = p->pEList;
  65693. assert( pEList!=0 );
  65694. for(i=0; i<pEList->nExpr; i++){
  65695. Expr *pX = pEList->a[i].pExpr;
  65696. if( sqlite3ResolveExprNames(&sNC, pX) ){
  65697. return WRC_Abort;
  65698. }
  65699. }
  65700. /* Recursively resolve names in all subqueries
  65701. */
  65702. for(i=0; i<p->pSrc->nSrc; i++){
  65703. struct SrcList_item *pItem = &p->pSrc->a[i];
  65704. if( pItem->pSelect ){
  65705. const char *zSavedContext = pParse->zAuthContext;
  65706. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  65707. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  65708. pParse->zAuthContext = zSavedContext;
  65709. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  65710. }
  65711. }
  65712. /* If there are no aggregate functions in the result-set, and no GROUP BY
  65713. ** expression, do not allow aggregates in any of the other expressions.
  65714. */
  65715. assert( (p->selFlags & SF_Aggregate)==0 );
  65716. pGroupBy = p->pGroupBy;
  65717. if( pGroupBy || sNC.hasAgg ){
  65718. p->selFlags |= SF_Aggregate;
  65719. }else{
  65720. sNC.allowAgg = 0;
  65721. }
  65722. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  65723. */
  65724. if( p->pHaving && !pGroupBy ){
  65725. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  65726. return WRC_Abort;
  65727. }
  65728. /* Add the expression list to the name-context before parsing the
  65729. ** other expressions in the SELECT statement. This is so that
  65730. ** expressions in the WHERE clause (etc.) can refer to expressions by
  65731. ** aliases in the result set.
  65732. **
  65733. ** Minor point: If this is the case, then the expression will be
  65734. ** re-evaluated for each reference to it.
  65735. */
  65736. sNC.pEList = p->pEList;
  65737. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
  65738. sqlite3ResolveExprNames(&sNC, p->pHaving)
  65739. ){
  65740. return WRC_Abort;
  65741. }
  65742. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  65743. ** outer queries
  65744. */
  65745. sNC.pNext = 0;
  65746. sNC.allowAgg = 1;
  65747. /* Process the ORDER BY clause for singleton SELECT statements.
  65748. ** The ORDER BY clause for compounds SELECT statements is handled
  65749. ** below, after all of the result-sets for all of the elements of
  65750. ** the compound have been resolved.
  65751. */
  65752. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  65753. return WRC_Abort;
  65754. }
  65755. if( db->mallocFailed ){
  65756. return WRC_Abort;
  65757. }
  65758. /* Resolve the GROUP BY clause. At the same time, make sure
  65759. ** the GROUP BY clause does not contain aggregate functions.
  65760. */
  65761. if( pGroupBy ){
  65762. struct ExprList_item *pItem;
  65763. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  65764. return WRC_Abort;
  65765. }
  65766. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  65767. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  65768. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  65769. "the GROUP BY clause");
  65770. return WRC_Abort;
  65771. }
  65772. }
  65773. }
  65774. /* Advance to the next term of the compound
  65775. */
  65776. p = p->pPrior;
  65777. nCompound++;
  65778. }
  65779. /* Resolve the ORDER BY on a compound SELECT after all terms of
  65780. ** the compound have been resolved.
  65781. */
  65782. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  65783. return WRC_Abort;
  65784. }
  65785. return WRC_Prune;
  65786. }
  65787. /*
  65788. ** This routine walks an expression tree and resolves references to
  65789. ** table columns and result-set columns. At the same time, do error
  65790. ** checking on function usage and set a flag if any aggregate functions
  65791. ** are seen.
  65792. **
  65793. ** To resolve table columns references we look for nodes (or subtrees) of the
  65794. ** form X.Y.Z or Y.Z or just Z where
  65795. **
  65796. ** X: The name of a database. Ex: "main" or "temp" or
  65797. ** the symbolic name assigned to an ATTACH-ed database.
  65798. **
  65799. ** Y: The name of a table in a FROM clause. Or in a trigger
  65800. ** one of the special names "old" or "new".
  65801. **
  65802. ** Z: The name of a column in table Y.
  65803. **
  65804. ** The node at the root of the subtree is modified as follows:
  65805. **
  65806. ** Expr.op Changed to TK_COLUMN
  65807. ** Expr.pTab Points to the Table object for X.Y
  65808. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  65809. ** Expr.iTable The VDBE cursor number for X.Y
  65810. **
  65811. **
  65812. ** To resolve result-set references, look for expression nodes of the
  65813. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  65814. ** size of an AS clause in the result-set of a SELECT. The Z expression
  65815. ** is replaced by a copy of the left-hand side of the result-set expression.
  65816. ** Table-name and function resolution occurs on the substituted expression
  65817. ** tree. For example, in:
  65818. **
  65819. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  65820. **
  65821. ** The "x" term of the order by is replaced by "a+b" to render:
  65822. **
  65823. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  65824. **
  65825. ** Function calls are checked to make sure that the function is
  65826. ** defined and that the correct number of arguments are specified.
  65827. ** If the function is an aggregate function, then the pNC->hasAgg is
  65828. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  65829. ** If an expression contains aggregate functions then the EP_Agg
  65830. ** property on the expression is set.
  65831. **
  65832. ** An error message is left in pParse if anything is amiss. The number
  65833. ** if errors is returned.
  65834. */
  65835. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  65836. NameContext *pNC, /* Namespace to resolve expressions in. */
  65837. Expr *pExpr /* The expression to be analyzed. */
  65838. ){
  65839. int savedHasAgg;
  65840. Walker w;
  65841. if( pExpr==0 ) return 0;
  65842. #if SQLITE_MAX_EXPR_DEPTH>0
  65843. {
  65844. Parse *pParse = pNC->pParse;
  65845. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  65846. return 1;
  65847. }
  65848. pParse->nHeight += pExpr->nHeight;
  65849. }
  65850. #endif
  65851. savedHasAgg = pNC->hasAgg;
  65852. pNC->hasAgg = 0;
  65853. w.xExprCallback = resolveExprStep;
  65854. w.xSelectCallback = resolveSelectStep;
  65855. w.pParse = pNC->pParse;
  65856. w.u.pNC = pNC;
  65857. sqlite3WalkExpr(&w, pExpr);
  65858. #if SQLITE_MAX_EXPR_DEPTH>0
  65859. pNC->pParse->nHeight -= pExpr->nHeight;
  65860. #endif
  65861. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  65862. ExprSetProperty(pExpr, EP_Error);
  65863. }
  65864. if( pNC->hasAgg ){
  65865. ExprSetProperty(pExpr, EP_Agg);
  65866. }else if( savedHasAgg ){
  65867. pNC->hasAgg = 1;
  65868. }
  65869. return ExprHasProperty(pExpr, EP_Error);
  65870. }
  65871. /*
  65872. ** Resolve all names in all expressions of a SELECT and in all
  65873. ** decendents of the SELECT, including compounds off of p->pPrior,
  65874. ** subqueries in expressions, and subqueries used as FROM clause
  65875. ** terms.
  65876. **
  65877. ** See sqlite3ResolveExprNames() for a description of the kinds of
  65878. ** transformations that occur.
  65879. **
  65880. ** All SELECT statements should have been expanded using
  65881. ** sqlite3SelectExpand() prior to invoking this routine.
  65882. */
  65883. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  65884. Parse *pParse, /* The parser context */
  65885. Select *p, /* The SELECT statement being coded. */
  65886. NameContext *pOuterNC /* Name context for parent SELECT statement */
  65887. ){
  65888. Walker w;
  65889. assert( p!=0 );
  65890. w.xExprCallback = resolveExprStep;
  65891. w.xSelectCallback = resolveSelectStep;
  65892. w.pParse = pParse;
  65893. w.u.pNC = pOuterNC;
  65894. sqlite3WalkSelect(&w, p);
  65895. }
  65896. /************** End of resolve.c *********************************************/
  65897. /************** Begin file expr.c ********************************************/
  65898. /*
  65899. ** 2001 September 15
  65900. **
  65901. ** The author disclaims copyright to this source code. In place of
  65902. ** a legal notice, here is a blessing:
  65903. **
  65904. ** May you do good and not evil.
  65905. ** May you find forgiveness for yourself and forgive others.
  65906. ** May you share freely, never taking more than you give.
  65907. **
  65908. *************************************************************************
  65909. ** This file contains routines used for analyzing expressions and
  65910. ** for generating VDBE code that evaluates expressions in SQLite.
  65911. */
  65912. /*
  65913. ** Return the 'affinity' of the expression pExpr if any.
  65914. **
  65915. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  65916. ** or a sub-select with a column as the return value, then the
  65917. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  65918. ** indicating no affinity for the expression.
  65919. **
  65920. ** i.e. the WHERE clause expresssions in the following statements all
  65921. ** have an affinity:
  65922. **
  65923. ** CREATE TABLE t1(a);
  65924. ** SELECT * FROM t1 WHERE a;
  65925. ** SELECT a AS b FROM t1 WHERE b;
  65926. ** SELECT * FROM t1 WHERE (select a from t1);
  65927. */
  65928. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  65929. int op = pExpr->op;
  65930. if( op==TK_SELECT ){
  65931. assert( pExpr->flags&EP_xIsSelect );
  65932. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  65933. }
  65934. #ifndef SQLITE_OMIT_CAST
  65935. if( op==TK_CAST ){
  65936. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  65937. return sqlite3AffinityType(pExpr->u.zToken);
  65938. }
  65939. #endif
  65940. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  65941. && pExpr->pTab!=0
  65942. ){
  65943. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  65944. ** a TK_COLUMN but was previously evaluated and cached in a register */
  65945. int j = pExpr->iColumn;
  65946. if( j<0 ) return SQLITE_AFF_INTEGER;
  65947. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  65948. return pExpr->pTab->aCol[j].affinity;
  65949. }
  65950. return pExpr->affinity;
  65951. }
  65952. /*
  65953. ** Set the explicit collating sequence for an expression to the
  65954. ** collating sequence supplied in the second argument.
  65955. */
  65956. SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
  65957. if( pExpr && pColl ){
  65958. pExpr->pColl = pColl;
  65959. pExpr->flags |= EP_ExpCollate;
  65960. }
  65961. return pExpr;
  65962. }
  65963. /*
  65964. ** Set the collating sequence for expression pExpr to be the collating
  65965. ** sequence named by pToken. Return a pointer to the revised expression.
  65966. ** The collating sequence is marked as "explicit" using the EP_ExpCollate
  65967. ** flag. An explicit collating sequence will override implicit
  65968. ** collating sequences.
  65969. */
  65970. SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  65971. char *zColl = 0; /* Dequoted name of collation sequence */
  65972. CollSeq *pColl;
  65973. sqlite3 *db = pParse->db;
  65974. zColl = sqlite3NameFromToken(db, pCollName);
  65975. pColl = sqlite3LocateCollSeq(pParse, zColl);
  65976. sqlite3ExprSetColl(pExpr, pColl);
  65977. sqlite3DbFree(db, zColl);
  65978. return pExpr;
  65979. }
  65980. /*
  65981. ** Return the default collation sequence for the expression pExpr. If
  65982. ** there is no default collation type, return 0.
  65983. */
  65984. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  65985. CollSeq *pColl = 0;
  65986. Expr *p = pExpr;
  65987. while( p ){
  65988. int op;
  65989. pColl = p->pColl;
  65990. if( pColl ) break;
  65991. op = p->op;
  65992. if( p->pTab!=0 && (
  65993. op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
  65994. )){
  65995. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  65996. ** a TK_COLUMN but was previously evaluated and cached in a register */
  65997. const char *zColl;
  65998. int j = p->iColumn;
  65999. if( j>=0 ){
  66000. sqlite3 *db = pParse->db;
  66001. zColl = p->pTab->aCol[j].zColl;
  66002. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  66003. pExpr->pColl = pColl;
  66004. }
  66005. break;
  66006. }
  66007. if( op!=TK_CAST && op!=TK_UPLUS ){
  66008. break;
  66009. }
  66010. p = p->pLeft;
  66011. }
  66012. if( sqlite3CheckCollSeq(pParse, pColl) ){
  66013. pColl = 0;
  66014. }
  66015. return pColl;
  66016. }
  66017. /*
  66018. ** pExpr is an operand of a comparison operator. aff2 is the
  66019. ** type affinity of the other operand. This routine returns the
  66020. ** type affinity that should be used for the comparison operator.
  66021. */
  66022. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  66023. char aff1 = sqlite3ExprAffinity(pExpr);
  66024. if( aff1 && aff2 ){
  66025. /* Both sides of the comparison are columns. If one has numeric
  66026. ** affinity, use that. Otherwise use no affinity.
  66027. */
  66028. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  66029. return SQLITE_AFF_NUMERIC;
  66030. }else{
  66031. return SQLITE_AFF_NONE;
  66032. }
  66033. }else if( !aff1 && !aff2 ){
  66034. /* Neither side of the comparison is a column. Compare the
  66035. ** results directly.
  66036. */
  66037. return SQLITE_AFF_NONE;
  66038. }else{
  66039. /* One side is a column, the other is not. Use the columns affinity. */
  66040. assert( aff1==0 || aff2==0 );
  66041. return (aff1 + aff2);
  66042. }
  66043. }
  66044. /*
  66045. ** pExpr is a comparison operator. Return the type affinity that should
  66046. ** be applied to both operands prior to doing the comparison.
  66047. */
  66048. static char comparisonAffinity(Expr *pExpr){
  66049. char aff;
  66050. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  66051. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  66052. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  66053. assert( pExpr->pLeft );
  66054. aff = sqlite3ExprAffinity(pExpr->pLeft);
  66055. if( pExpr->pRight ){
  66056. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  66057. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  66058. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  66059. }else if( !aff ){
  66060. aff = SQLITE_AFF_NONE;
  66061. }
  66062. return aff;
  66063. }
  66064. /*
  66065. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  66066. ** idx_affinity is the affinity of an indexed column. Return true
  66067. ** if the index with affinity idx_affinity may be used to implement
  66068. ** the comparison in pExpr.
  66069. */
  66070. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  66071. char aff = comparisonAffinity(pExpr);
  66072. switch( aff ){
  66073. case SQLITE_AFF_NONE:
  66074. return 1;
  66075. case SQLITE_AFF_TEXT:
  66076. return idx_affinity==SQLITE_AFF_TEXT;
  66077. default:
  66078. return sqlite3IsNumericAffinity(idx_affinity);
  66079. }
  66080. }
  66081. /*
  66082. ** Return the P5 value that should be used for a binary comparison
  66083. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  66084. */
  66085. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  66086. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  66087. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  66088. return aff;
  66089. }
  66090. /*
  66091. ** Return a pointer to the collation sequence that should be used by
  66092. ** a binary comparison operator comparing pLeft and pRight.
  66093. **
  66094. ** If the left hand expression has a collating sequence type, then it is
  66095. ** used. Otherwise the collation sequence for the right hand expression
  66096. ** is used, or the default (BINARY) if neither expression has a collating
  66097. ** type.
  66098. **
  66099. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  66100. ** it is not considered.
  66101. */
  66102. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  66103. Parse *pParse,
  66104. Expr *pLeft,
  66105. Expr *pRight
  66106. ){
  66107. CollSeq *pColl;
  66108. assert( pLeft );
  66109. if( pLeft->flags & EP_ExpCollate ){
  66110. assert( pLeft->pColl );
  66111. pColl = pLeft->pColl;
  66112. }else if( pRight && pRight->flags & EP_ExpCollate ){
  66113. assert( pRight->pColl );
  66114. pColl = pRight->pColl;
  66115. }else{
  66116. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  66117. if( !pColl ){
  66118. pColl = sqlite3ExprCollSeq(pParse, pRight);
  66119. }
  66120. }
  66121. return pColl;
  66122. }
  66123. /*
  66124. ** Generate code for a comparison operator.
  66125. */
  66126. static int codeCompare(
  66127. Parse *pParse, /* The parsing (and code generating) context */
  66128. Expr *pLeft, /* The left operand */
  66129. Expr *pRight, /* The right operand */
  66130. int opcode, /* The comparison opcode */
  66131. int in1, int in2, /* Register holding operands */
  66132. int dest, /* Jump here if true. */
  66133. int jumpIfNull /* If true, jump if either operand is NULL */
  66134. ){
  66135. int p5;
  66136. int addr;
  66137. CollSeq *p4;
  66138. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  66139. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  66140. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  66141. (void*)p4, P4_COLLSEQ);
  66142. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  66143. return addr;
  66144. }
  66145. #if SQLITE_MAX_EXPR_DEPTH>0
  66146. /*
  66147. ** Check that argument nHeight is less than or equal to the maximum
  66148. ** expression depth allowed. If it is not, leave an error message in
  66149. ** pParse.
  66150. */
  66151. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  66152. int rc = SQLITE_OK;
  66153. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  66154. if( nHeight>mxHeight ){
  66155. sqlite3ErrorMsg(pParse,
  66156. "Expression tree is too large (maximum depth %d)", mxHeight
  66157. );
  66158. rc = SQLITE_ERROR;
  66159. }
  66160. return rc;
  66161. }
  66162. /* The following three functions, heightOfExpr(), heightOfExprList()
  66163. ** and heightOfSelect(), are used to determine the maximum height
  66164. ** of any expression tree referenced by the structure passed as the
  66165. ** first argument.
  66166. **
  66167. ** If this maximum height is greater than the current value pointed
  66168. ** to by pnHeight, the second parameter, then set *pnHeight to that
  66169. ** value.
  66170. */
  66171. static void heightOfExpr(Expr *p, int *pnHeight){
  66172. if( p ){
  66173. if( p->nHeight>*pnHeight ){
  66174. *pnHeight = p->nHeight;
  66175. }
  66176. }
  66177. }
  66178. static void heightOfExprList(ExprList *p, int *pnHeight){
  66179. if( p ){
  66180. int i;
  66181. for(i=0; i<p->nExpr; i++){
  66182. heightOfExpr(p->a[i].pExpr, pnHeight);
  66183. }
  66184. }
  66185. }
  66186. static void heightOfSelect(Select *p, int *pnHeight){
  66187. if( p ){
  66188. heightOfExpr(p->pWhere, pnHeight);
  66189. heightOfExpr(p->pHaving, pnHeight);
  66190. heightOfExpr(p->pLimit, pnHeight);
  66191. heightOfExpr(p->pOffset, pnHeight);
  66192. heightOfExprList(p->pEList, pnHeight);
  66193. heightOfExprList(p->pGroupBy, pnHeight);
  66194. heightOfExprList(p->pOrderBy, pnHeight);
  66195. heightOfSelect(p->pPrior, pnHeight);
  66196. }
  66197. }
  66198. /*
  66199. ** Set the Expr.nHeight variable in the structure passed as an
  66200. ** argument. An expression with no children, Expr.pList or
  66201. ** Expr.pSelect member has a height of 1. Any other expression
  66202. ** has a height equal to the maximum height of any other
  66203. ** referenced Expr plus one.
  66204. */
  66205. static void exprSetHeight(Expr *p){
  66206. int nHeight = 0;
  66207. heightOfExpr(p->pLeft, &nHeight);
  66208. heightOfExpr(p->pRight, &nHeight);
  66209. if( ExprHasProperty(p, EP_xIsSelect) ){
  66210. heightOfSelect(p->x.pSelect, &nHeight);
  66211. }else{
  66212. heightOfExprList(p->x.pList, &nHeight);
  66213. }
  66214. p->nHeight = nHeight + 1;
  66215. }
  66216. /*
  66217. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  66218. ** the height is greater than the maximum allowed expression depth,
  66219. ** leave an error in pParse.
  66220. */
  66221. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  66222. exprSetHeight(p);
  66223. sqlite3ExprCheckHeight(pParse, p->nHeight);
  66224. }
  66225. /*
  66226. ** Return the maximum height of any expression tree referenced
  66227. ** by the select statement passed as an argument.
  66228. */
  66229. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  66230. int nHeight = 0;
  66231. heightOfSelect(p, &nHeight);
  66232. return nHeight;
  66233. }
  66234. #else
  66235. #define exprSetHeight(y)
  66236. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  66237. /*
  66238. ** This routine is the core allocator for Expr nodes.
  66239. **
  66240. ** Construct a new expression node and return a pointer to it. Memory
  66241. ** for this node and for the pToken argument is a single allocation
  66242. ** obtained from sqlite3DbMalloc(). The calling function
  66243. ** is responsible for making sure the node eventually gets freed.
  66244. **
  66245. ** If dequote is true, then the token (if it exists) is dequoted.
  66246. ** If dequote is false, no dequoting is performance. The deQuote
  66247. ** parameter is ignored if pToken is NULL or if the token does not
  66248. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  66249. ** then the EP_DblQuoted flag is set on the expression node.
  66250. **
  66251. ** Special case: If op==TK_INTEGER and pToken points to a string that
  66252. ** can be translated into a 32-bit integer, then the token is not
  66253. ** stored in u.zToken. Instead, the integer values is written
  66254. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  66255. ** is allocated to hold the integer text and the dequote flag is ignored.
  66256. */
  66257. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  66258. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  66259. int op, /* Expression opcode */
  66260. const Token *pToken, /* Token argument. Might be NULL */
  66261. int dequote /* True to dequote */
  66262. ){
  66263. Expr *pNew;
  66264. int nExtra = 0;
  66265. int iValue = 0;
  66266. if( pToken ){
  66267. if( op!=TK_INTEGER || pToken->z==0
  66268. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  66269. nExtra = pToken->n+1;
  66270. assert( iValue>=0 );
  66271. }
  66272. }
  66273. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  66274. if( pNew ){
  66275. pNew->op = (u8)op;
  66276. pNew->iAgg = -1;
  66277. if( pToken ){
  66278. if( nExtra==0 ){
  66279. pNew->flags |= EP_IntValue;
  66280. pNew->u.iValue = iValue;
  66281. }else{
  66282. int c;
  66283. pNew->u.zToken = (char*)&pNew[1];
  66284. memcpy(pNew->u.zToken, pToken->z, pToken->n);
  66285. pNew->u.zToken[pToken->n] = 0;
  66286. if( dequote && nExtra>=3
  66287. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  66288. sqlite3Dequote(pNew->u.zToken);
  66289. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  66290. }
  66291. }
  66292. }
  66293. #if SQLITE_MAX_EXPR_DEPTH>0
  66294. pNew->nHeight = 1;
  66295. #endif
  66296. }
  66297. return pNew;
  66298. }
  66299. /*
  66300. ** Allocate a new expression node from a zero-terminated token that has
  66301. ** already been dequoted.
  66302. */
  66303. SQLITE_PRIVATE Expr *sqlite3Expr(
  66304. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  66305. int op, /* Expression opcode */
  66306. const char *zToken /* Token argument. Might be NULL */
  66307. ){
  66308. Token x;
  66309. x.z = zToken;
  66310. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  66311. return sqlite3ExprAlloc(db, op, &x, 0);
  66312. }
  66313. /*
  66314. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  66315. **
  66316. ** If pRoot==NULL that means that a memory allocation error has occurred.
  66317. ** In that case, delete the subtrees pLeft and pRight.
  66318. */
  66319. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  66320. sqlite3 *db,
  66321. Expr *pRoot,
  66322. Expr *pLeft,
  66323. Expr *pRight
  66324. ){
  66325. if( pRoot==0 ){
  66326. assert( db->mallocFailed );
  66327. sqlite3ExprDelete(db, pLeft);
  66328. sqlite3ExprDelete(db, pRight);
  66329. }else{
  66330. if( pRight ){
  66331. pRoot->pRight = pRight;
  66332. if( pRight->flags & EP_ExpCollate ){
  66333. pRoot->flags |= EP_ExpCollate;
  66334. pRoot->pColl = pRight->pColl;
  66335. }
  66336. }
  66337. if( pLeft ){
  66338. pRoot->pLeft = pLeft;
  66339. if( pLeft->flags & EP_ExpCollate ){
  66340. pRoot->flags |= EP_ExpCollate;
  66341. pRoot->pColl = pLeft->pColl;
  66342. }
  66343. }
  66344. exprSetHeight(pRoot);
  66345. }
  66346. }
  66347. /*
  66348. ** Allocate a Expr node which joins as many as two subtrees.
  66349. **
  66350. ** One or both of the subtrees can be NULL. Return a pointer to the new
  66351. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  66352. ** free the subtrees and return NULL.
  66353. */
  66354. SQLITE_PRIVATE Expr *sqlite3PExpr(
  66355. Parse *pParse, /* Parsing context */
  66356. int op, /* Expression opcode */
  66357. Expr *pLeft, /* Left operand */
  66358. Expr *pRight, /* Right operand */
  66359. const Token *pToken /* Argument token */
  66360. ){
  66361. Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  66362. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  66363. if( p ) {
  66364. sqlite3ExprCheckHeight(pParse, p->nHeight);
  66365. }
  66366. return p;
  66367. }
  66368. /*
  66369. ** Join two expressions using an AND operator. If either expression is
  66370. ** NULL, then just return the other expression.
  66371. */
  66372. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  66373. if( pLeft==0 ){
  66374. return pRight;
  66375. }else if( pRight==0 ){
  66376. return pLeft;
  66377. }else{
  66378. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  66379. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  66380. return pNew;
  66381. }
  66382. }
  66383. /*
  66384. ** Construct a new expression node for a function with multiple
  66385. ** arguments.
  66386. */
  66387. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  66388. Expr *pNew;
  66389. sqlite3 *db = pParse->db;
  66390. assert( pToken );
  66391. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  66392. if( pNew==0 ){
  66393. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  66394. return 0;
  66395. }
  66396. pNew->x.pList = pList;
  66397. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  66398. sqlite3ExprSetHeight(pParse, pNew);
  66399. return pNew;
  66400. }
  66401. /*
  66402. ** Assign a variable number to an expression that encodes a wildcard
  66403. ** in the original SQL statement.
  66404. **
  66405. ** Wildcards consisting of a single "?" are assigned the next sequential
  66406. ** variable number.
  66407. **
  66408. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  66409. ** sure "nnn" is not too be to avoid a denial of service attack when
  66410. ** the SQL statement comes from an external source.
  66411. **
  66412. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  66413. ** as the previous instance of the same wildcard. Or if this is the first
  66414. ** instance of the wildcard, the next sequenial variable number is
  66415. ** assigned.
  66416. */
  66417. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  66418. sqlite3 *db = pParse->db;
  66419. const char *z;
  66420. if( pExpr==0 ) return;
  66421. assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  66422. z = pExpr->u.zToken;
  66423. assert( z!=0 );
  66424. assert( z[0]!=0 );
  66425. if( z[1]==0 ){
  66426. /* Wildcard of the form "?". Assign the next variable number */
  66427. assert( z[0]=='?' );
  66428. pExpr->iColumn = (ynVar)(++pParse->nVar);
  66429. }else if( z[0]=='?' ){
  66430. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  66431. ** use it as the variable number */
  66432. i64 i;
  66433. int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
  66434. pExpr->iColumn = (ynVar)i;
  66435. testcase( i==0 );
  66436. testcase( i==1 );
  66437. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  66438. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  66439. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  66440. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  66441. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  66442. }
  66443. if( i>pParse->nVar ){
  66444. pParse->nVar = (int)i;
  66445. }
  66446. }else{
  66447. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  66448. ** number as the prior appearance of the same name, or if the name
  66449. ** has never appeared before, reuse the same variable number
  66450. */
  66451. int i;
  66452. u32 n;
  66453. n = sqlite3Strlen30(z);
  66454. for(i=0; i<pParse->nVarExpr; i++){
  66455. Expr *pE = pParse->apVarExpr[i];
  66456. assert( pE!=0 );
  66457. if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
  66458. pExpr->iColumn = pE->iColumn;
  66459. break;
  66460. }
  66461. }
  66462. if( i>=pParse->nVarExpr ){
  66463. pExpr->iColumn = (ynVar)(++pParse->nVar);
  66464. if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
  66465. pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
  66466. pParse->apVarExpr =
  66467. sqlite3DbReallocOrFree(
  66468. db,
  66469. pParse->apVarExpr,
  66470. pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
  66471. );
  66472. }
  66473. if( !db->mallocFailed ){
  66474. assert( pParse->apVarExpr!=0 );
  66475. pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
  66476. }
  66477. }
  66478. }
  66479. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  66480. sqlite3ErrorMsg(pParse, "too many SQL variables");
  66481. }
  66482. }
  66483. /*
  66484. ** Recursively delete an expression tree.
  66485. */
  66486. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  66487. if( p==0 ) return;
  66488. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  66489. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  66490. if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
  66491. sqlite3ExprDelete(db, p->pLeft);
  66492. sqlite3ExprDelete(db, p->pRight);
  66493. if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
  66494. sqlite3DbFree(db, p->u.zToken);
  66495. }
  66496. if( ExprHasProperty(p, EP_xIsSelect) ){
  66497. sqlite3SelectDelete(db, p->x.pSelect);
  66498. }else{
  66499. sqlite3ExprListDelete(db, p->x.pList);
  66500. }
  66501. }
  66502. if( !ExprHasProperty(p, EP_Static) ){
  66503. sqlite3DbFree(db, p);
  66504. }
  66505. }
  66506. /*
  66507. ** Return the number of bytes allocated for the expression structure
  66508. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  66509. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  66510. */
  66511. static int exprStructSize(Expr *p){
  66512. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  66513. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  66514. return EXPR_FULLSIZE;
  66515. }
  66516. /*
  66517. ** The dupedExpr*Size() routines each return the number of bytes required
  66518. ** to store a copy of an expression or expression tree. They differ in
  66519. ** how much of the tree is measured.
  66520. **
  66521. ** dupedExprStructSize() Size of only the Expr structure
  66522. ** dupedExprNodeSize() Size of Expr + space for token
  66523. ** dupedExprSize() Expr + token + subtree components
  66524. **
  66525. ***************************************************************************
  66526. **
  66527. ** The dupedExprStructSize() function returns two values OR-ed together:
  66528. ** (1) the space required for a copy of the Expr structure only and
  66529. ** (2) the EP_xxx flags that indicate what the structure size should be.
  66530. ** The return values is always one of:
  66531. **
  66532. ** EXPR_FULLSIZE
  66533. ** EXPR_REDUCEDSIZE | EP_Reduced
  66534. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  66535. **
  66536. ** The size of the structure can be found by masking the return value
  66537. ** of this routine with 0xfff. The flags can be found by masking the
  66538. ** return value with EP_Reduced|EP_TokenOnly.
  66539. **
  66540. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  66541. ** (unreduced) Expr objects as they or originally constructed by the parser.
  66542. ** During expression analysis, extra information is computed and moved into
  66543. ** later parts of teh Expr object and that extra information might get chopped
  66544. ** off if the expression is reduced. Note also that it does not work to
  66545. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  66546. ** to reduce a pristine expression tree from the parser. The implementation
  66547. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  66548. ** to enforce this constraint.
  66549. */
  66550. static int dupedExprStructSize(Expr *p, int flags){
  66551. int nSize;
  66552. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  66553. if( 0==(flags&EXPRDUP_REDUCE) ){
  66554. nSize = EXPR_FULLSIZE;
  66555. }else{
  66556. assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
  66557. assert( !ExprHasProperty(p, EP_FromJoin) );
  66558. assert( (p->flags2 & EP2_MallocedToken)==0 );
  66559. assert( (p->flags2 & EP2_Irreducible)==0 );
  66560. if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
  66561. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  66562. }else{
  66563. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  66564. }
  66565. }
  66566. return nSize;
  66567. }
  66568. /*
  66569. ** This function returns the space in bytes required to store the copy
  66570. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  66571. ** string is defined.)
  66572. */
  66573. static int dupedExprNodeSize(Expr *p, int flags){
  66574. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  66575. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  66576. nByte += sqlite3Strlen30(p->u.zToken)+1;
  66577. }
  66578. return ROUND8(nByte);
  66579. }
  66580. /*
  66581. ** Return the number of bytes required to create a duplicate of the
  66582. ** expression passed as the first argument. The second argument is a
  66583. ** mask containing EXPRDUP_XXX flags.
  66584. **
  66585. ** The value returned includes space to create a copy of the Expr struct
  66586. ** itself and the buffer referred to by Expr.u.zToken, if any.
  66587. **
  66588. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  66589. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  66590. ** and Expr.pRight variables (but not for any structures pointed to or
  66591. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  66592. */
  66593. static int dupedExprSize(Expr *p, int flags){
  66594. int nByte = 0;
  66595. if( p ){
  66596. nByte = dupedExprNodeSize(p, flags);
  66597. if( flags&EXPRDUP_REDUCE ){
  66598. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  66599. }
  66600. }
  66601. return nByte;
  66602. }
  66603. /*
  66604. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  66605. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  66606. ** to store the copy of expression p, the copies of p->u.zToken
  66607. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  66608. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  66609. ** portion of the buffer copied into by this function.
  66610. */
  66611. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  66612. Expr *pNew = 0; /* Value to return */
  66613. if( p ){
  66614. const int isReduced = (flags&EXPRDUP_REDUCE);
  66615. u8 *zAlloc;
  66616. u32 staticFlag = 0;
  66617. assert( pzBuffer==0 || isReduced );
  66618. /* Figure out where to write the new Expr structure. */
  66619. if( pzBuffer ){
  66620. zAlloc = *pzBuffer;
  66621. staticFlag = EP_Static;
  66622. }else{
  66623. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  66624. }
  66625. pNew = (Expr *)zAlloc;
  66626. if( pNew ){
  66627. /* Set nNewSize to the size allocated for the structure pointed to
  66628. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  66629. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  66630. ** by the copy of the p->u.zToken string (if any).
  66631. */
  66632. const unsigned nStructSize = dupedExprStructSize(p, flags);
  66633. const int nNewSize = nStructSize & 0xfff;
  66634. int nToken;
  66635. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  66636. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  66637. }else{
  66638. nToken = 0;
  66639. }
  66640. if( isReduced ){
  66641. assert( ExprHasProperty(p, EP_Reduced)==0 );
  66642. memcpy(zAlloc, p, nNewSize);
  66643. }else{
  66644. int nSize = exprStructSize(p);
  66645. memcpy(zAlloc, p, nSize);
  66646. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  66647. }
  66648. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  66649. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
  66650. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  66651. pNew->flags |= staticFlag;
  66652. /* Copy the p->u.zToken string, if any. */
  66653. if( nToken ){
  66654. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  66655. memcpy(zToken, p->u.zToken, nToken);
  66656. }
  66657. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  66658. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  66659. if( ExprHasProperty(p, EP_xIsSelect) ){
  66660. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  66661. }else{
  66662. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  66663. }
  66664. }
  66665. /* Fill in pNew->pLeft and pNew->pRight. */
  66666. if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  66667. zAlloc += dupedExprNodeSize(p, flags);
  66668. if( ExprHasProperty(pNew, EP_Reduced) ){
  66669. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  66670. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  66671. }
  66672. if( pzBuffer ){
  66673. *pzBuffer = zAlloc;
  66674. }
  66675. }else{
  66676. pNew->flags2 = 0;
  66677. if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
  66678. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  66679. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  66680. }
  66681. }
  66682. }
  66683. }
  66684. return pNew;
  66685. }
  66686. /*
  66687. ** The following group of routines make deep copies of expressions,
  66688. ** expression lists, ID lists, and select statements. The copies can
  66689. ** be deleted (by being passed to their respective ...Delete() routines)
  66690. ** without effecting the originals.
  66691. **
  66692. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  66693. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  66694. ** by subsequent calls to sqlite*ListAppend() routines.
  66695. **
  66696. ** Any tables that the SrcList might point to are not duplicated.
  66697. **
  66698. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  66699. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  66700. ** truncated version of the usual Expr structure that will be stored as
  66701. ** part of the in-memory representation of the database schema.
  66702. */
  66703. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  66704. return exprDup(db, p, flags, 0);
  66705. }
  66706. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  66707. ExprList *pNew;
  66708. struct ExprList_item *pItem, *pOldItem;
  66709. int i;
  66710. if( p==0 ) return 0;
  66711. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  66712. if( pNew==0 ) return 0;
  66713. pNew->iECursor = 0;
  66714. pNew->nExpr = pNew->nAlloc = p->nExpr;
  66715. pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
  66716. if( pItem==0 ){
  66717. sqlite3DbFree(db, pNew);
  66718. return 0;
  66719. }
  66720. pOldItem = p->a;
  66721. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  66722. Expr *pOldExpr = pOldItem->pExpr;
  66723. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  66724. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  66725. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  66726. pItem->sortOrder = pOldItem->sortOrder;
  66727. pItem->done = 0;
  66728. pItem->iCol = pOldItem->iCol;
  66729. pItem->iAlias = pOldItem->iAlias;
  66730. }
  66731. return pNew;
  66732. }
  66733. /*
  66734. ** If cursors, triggers, views and subqueries are all omitted from
  66735. ** the build, then none of the following routines, except for
  66736. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  66737. ** called with a NULL argument.
  66738. */
  66739. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  66740. || !defined(SQLITE_OMIT_SUBQUERY)
  66741. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  66742. SrcList *pNew;
  66743. int i;
  66744. int nByte;
  66745. if( p==0 ) return 0;
  66746. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  66747. pNew = sqlite3DbMallocRaw(db, nByte );
  66748. if( pNew==0 ) return 0;
  66749. pNew->nSrc = pNew->nAlloc = p->nSrc;
  66750. for(i=0; i<p->nSrc; i++){
  66751. struct SrcList_item *pNewItem = &pNew->a[i];
  66752. struct SrcList_item *pOldItem = &p->a[i];
  66753. Table *pTab;
  66754. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  66755. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  66756. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  66757. pNewItem->jointype = pOldItem->jointype;
  66758. pNewItem->iCursor = pOldItem->iCursor;
  66759. pNewItem->isPopulated = pOldItem->isPopulated;
  66760. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  66761. pNewItem->notIndexed = pOldItem->notIndexed;
  66762. pNewItem->pIndex = pOldItem->pIndex;
  66763. pTab = pNewItem->pTab = pOldItem->pTab;
  66764. if( pTab ){
  66765. pTab->nRef++;
  66766. }
  66767. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  66768. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  66769. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  66770. pNewItem->colUsed = pOldItem->colUsed;
  66771. }
  66772. return pNew;
  66773. }
  66774. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  66775. IdList *pNew;
  66776. int i;
  66777. if( p==0 ) return 0;
  66778. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  66779. if( pNew==0 ) return 0;
  66780. pNew->nId = pNew->nAlloc = p->nId;
  66781. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  66782. if( pNew->a==0 ){
  66783. sqlite3DbFree(db, pNew);
  66784. return 0;
  66785. }
  66786. for(i=0; i<p->nId; i++){
  66787. struct IdList_item *pNewItem = &pNew->a[i];
  66788. struct IdList_item *pOldItem = &p->a[i];
  66789. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  66790. pNewItem->idx = pOldItem->idx;
  66791. }
  66792. return pNew;
  66793. }
  66794. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  66795. Select *pNew;
  66796. if( p==0 ) return 0;
  66797. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  66798. if( pNew==0 ) return 0;
  66799. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  66800. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  66801. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  66802. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  66803. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  66804. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  66805. pNew->op = p->op;
  66806. pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  66807. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  66808. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  66809. pNew->iLimit = 0;
  66810. pNew->iOffset = 0;
  66811. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  66812. pNew->pRightmost = 0;
  66813. pNew->addrOpenEphm[0] = -1;
  66814. pNew->addrOpenEphm[1] = -1;
  66815. pNew->addrOpenEphm[2] = -1;
  66816. return pNew;
  66817. }
  66818. #else
  66819. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  66820. assert( p==0 );
  66821. return 0;
  66822. }
  66823. #endif
  66824. /*
  66825. ** Add a new element to the end of an expression list. If pList is
  66826. ** initially NULL, then create a new expression list.
  66827. **
  66828. ** If a memory allocation error occurs, the entire list is freed and
  66829. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  66830. ** that the new entry was successfully appended.
  66831. */
  66832. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  66833. Parse *pParse, /* Parsing context */
  66834. ExprList *pList, /* List to which to append. Might be NULL */
  66835. Expr *pExpr /* Expression to be appended. Might be NULL */
  66836. ){
  66837. sqlite3 *db = pParse->db;
  66838. if( pList==0 ){
  66839. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  66840. if( pList==0 ){
  66841. goto no_mem;
  66842. }
  66843. assert( pList->nAlloc==0 );
  66844. }
  66845. if( pList->nAlloc<=pList->nExpr ){
  66846. struct ExprList_item *a;
  66847. int n = pList->nAlloc*2 + 4;
  66848. a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
  66849. if( a==0 ){
  66850. goto no_mem;
  66851. }
  66852. pList->a = a;
  66853. pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
  66854. }
  66855. assert( pList->a!=0 );
  66856. if( 1 ){
  66857. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  66858. memset(pItem, 0, sizeof(*pItem));
  66859. pItem->pExpr = pExpr;
  66860. }
  66861. return pList;
  66862. no_mem:
  66863. /* Avoid leaking memory if malloc has failed. */
  66864. sqlite3ExprDelete(db, pExpr);
  66865. sqlite3ExprListDelete(db, pList);
  66866. return 0;
  66867. }
  66868. /*
  66869. ** Set the ExprList.a[].zName element of the most recently added item
  66870. ** on the expression list.
  66871. **
  66872. ** pList might be NULL following an OOM error. But pName should never be
  66873. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  66874. ** is set.
  66875. */
  66876. SQLITE_PRIVATE void sqlite3ExprListSetName(
  66877. Parse *pParse, /* Parsing context */
  66878. ExprList *pList, /* List to which to add the span. */
  66879. Token *pName, /* Name to be added */
  66880. int dequote /* True to cause the name to be dequoted */
  66881. ){
  66882. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  66883. if( pList ){
  66884. struct ExprList_item *pItem;
  66885. assert( pList->nExpr>0 );
  66886. pItem = &pList->a[pList->nExpr-1];
  66887. assert( pItem->zName==0 );
  66888. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  66889. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  66890. }
  66891. }
  66892. /*
  66893. ** Set the ExprList.a[].zSpan element of the most recently added item
  66894. ** on the expression list.
  66895. **
  66896. ** pList might be NULL following an OOM error. But pSpan should never be
  66897. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  66898. ** is set.
  66899. */
  66900. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  66901. Parse *pParse, /* Parsing context */
  66902. ExprList *pList, /* List to which to add the span. */
  66903. ExprSpan *pSpan /* The span to be added */
  66904. ){
  66905. sqlite3 *db = pParse->db;
  66906. assert( pList!=0 || db->mallocFailed!=0 );
  66907. if( pList ){
  66908. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  66909. assert( pList->nExpr>0 );
  66910. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  66911. sqlite3DbFree(db, pItem->zSpan);
  66912. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  66913. (int)(pSpan->zEnd - pSpan->zStart));
  66914. }
  66915. }
  66916. /*
  66917. ** If the expression list pEList contains more than iLimit elements,
  66918. ** leave an error message in pParse.
  66919. */
  66920. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  66921. Parse *pParse,
  66922. ExprList *pEList,
  66923. const char *zObject
  66924. ){
  66925. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  66926. testcase( pEList && pEList->nExpr==mx );
  66927. testcase( pEList && pEList->nExpr==mx+1 );
  66928. if( pEList && pEList->nExpr>mx ){
  66929. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  66930. }
  66931. }
  66932. /*
  66933. ** Delete an entire expression list.
  66934. */
  66935. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  66936. int i;
  66937. struct ExprList_item *pItem;
  66938. if( pList==0 ) return;
  66939. assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
  66940. assert( pList->nExpr<=pList->nAlloc );
  66941. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  66942. sqlite3ExprDelete(db, pItem->pExpr);
  66943. sqlite3DbFree(db, pItem->zName);
  66944. sqlite3DbFree(db, pItem->zSpan);
  66945. }
  66946. sqlite3DbFree(db, pList->a);
  66947. sqlite3DbFree(db, pList);
  66948. }
  66949. /*
  66950. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  66951. ** to an integer. These routines are checking an expression to see
  66952. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  66953. ** not constant.
  66954. **
  66955. ** These callback routines are used to implement the following:
  66956. **
  66957. ** sqlite3ExprIsConstant()
  66958. ** sqlite3ExprIsConstantNotJoin()
  66959. ** sqlite3ExprIsConstantOrFunction()
  66960. **
  66961. */
  66962. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  66963. /* If pWalker->u.i is 3 then any term of the expression that comes from
  66964. ** the ON or USING clauses of a join disqualifies the expression
  66965. ** from being considered constant. */
  66966. if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
  66967. pWalker->u.i = 0;
  66968. return WRC_Abort;
  66969. }
  66970. switch( pExpr->op ){
  66971. /* Consider functions to be constant if all their arguments are constant
  66972. ** and pWalker->u.i==2 */
  66973. case TK_FUNCTION:
  66974. if( pWalker->u.i==2 ) return 0;
  66975. /* Fall through */
  66976. case TK_ID:
  66977. case TK_COLUMN:
  66978. case TK_AGG_FUNCTION:
  66979. case TK_AGG_COLUMN:
  66980. testcase( pExpr->op==TK_ID );
  66981. testcase( pExpr->op==TK_COLUMN );
  66982. testcase( pExpr->op==TK_AGG_FUNCTION );
  66983. testcase( pExpr->op==TK_AGG_COLUMN );
  66984. pWalker->u.i = 0;
  66985. return WRC_Abort;
  66986. default:
  66987. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  66988. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  66989. return WRC_Continue;
  66990. }
  66991. }
  66992. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  66993. UNUSED_PARAMETER(NotUsed);
  66994. pWalker->u.i = 0;
  66995. return WRC_Abort;
  66996. }
  66997. static int exprIsConst(Expr *p, int initFlag){
  66998. Walker w;
  66999. w.u.i = initFlag;
  67000. w.xExprCallback = exprNodeIsConstant;
  67001. w.xSelectCallback = selectNodeIsConstant;
  67002. sqlite3WalkExpr(&w, p);
  67003. return w.u.i;
  67004. }
  67005. /*
  67006. ** Walk an expression tree. Return 1 if the expression is constant
  67007. ** and 0 if it involves variables or function calls.
  67008. **
  67009. ** For the purposes of this function, a double-quoted string (ex: "abc")
  67010. ** is considered a variable but a single-quoted string (ex: 'abc') is
  67011. ** a constant.
  67012. */
  67013. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  67014. return exprIsConst(p, 1);
  67015. }
  67016. /*
  67017. ** Walk an expression tree. Return 1 if the expression is constant
  67018. ** that does no originate from the ON or USING clauses of a join.
  67019. ** Return 0 if it involves variables or function calls or terms from
  67020. ** an ON or USING clause.
  67021. */
  67022. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  67023. return exprIsConst(p, 3);
  67024. }
  67025. /*
  67026. ** Walk an expression tree. Return 1 if the expression is constant
  67027. ** or a function call with constant arguments. Return and 0 if there
  67028. ** are any variables.
  67029. **
  67030. ** For the purposes of this function, a double-quoted string (ex: "abc")
  67031. ** is considered a variable but a single-quoted string (ex: 'abc') is
  67032. ** a constant.
  67033. */
  67034. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  67035. return exprIsConst(p, 2);
  67036. }
  67037. /*
  67038. ** If the expression p codes a constant integer that is small enough
  67039. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  67040. ** in *pValue. If the expression is not an integer or if it is too big
  67041. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  67042. */
  67043. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  67044. int rc = 0;
  67045. /* If an expression is an integer literal that fits in a signed 32-bit
  67046. ** integer, then the EP_IntValue flag will have already been set */
  67047. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  67048. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  67049. if( p->flags & EP_IntValue ){
  67050. *pValue = p->u.iValue;
  67051. return 1;
  67052. }
  67053. switch( p->op ){
  67054. case TK_UPLUS: {
  67055. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  67056. break;
  67057. }
  67058. case TK_UMINUS: {
  67059. int v;
  67060. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  67061. *pValue = -v;
  67062. rc = 1;
  67063. }
  67064. break;
  67065. }
  67066. default: break;
  67067. }
  67068. return rc;
  67069. }
  67070. /*
  67071. ** Return FALSE if there is no chance that the expression can be NULL.
  67072. **
  67073. ** If the expression might be NULL or if the expression is too complex
  67074. ** to tell return TRUE.
  67075. **
  67076. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  67077. ** when we know that a value cannot be NULL. Hence, a false positive
  67078. ** (returning TRUE when in fact the expression can never be NULL) might
  67079. ** be a small performance hit but is otherwise harmless. On the other
  67080. ** hand, a false negative (returning FALSE when the result could be NULL)
  67081. ** will likely result in an incorrect answer. So when in doubt, return
  67082. ** TRUE.
  67083. */
  67084. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  67085. u8 op;
  67086. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  67087. op = p->op;
  67088. if( op==TK_REGISTER ) op = p->op2;
  67089. switch( op ){
  67090. case TK_INTEGER:
  67091. case TK_STRING:
  67092. case TK_FLOAT:
  67093. case TK_BLOB:
  67094. return 0;
  67095. default:
  67096. return 1;
  67097. }
  67098. }
  67099. /*
  67100. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  67101. ** to location iDest if the value in iReg is NULL. The value in iReg
  67102. ** was computed by pExpr. If we can look at pExpr at compile-time and
  67103. ** determine that it can never generate a NULL, then the OP_IsNull operation
  67104. ** can be omitted.
  67105. */
  67106. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
  67107. Vdbe *v, /* The VDBE under construction */
  67108. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  67109. int iReg, /* Test the value in this register for NULL */
  67110. int iDest /* Jump here if the value is null */
  67111. ){
  67112. if( sqlite3ExprCanBeNull(pExpr) ){
  67113. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  67114. }
  67115. }
  67116. /*
  67117. ** Return TRUE if the given expression is a constant which would be
  67118. ** unchanged by OP_Affinity with the affinity given in the second
  67119. ** argument.
  67120. **
  67121. ** This routine is used to determine if the OP_Affinity operation
  67122. ** can be omitted. When in doubt return FALSE. A false negative
  67123. ** is harmless. A false positive, however, can result in the wrong
  67124. ** answer.
  67125. */
  67126. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  67127. u8 op;
  67128. if( aff==SQLITE_AFF_NONE ) return 1;
  67129. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  67130. op = p->op;
  67131. if( op==TK_REGISTER ) op = p->op2;
  67132. switch( op ){
  67133. case TK_INTEGER: {
  67134. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  67135. }
  67136. case TK_FLOAT: {
  67137. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  67138. }
  67139. case TK_STRING: {
  67140. return aff==SQLITE_AFF_TEXT;
  67141. }
  67142. case TK_BLOB: {
  67143. return 1;
  67144. }
  67145. case TK_COLUMN: {
  67146. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  67147. return p->iColumn<0
  67148. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  67149. }
  67150. default: {
  67151. return 0;
  67152. }
  67153. }
  67154. }
  67155. /*
  67156. ** Return TRUE if the given string is a row-id column name.
  67157. */
  67158. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  67159. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  67160. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  67161. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  67162. return 0;
  67163. }
  67164. /*
  67165. ** Return true if we are able to the IN operator optimization on a
  67166. ** query of the form
  67167. **
  67168. ** x IN (SELECT ...)
  67169. **
  67170. ** Where the SELECT... clause is as specified by the parameter to this
  67171. ** routine.
  67172. **
  67173. ** The Select object passed in has already been preprocessed and no
  67174. ** errors have been found.
  67175. */
  67176. #ifndef SQLITE_OMIT_SUBQUERY
  67177. static int isCandidateForInOpt(Select *p){
  67178. SrcList *pSrc;
  67179. ExprList *pEList;
  67180. Table *pTab;
  67181. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  67182. if( p->pPrior ) return 0; /* Not a compound SELECT */
  67183. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  67184. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  67185. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  67186. return 0; /* No DISTINCT keyword and no aggregate functions */
  67187. }
  67188. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  67189. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  67190. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  67191. if( p->pWhere ) return 0; /* Has no WHERE clause */
  67192. pSrc = p->pSrc;
  67193. assert( pSrc!=0 );
  67194. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  67195. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  67196. pTab = pSrc->a[0].pTab;
  67197. if( NEVER(pTab==0) ) return 0;
  67198. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  67199. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  67200. pEList = p->pEList;
  67201. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  67202. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  67203. return 1;
  67204. }
  67205. #endif /* SQLITE_OMIT_SUBQUERY */
  67206. /*
  67207. ** This function is used by the implementation of the IN (...) operator.
  67208. ** It's job is to find or create a b-tree structure that may be used
  67209. ** either to test for membership of the (...) set or to iterate through
  67210. ** its members, skipping duplicates.
  67211. **
  67212. ** The index of the cursor opened on the b-tree (database table, database index
  67213. ** or ephermal table) is stored in pX->iTable before this function returns.
  67214. ** The returned value of this function indicates the b-tree type, as follows:
  67215. **
  67216. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  67217. ** IN_INDEX_INDEX - The cursor was opened on a database index.
  67218. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  67219. ** populated epheremal table.
  67220. **
  67221. ** An existing b-tree may only be used if the SELECT is of the simple
  67222. ** form:
  67223. **
  67224. ** SELECT <column> FROM <table>
  67225. **
  67226. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  67227. ** through the set members, skipping any duplicates. In this case an
  67228. ** epheremal table must be used unless the selected <column> is guaranteed
  67229. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  67230. ** has a UNIQUE constraint or UNIQUE index.
  67231. **
  67232. ** If the prNotFound parameter is not 0, then the b-tree will be used
  67233. ** for fast set membership tests. In this case an epheremal table must
  67234. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  67235. ** be found with <column> as its left-most column.
  67236. **
  67237. ** When the b-tree is being used for membership tests, the calling function
  67238. ** needs to know whether or not the structure contains an SQL NULL
  67239. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  67240. ** If there is any chance that the (...) might contain a NULL value at
  67241. ** runtime, then a register is allocated and the register number written
  67242. ** to *prNotFound. If there is no chance that the (...) contains a
  67243. ** NULL value, then *prNotFound is left unchanged.
  67244. **
  67245. ** If a register is allocated and its location stored in *prNotFound, then
  67246. ** its initial value is NULL. If the (...) does not remain constant
  67247. ** for the duration of the query (i.e. the SELECT within the (...)
  67248. ** is a correlated subquery) then the value of the allocated register is
  67249. ** reset to NULL each time the subquery is rerun. This allows the
  67250. ** caller to use vdbe code equivalent to the following:
  67251. **
  67252. ** if( register==NULL ){
  67253. ** has_null = <test if data structure contains null>
  67254. ** register = 1
  67255. ** }
  67256. **
  67257. ** in order to avoid running the <test if data structure contains null>
  67258. ** test more often than is necessary.
  67259. */
  67260. #ifndef SQLITE_OMIT_SUBQUERY
  67261. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  67262. Select *p; /* SELECT to the right of IN operator */
  67263. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  67264. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  67265. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  67266. assert( pX->op==TK_IN );
  67267. /* Check to see if an existing table or index can be used to
  67268. ** satisfy the query. This is preferable to generating a new
  67269. ** ephemeral table.
  67270. */
  67271. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  67272. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  67273. sqlite3 *db = pParse->db; /* Database connection */
  67274. Expr *pExpr = p->pEList->a[0].pExpr; /* Expression <column> */
  67275. int iCol = pExpr->iColumn; /* Index of column <column> */
  67276. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  67277. Table *pTab = p->pSrc->a[0].pTab; /* Table <table>. */
  67278. int iDb; /* Database idx for pTab */
  67279. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  67280. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  67281. sqlite3CodeVerifySchema(pParse, iDb);
  67282. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  67283. /* This function is only called from two places. In both cases the vdbe
  67284. ** has already been allocated. So assume sqlite3GetVdbe() is always
  67285. ** successful here.
  67286. */
  67287. assert(v);
  67288. if( iCol<0 ){
  67289. int iMem = ++pParse->nMem;
  67290. int iAddr;
  67291. iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  67292. sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  67293. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  67294. eType = IN_INDEX_ROWID;
  67295. sqlite3VdbeJumpHere(v, iAddr);
  67296. }else{
  67297. Index *pIdx; /* Iterator variable */
  67298. /* The collation sequence used by the comparison. If an index is to
  67299. ** be used in place of a temp-table, it must be ordered according
  67300. ** to this collation sequence. */
  67301. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  67302. /* Check that the affinity that will be used to perform the
  67303. ** comparison is the same as the affinity of the column. If
  67304. ** it is not, it is not possible to use any index.
  67305. */
  67306. char aff = comparisonAffinity(pX);
  67307. int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
  67308. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  67309. if( (pIdx->aiColumn[0]==iCol)
  67310. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  67311. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  67312. ){
  67313. int iMem = ++pParse->nMem;
  67314. int iAddr;
  67315. char *pKey;
  67316. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  67317. iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
  67318. sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
  67319. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  67320. pKey,P4_KEYINFO_HANDOFF);
  67321. VdbeComment((v, "%s", pIdx->zName));
  67322. eType = IN_INDEX_INDEX;
  67323. sqlite3VdbeJumpHere(v, iAddr);
  67324. if( prNotFound && !pTab->aCol[iCol].notNull ){
  67325. *prNotFound = ++pParse->nMem;
  67326. }
  67327. }
  67328. }
  67329. }
  67330. }
  67331. if( eType==0 ){
  67332. /* Could not found an existing table or index to use as the RHS b-tree.
  67333. ** We will have to generate an ephemeral table to do the job.
  67334. */
  67335. double savedNQueryLoop = pParse->nQueryLoop;
  67336. int rMayHaveNull = 0;
  67337. eType = IN_INDEX_EPH;
  67338. if( prNotFound ){
  67339. *prNotFound = rMayHaveNull = ++pParse->nMem;
  67340. }else{
  67341. testcase( pParse->nQueryLoop>(double)1 );
  67342. pParse->nQueryLoop = (double)1;
  67343. if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
  67344. eType = IN_INDEX_ROWID;
  67345. }
  67346. }
  67347. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  67348. pParse->nQueryLoop = savedNQueryLoop;
  67349. }else{
  67350. pX->iTable = iTab;
  67351. }
  67352. return eType;
  67353. }
  67354. #endif
  67355. /*
  67356. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  67357. ** or IN operators. Examples:
  67358. **
  67359. ** (SELECT a FROM b) -- subquery
  67360. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  67361. ** x IN (4,5,11) -- IN operator with list on right-hand side
  67362. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  67363. **
  67364. ** The pExpr parameter describes the expression that contains the IN
  67365. ** operator or subquery.
  67366. **
  67367. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  67368. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  67369. ** to some integer key column of a table B-Tree. In this case, use an
  67370. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  67371. ** (slower) variable length keys B-Tree.
  67372. **
  67373. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  67374. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  67375. ** Furthermore, the IN is in a WHERE clause and that we really want
  67376. ** to iterate over the RHS of the IN operator in order to quickly locate
  67377. ** all corresponding LHS elements. All this routine does is initialize
  67378. ** the register given by rMayHaveNull to NULL. Calling routines will take
  67379. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  67380. **
  67381. ** If rMayHaveNull is zero, that means that the subquery is being used
  67382. ** for membership testing only. There is no need to initialize any
  67383. ** registers to indicate the presense or absence of NULLs on the RHS.
  67384. **
  67385. ** For a SELECT or EXISTS operator, return the register that holds the
  67386. ** result. For IN operators or if an error occurs, the return value is 0.
  67387. */
  67388. #ifndef SQLITE_OMIT_SUBQUERY
  67389. SQLITE_PRIVATE int sqlite3CodeSubselect(
  67390. Parse *pParse, /* Parsing context */
  67391. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  67392. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  67393. int isRowid /* If true, LHS of IN operator is a rowid */
  67394. ){
  67395. int testAddr = 0; /* One-time test address */
  67396. int rReg = 0; /* Register storing resulting */
  67397. Vdbe *v = sqlite3GetVdbe(pParse);
  67398. if( NEVER(v==0) ) return 0;
  67399. sqlite3ExprCachePush(pParse);
  67400. /* This code must be run in its entirety every time it is encountered
  67401. ** if any of the following is true:
  67402. **
  67403. ** * The right-hand side is a correlated subquery
  67404. ** * The right-hand side is an expression list containing variables
  67405. ** * We are inside a trigger
  67406. **
  67407. ** If all of the above are false, then we can run this code just once
  67408. ** save the results, and reuse the same result on subsequent invocations.
  67409. */
  67410. if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
  67411. int mem = ++pParse->nMem;
  67412. sqlite3VdbeAddOp1(v, OP_If, mem);
  67413. testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
  67414. assert( testAddr>0 || pParse->db->mallocFailed );
  67415. }
  67416. #ifndef SQLITE_OMIT_EXPLAIN
  67417. if( pParse->explain==2 ){
  67418. char *zMsg = sqlite3MPrintf(
  67419. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
  67420. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  67421. );
  67422. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  67423. }
  67424. #endif
  67425. switch( pExpr->op ){
  67426. case TK_IN: {
  67427. char affinity; /* Affinity of the LHS of the IN */
  67428. KeyInfo keyInfo; /* Keyinfo for the generated table */
  67429. int addr; /* Address of OP_OpenEphemeral instruction */
  67430. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  67431. if( rMayHaveNull ){
  67432. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  67433. }
  67434. affinity = sqlite3ExprAffinity(pLeft);
  67435. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  67436. ** expression it is handled the same way. An ephemeral table is
  67437. ** filled with single-field index keys representing the results
  67438. ** from the SELECT or the <exprlist>.
  67439. **
  67440. ** If the 'x' expression is a column value, or the SELECT...
  67441. ** statement returns a column value, then the affinity of that
  67442. ** column is used to build the index keys. If both 'x' and the
  67443. ** SELECT... statement are columns, then numeric affinity is used
  67444. ** if either column has NUMERIC or INTEGER affinity. If neither
  67445. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  67446. ** is used.
  67447. */
  67448. pExpr->iTable = pParse->nTab++;
  67449. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  67450. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  67451. memset(&keyInfo, 0, sizeof(keyInfo));
  67452. keyInfo.nField = 1;
  67453. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  67454. /* Case 1: expr IN (SELECT ...)
  67455. **
  67456. ** Generate code to write the results of the select into the temporary
  67457. ** table allocated and opened above.
  67458. */
  67459. SelectDest dest;
  67460. ExprList *pEList;
  67461. assert( !isRowid );
  67462. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  67463. dest.affinity = (u8)affinity;
  67464. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  67465. pExpr->x.pSelect->iLimit = 0;
  67466. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  67467. return 0;
  67468. }
  67469. pEList = pExpr->x.pSelect->pEList;
  67470. if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
  67471. keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  67472. pEList->a[0].pExpr);
  67473. }
  67474. }else if( ALWAYS(pExpr->x.pList!=0) ){
  67475. /* Case 2: expr IN (exprlist)
  67476. **
  67477. ** For each expression, build an index key from the evaluation and
  67478. ** store it in the temporary table. If <expr> is a column, then use
  67479. ** that columns affinity when building index keys. If <expr> is not
  67480. ** a column, use numeric affinity.
  67481. */
  67482. int i;
  67483. ExprList *pList = pExpr->x.pList;
  67484. struct ExprList_item *pItem;
  67485. int r1, r2, r3;
  67486. if( !affinity ){
  67487. affinity = SQLITE_AFF_NONE;
  67488. }
  67489. keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  67490. /* Loop through each expression in <exprlist>. */
  67491. r1 = sqlite3GetTempReg(pParse);
  67492. r2 = sqlite3GetTempReg(pParse);
  67493. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  67494. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  67495. Expr *pE2 = pItem->pExpr;
  67496. int iValToIns;
  67497. /* If the expression is not constant then we will need to
  67498. ** disable the test that was generated above that makes sure
  67499. ** this code only executes once. Because for a non-constant
  67500. ** expression we need to rerun this code each time.
  67501. */
  67502. if( testAddr && !sqlite3ExprIsConstant(pE2) ){
  67503. sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
  67504. testAddr = 0;
  67505. }
  67506. /* Evaluate the expression and insert it into the temp table */
  67507. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  67508. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  67509. }else{
  67510. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  67511. if( isRowid ){
  67512. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  67513. sqlite3VdbeCurrentAddr(v)+2);
  67514. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  67515. }else{
  67516. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  67517. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  67518. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  67519. }
  67520. }
  67521. }
  67522. sqlite3ReleaseTempReg(pParse, r1);
  67523. sqlite3ReleaseTempReg(pParse, r2);
  67524. }
  67525. if( !isRowid ){
  67526. sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
  67527. }
  67528. break;
  67529. }
  67530. case TK_EXISTS:
  67531. case TK_SELECT:
  67532. default: {
  67533. /* If this has to be a scalar SELECT. Generate code to put the
  67534. ** value of this select in a memory cell and record the number
  67535. ** of the memory cell in iColumn. If this is an EXISTS, write
  67536. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  67537. ** and record that memory cell in iColumn.
  67538. */
  67539. Select *pSel; /* SELECT statement to encode */
  67540. SelectDest dest; /* How to deal with SELECt result */
  67541. testcase( pExpr->op==TK_EXISTS );
  67542. testcase( pExpr->op==TK_SELECT );
  67543. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  67544. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  67545. pSel = pExpr->x.pSelect;
  67546. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  67547. if( pExpr->op==TK_SELECT ){
  67548. dest.eDest = SRT_Mem;
  67549. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
  67550. VdbeComment((v, "Init subquery result"));
  67551. }else{
  67552. dest.eDest = SRT_Exists;
  67553. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
  67554. VdbeComment((v, "Init EXISTS result"));
  67555. }
  67556. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  67557. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  67558. &sqlite3IntTokens[1]);
  67559. pSel->iLimit = 0;
  67560. if( sqlite3Select(pParse, pSel, &dest) ){
  67561. return 0;
  67562. }
  67563. rReg = dest.iParm;
  67564. ExprSetIrreducible(pExpr);
  67565. break;
  67566. }
  67567. }
  67568. if( testAddr ){
  67569. sqlite3VdbeJumpHere(v, testAddr-1);
  67570. }
  67571. sqlite3ExprCachePop(pParse, 1);
  67572. return rReg;
  67573. }
  67574. #endif /* SQLITE_OMIT_SUBQUERY */
  67575. #ifndef SQLITE_OMIT_SUBQUERY
  67576. /*
  67577. ** Generate code for an IN expression.
  67578. **
  67579. ** x IN (SELECT ...)
  67580. ** x IN (value, value, ...)
  67581. **
  67582. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  67583. ** is an array of zero or more values. The expression is true if the LHS is
  67584. ** contained within the RHS. The value of the expression is unknown (NULL)
  67585. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  67586. ** RHS contains one or more NULL values.
  67587. **
  67588. ** This routine generates code will jump to destIfFalse if the LHS is not
  67589. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  67590. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  67591. ** within the RHS then fall through.
  67592. */
  67593. static void sqlite3ExprCodeIN(
  67594. Parse *pParse, /* Parsing and code generating context */
  67595. Expr *pExpr, /* The IN expression */
  67596. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  67597. int destIfNull /* Jump here if the results are unknown due to NULLs */
  67598. ){
  67599. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  67600. char affinity; /* Comparison affinity to use */
  67601. int eType; /* Type of the RHS */
  67602. int r1; /* Temporary use register */
  67603. Vdbe *v; /* Statement under construction */
  67604. /* Compute the RHS. After this step, the table with cursor
  67605. ** pExpr->iTable will contains the values that make up the RHS.
  67606. */
  67607. v = pParse->pVdbe;
  67608. assert( v!=0 ); /* OOM detected prior to this routine */
  67609. VdbeNoopComment((v, "begin IN expr"));
  67610. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  67611. /* Figure out the affinity to use to create a key from the results
  67612. ** of the expression. affinityStr stores a static string suitable for
  67613. ** P4 of OP_MakeRecord.
  67614. */
  67615. affinity = comparisonAffinity(pExpr);
  67616. /* Code the LHS, the <expr> from "<expr> IN (...)".
  67617. */
  67618. sqlite3ExprCachePush(pParse);
  67619. r1 = sqlite3GetTempReg(pParse);
  67620. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  67621. /* If the LHS is NULL, then the result is either false or NULL depending
  67622. ** on whether the RHS is empty or not, respectively.
  67623. */
  67624. if( destIfNull==destIfFalse ){
  67625. /* Shortcut for the common case where the false and NULL outcomes are
  67626. ** the same. */
  67627. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  67628. }else{
  67629. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  67630. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  67631. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  67632. sqlite3VdbeJumpHere(v, addr1);
  67633. }
  67634. if( eType==IN_INDEX_ROWID ){
  67635. /* In this case, the RHS is the ROWID of table b-tree
  67636. */
  67637. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  67638. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  67639. }else{
  67640. /* In this case, the RHS is an index b-tree.
  67641. */
  67642. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  67643. /* If the set membership test fails, then the result of the
  67644. ** "x IN (...)" expression must be either 0 or NULL. If the set
  67645. ** contains no NULL values, then the result is 0. If the set
  67646. ** contains one or more NULL values, then the result of the
  67647. ** expression is also NULL.
  67648. */
  67649. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  67650. /* This branch runs if it is known at compile time that the RHS
  67651. ** cannot contain NULL values. This happens as the result
  67652. ** of a "NOT NULL" constraint in the database schema.
  67653. **
  67654. ** Also run this branch if NULL is equivalent to FALSE
  67655. ** for this particular IN operator.
  67656. */
  67657. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  67658. }else{
  67659. /* In this branch, the RHS of the IN might contain a NULL and
  67660. ** the presence of a NULL on the RHS makes a difference in the
  67661. ** outcome.
  67662. */
  67663. int j1, j2, j3;
  67664. /* First check to see if the LHS is contained in the RHS. If so,
  67665. ** then the presence of NULLs in the RHS does not matter, so jump
  67666. ** over all of the code that follows.
  67667. */
  67668. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  67669. /* Here we begin generating code that runs if the LHS is not
  67670. ** contained within the RHS. Generate additional code that
  67671. ** tests the RHS for NULLs. If the RHS contains a NULL then
  67672. ** jump to destIfNull. If there are no NULLs in the RHS then
  67673. ** jump to destIfFalse.
  67674. */
  67675. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  67676. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  67677. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  67678. sqlite3VdbeJumpHere(v, j3);
  67679. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  67680. sqlite3VdbeJumpHere(v, j2);
  67681. /* Jump to the appropriate target depending on whether or not
  67682. ** the RHS contains a NULL
  67683. */
  67684. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  67685. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  67686. /* The OP_Found at the top of this branch jumps here when true,
  67687. ** causing the overall IN expression evaluation to fall through.
  67688. */
  67689. sqlite3VdbeJumpHere(v, j1);
  67690. }
  67691. }
  67692. sqlite3ReleaseTempReg(pParse, r1);
  67693. sqlite3ExprCachePop(pParse, 1);
  67694. VdbeComment((v, "end IN expr"));
  67695. }
  67696. #endif /* SQLITE_OMIT_SUBQUERY */
  67697. /*
  67698. ** Duplicate an 8-byte value
  67699. */
  67700. static char *dup8bytes(Vdbe *v, const char *in){
  67701. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  67702. if( out ){
  67703. memcpy(out, in, 8);
  67704. }
  67705. return out;
  67706. }
  67707. #ifndef SQLITE_OMIT_FLOATING_POINT
  67708. /*
  67709. ** Generate an instruction that will put the floating point
  67710. ** value described by z[0..n-1] into register iMem.
  67711. **
  67712. ** The z[] string will probably not be zero-terminated. But the
  67713. ** z[n] character is guaranteed to be something that does not look
  67714. ** like the continuation of the number.
  67715. */
  67716. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  67717. if( ALWAYS(z!=0) ){
  67718. double value;
  67719. char *zV;
  67720. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  67721. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  67722. if( negateFlag ) value = -value;
  67723. zV = dup8bytes(v, (char*)&value);
  67724. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  67725. }
  67726. }
  67727. #endif
  67728. /*
  67729. ** Generate an instruction that will put the integer describe by
  67730. ** text z[0..n-1] into register iMem.
  67731. **
  67732. ** Expr.u.zToken is always UTF8 and zero-terminated.
  67733. */
  67734. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  67735. Vdbe *v = pParse->pVdbe;
  67736. if( pExpr->flags & EP_IntValue ){
  67737. int i = pExpr->u.iValue;
  67738. assert( i>=0 );
  67739. if( negFlag ) i = -i;
  67740. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  67741. }else{
  67742. int c;
  67743. i64 value;
  67744. const char *z = pExpr->u.zToken;
  67745. assert( z!=0 );
  67746. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  67747. if( c==0 || (c==2 && negFlag) ){
  67748. char *zV;
  67749. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  67750. zV = dup8bytes(v, (char*)&value);
  67751. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  67752. }else{
  67753. #ifdef SQLITE_OMIT_FLOATING_POINT
  67754. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  67755. #else
  67756. codeReal(v, z, negFlag, iMem);
  67757. #endif
  67758. }
  67759. }
  67760. }
  67761. /*
  67762. ** Clear a cache entry.
  67763. */
  67764. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  67765. if( p->tempReg ){
  67766. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  67767. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  67768. }
  67769. p->tempReg = 0;
  67770. }
  67771. }
  67772. /*
  67773. ** Record in the column cache that a particular column from a
  67774. ** particular table is stored in a particular register.
  67775. */
  67776. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  67777. int i;
  67778. int minLru;
  67779. int idxLru;
  67780. struct yColCache *p;
  67781. assert( iReg>0 ); /* Register numbers are always positive */
  67782. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  67783. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  67784. ** for testing only - to verify that SQLite always gets the same answer
  67785. ** with and without the column cache.
  67786. */
  67787. if( pParse->db->flags & SQLITE_ColumnCache ) return;
  67788. /* First replace any existing entry.
  67789. **
  67790. ** Actually, the way the column cache is currently used, we are guaranteed
  67791. ** that the object will never already be in cache. Verify this guarantee.
  67792. */
  67793. #ifndef NDEBUG
  67794. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67795. #if 0 /* This code wold remove the entry from the cache if it existed */
  67796. if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
  67797. cacheEntryClear(pParse, p);
  67798. p->iLevel = pParse->iCacheLevel;
  67799. p->iReg = iReg;
  67800. p->lru = pParse->iCacheCnt++;
  67801. return;
  67802. }
  67803. #endif
  67804. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  67805. }
  67806. #endif
  67807. /* Find an empty slot and replace it */
  67808. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67809. if( p->iReg==0 ){
  67810. p->iLevel = pParse->iCacheLevel;
  67811. p->iTable = iTab;
  67812. p->iColumn = iCol;
  67813. p->iReg = iReg;
  67814. p->tempReg = 0;
  67815. p->lru = pParse->iCacheCnt++;
  67816. return;
  67817. }
  67818. }
  67819. /* Replace the last recently used */
  67820. minLru = 0x7fffffff;
  67821. idxLru = -1;
  67822. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67823. if( p->lru<minLru ){
  67824. idxLru = i;
  67825. minLru = p->lru;
  67826. }
  67827. }
  67828. if( ALWAYS(idxLru>=0) ){
  67829. p = &pParse->aColCache[idxLru];
  67830. p->iLevel = pParse->iCacheLevel;
  67831. p->iTable = iTab;
  67832. p->iColumn = iCol;
  67833. p->iReg = iReg;
  67834. p->tempReg = 0;
  67835. p->lru = pParse->iCacheCnt++;
  67836. return;
  67837. }
  67838. }
  67839. /*
  67840. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  67841. ** Purge the range of registers from the column cache.
  67842. */
  67843. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  67844. int i;
  67845. int iLast = iReg + nReg - 1;
  67846. struct yColCache *p;
  67847. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67848. int r = p->iReg;
  67849. if( r>=iReg && r<=iLast ){
  67850. cacheEntryClear(pParse, p);
  67851. p->iReg = 0;
  67852. }
  67853. }
  67854. }
  67855. /*
  67856. ** Remember the current column cache context. Any new entries added
  67857. ** added to the column cache after this call are removed when the
  67858. ** corresponding pop occurs.
  67859. */
  67860. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  67861. pParse->iCacheLevel++;
  67862. }
  67863. /*
  67864. ** Remove from the column cache any entries that were added since the
  67865. ** the previous N Push operations. In other words, restore the cache
  67866. ** to the state it was in N Pushes ago.
  67867. */
  67868. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
  67869. int i;
  67870. struct yColCache *p;
  67871. assert( N>0 );
  67872. assert( pParse->iCacheLevel>=N );
  67873. pParse->iCacheLevel -= N;
  67874. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67875. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  67876. cacheEntryClear(pParse, p);
  67877. p->iReg = 0;
  67878. }
  67879. }
  67880. }
  67881. /*
  67882. ** When a cached column is reused, make sure that its register is
  67883. ** no longer available as a temp register. ticket #3879: that same
  67884. ** register might be in the cache in multiple places, so be sure to
  67885. ** get them all.
  67886. */
  67887. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  67888. int i;
  67889. struct yColCache *p;
  67890. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67891. if( p->iReg==iReg ){
  67892. p->tempReg = 0;
  67893. }
  67894. }
  67895. }
  67896. /*
  67897. ** Generate code to extract the value of the iCol-th column of a table.
  67898. */
  67899. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  67900. Vdbe *v, /* The VDBE under construction */
  67901. Table *pTab, /* The table containing the value */
  67902. int iTabCur, /* The cursor for this table */
  67903. int iCol, /* Index of the column to extract */
  67904. int regOut /* Extract the valud into this register */
  67905. ){
  67906. if( iCol<0 || iCol==pTab->iPKey ){
  67907. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  67908. }else{
  67909. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  67910. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  67911. }
  67912. if( iCol>=0 ){
  67913. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  67914. }
  67915. }
  67916. /*
  67917. ** Generate code that will extract the iColumn-th column from
  67918. ** table pTab and store the column value in a register. An effort
  67919. ** is made to store the column value in register iReg, but this is
  67920. ** not guaranteed. The location of the column value is returned.
  67921. **
  67922. ** There must be an open cursor to pTab in iTable when this routine
  67923. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  67924. */
  67925. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  67926. Parse *pParse, /* Parsing and code generating context */
  67927. Table *pTab, /* Description of the table we are reading from */
  67928. int iColumn, /* Index of the table column */
  67929. int iTable, /* The cursor pointing to the table */
  67930. int iReg /* Store results here */
  67931. ){
  67932. Vdbe *v = pParse->pVdbe;
  67933. int i;
  67934. struct yColCache *p;
  67935. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67936. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  67937. p->lru = pParse->iCacheCnt++;
  67938. sqlite3ExprCachePinRegister(pParse, p->iReg);
  67939. return p->iReg;
  67940. }
  67941. }
  67942. assert( v!=0 );
  67943. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  67944. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  67945. return iReg;
  67946. }
  67947. /*
  67948. ** Clear all column cache entries.
  67949. */
  67950. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  67951. int i;
  67952. struct yColCache *p;
  67953. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67954. if( p->iReg ){
  67955. cacheEntryClear(pParse, p);
  67956. p->iReg = 0;
  67957. }
  67958. }
  67959. }
  67960. /*
  67961. ** Record the fact that an affinity change has occurred on iCount
  67962. ** registers starting with iStart.
  67963. */
  67964. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  67965. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  67966. }
  67967. /*
  67968. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  67969. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  67970. */
  67971. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  67972. int i;
  67973. struct yColCache *p;
  67974. if( NEVER(iFrom==iTo) ) return;
  67975. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  67976. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  67977. int x = p->iReg;
  67978. if( x>=iFrom && x<iFrom+nReg ){
  67979. p->iReg += iTo-iFrom;
  67980. }
  67981. }
  67982. }
  67983. /*
  67984. ** Generate code to copy content from registers iFrom...iFrom+nReg-1
  67985. ** over to iTo..iTo+nReg-1.
  67986. */
  67987. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
  67988. int i;
  67989. if( NEVER(iFrom==iTo) ) return;
  67990. for(i=0; i<nReg; i++){
  67991. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
  67992. }
  67993. }
  67994. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  67995. /*
  67996. ** Return true if any register in the range iFrom..iTo (inclusive)
  67997. ** is used as part of the column cache.
  67998. **
  67999. ** This routine is used within assert() and testcase() macros only
  68000. ** and does not appear in a normal build.
  68001. */
  68002. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  68003. int i;
  68004. struct yColCache *p;
  68005. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  68006. int r = p->iReg;
  68007. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  68008. }
  68009. return 0;
  68010. }
  68011. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  68012. /*
  68013. ** Generate code into the current Vdbe to evaluate the given
  68014. ** expression. Attempt to store the results in register "target".
  68015. ** Return the register where results are stored.
  68016. **
  68017. ** With this routine, there is no guarantee that results will
  68018. ** be stored in target. The result might be stored in some other
  68019. ** register if it is convenient to do so. The calling function
  68020. ** must check the return code and move the results to the desired
  68021. ** register.
  68022. */
  68023. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  68024. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  68025. int op; /* The opcode being coded */
  68026. int inReg = target; /* Results stored in register inReg */
  68027. int regFree1 = 0; /* If non-zero free this temporary register */
  68028. int regFree2 = 0; /* If non-zero free this temporary register */
  68029. int r1, r2, r3, r4; /* Various register numbers */
  68030. sqlite3 *db = pParse->db; /* The database connection */
  68031. assert( target>0 && target<=pParse->nMem );
  68032. if( v==0 ){
  68033. assert( pParse->db->mallocFailed );
  68034. return 0;
  68035. }
  68036. if( pExpr==0 ){
  68037. op = TK_NULL;
  68038. }else{
  68039. op = pExpr->op;
  68040. }
  68041. switch( op ){
  68042. case TK_AGG_COLUMN: {
  68043. AggInfo *pAggInfo = pExpr->pAggInfo;
  68044. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  68045. if( !pAggInfo->directMode ){
  68046. assert( pCol->iMem>0 );
  68047. inReg = pCol->iMem;
  68048. break;
  68049. }else if( pAggInfo->useSortingIdx ){
  68050. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
  68051. pCol->iSorterColumn, target);
  68052. break;
  68053. }
  68054. /* Otherwise, fall thru into the TK_COLUMN case */
  68055. }
  68056. case TK_COLUMN: {
  68057. if( pExpr->iTable<0 ){
  68058. /* This only happens when coding check constraints */
  68059. assert( pParse->ckBase>0 );
  68060. inReg = pExpr->iColumn + pParse->ckBase;
  68061. }else{
  68062. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  68063. pExpr->iColumn, pExpr->iTable, target);
  68064. }
  68065. break;
  68066. }
  68067. case TK_INTEGER: {
  68068. codeInteger(pParse, pExpr, 0, target);
  68069. break;
  68070. }
  68071. #ifndef SQLITE_OMIT_FLOATING_POINT
  68072. case TK_FLOAT: {
  68073. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68074. codeReal(v, pExpr->u.zToken, 0, target);
  68075. break;
  68076. }
  68077. #endif
  68078. case TK_STRING: {
  68079. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68080. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  68081. break;
  68082. }
  68083. case TK_NULL: {
  68084. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  68085. break;
  68086. }
  68087. #ifndef SQLITE_OMIT_BLOB_LITERAL
  68088. case TK_BLOB: {
  68089. int n;
  68090. const char *z;
  68091. char *zBlob;
  68092. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68093. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  68094. assert( pExpr->u.zToken[1]=='\'' );
  68095. z = &pExpr->u.zToken[2];
  68096. n = sqlite3Strlen30(z) - 1;
  68097. assert( z[n]=='\'' );
  68098. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  68099. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  68100. break;
  68101. }
  68102. #endif
  68103. case TK_VARIABLE: {
  68104. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68105. assert( pExpr->u.zToken!=0 );
  68106. assert( pExpr->u.zToken[0]!=0 );
  68107. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  68108. if( pExpr->u.zToken[1]!=0 ){
  68109. sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, P4_TRANSIENT);
  68110. }
  68111. break;
  68112. }
  68113. case TK_REGISTER: {
  68114. inReg = pExpr->iTable;
  68115. break;
  68116. }
  68117. case TK_AS: {
  68118. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  68119. break;
  68120. }
  68121. #ifndef SQLITE_OMIT_CAST
  68122. case TK_CAST: {
  68123. /* Expressions of the form: CAST(pLeft AS token) */
  68124. int aff, to_op;
  68125. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  68126. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68127. aff = sqlite3AffinityType(pExpr->u.zToken);
  68128. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  68129. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  68130. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  68131. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  68132. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  68133. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  68134. testcase( to_op==OP_ToText );
  68135. testcase( to_op==OP_ToBlob );
  68136. testcase( to_op==OP_ToNumeric );
  68137. testcase( to_op==OP_ToInt );
  68138. testcase( to_op==OP_ToReal );
  68139. if( inReg!=target ){
  68140. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  68141. inReg = target;
  68142. }
  68143. sqlite3VdbeAddOp1(v, to_op, inReg);
  68144. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  68145. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  68146. break;
  68147. }
  68148. #endif /* SQLITE_OMIT_CAST */
  68149. case TK_LT:
  68150. case TK_LE:
  68151. case TK_GT:
  68152. case TK_GE:
  68153. case TK_NE:
  68154. case TK_EQ: {
  68155. assert( TK_LT==OP_Lt );
  68156. assert( TK_LE==OP_Le );
  68157. assert( TK_GT==OP_Gt );
  68158. assert( TK_GE==OP_Ge );
  68159. assert( TK_EQ==OP_Eq );
  68160. assert( TK_NE==OP_Ne );
  68161. testcase( op==TK_LT );
  68162. testcase( op==TK_LE );
  68163. testcase( op==TK_GT );
  68164. testcase( op==TK_GE );
  68165. testcase( op==TK_EQ );
  68166. testcase( op==TK_NE );
  68167. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  68168. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  68169. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  68170. r1, r2, inReg, SQLITE_STOREP2);
  68171. testcase( regFree1==0 );
  68172. testcase( regFree2==0 );
  68173. break;
  68174. }
  68175. case TK_IS:
  68176. case TK_ISNOT: {
  68177. testcase( op==TK_IS );
  68178. testcase( op==TK_ISNOT );
  68179. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  68180. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  68181. op = (op==TK_IS) ? TK_EQ : TK_NE;
  68182. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  68183. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  68184. testcase( regFree1==0 );
  68185. testcase( regFree2==0 );
  68186. break;
  68187. }
  68188. case TK_AND:
  68189. case TK_OR:
  68190. case TK_PLUS:
  68191. case TK_STAR:
  68192. case TK_MINUS:
  68193. case TK_REM:
  68194. case TK_BITAND:
  68195. case TK_BITOR:
  68196. case TK_SLASH:
  68197. case TK_LSHIFT:
  68198. case TK_RSHIFT:
  68199. case TK_CONCAT: {
  68200. assert( TK_AND==OP_And );
  68201. assert( TK_OR==OP_Or );
  68202. assert( TK_PLUS==OP_Add );
  68203. assert( TK_MINUS==OP_Subtract );
  68204. assert( TK_REM==OP_Remainder );
  68205. assert( TK_BITAND==OP_BitAnd );
  68206. assert( TK_BITOR==OP_BitOr );
  68207. assert( TK_SLASH==OP_Divide );
  68208. assert( TK_LSHIFT==OP_ShiftLeft );
  68209. assert( TK_RSHIFT==OP_ShiftRight );
  68210. assert( TK_CONCAT==OP_Concat );
  68211. testcase( op==TK_AND );
  68212. testcase( op==TK_OR );
  68213. testcase( op==TK_PLUS );
  68214. testcase( op==TK_MINUS );
  68215. testcase( op==TK_REM );
  68216. testcase( op==TK_BITAND );
  68217. testcase( op==TK_BITOR );
  68218. testcase( op==TK_SLASH );
  68219. testcase( op==TK_LSHIFT );
  68220. testcase( op==TK_RSHIFT );
  68221. testcase( op==TK_CONCAT );
  68222. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  68223. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  68224. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  68225. testcase( regFree1==0 );
  68226. testcase( regFree2==0 );
  68227. break;
  68228. }
  68229. case TK_UMINUS: {
  68230. Expr *pLeft = pExpr->pLeft;
  68231. assert( pLeft );
  68232. if( pLeft->op==TK_INTEGER ){
  68233. codeInteger(pParse, pLeft, 1, target);
  68234. #ifndef SQLITE_OMIT_FLOATING_POINT
  68235. }else if( pLeft->op==TK_FLOAT ){
  68236. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68237. codeReal(v, pLeft->u.zToken, 1, target);
  68238. #endif
  68239. }else{
  68240. regFree1 = r1 = sqlite3GetTempReg(pParse);
  68241. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  68242. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  68243. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  68244. testcase( regFree2==0 );
  68245. }
  68246. inReg = target;
  68247. break;
  68248. }
  68249. case TK_BITNOT:
  68250. case TK_NOT: {
  68251. assert( TK_BITNOT==OP_BitNot );
  68252. assert( TK_NOT==OP_Not );
  68253. testcase( op==TK_BITNOT );
  68254. testcase( op==TK_NOT );
  68255. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  68256. testcase( regFree1==0 );
  68257. inReg = target;
  68258. sqlite3VdbeAddOp2(v, op, r1, inReg);
  68259. break;
  68260. }
  68261. case TK_ISNULL:
  68262. case TK_NOTNULL: {
  68263. int addr;
  68264. assert( TK_ISNULL==OP_IsNull );
  68265. assert( TK_NOTNULL==OP_NotNull );
  68266. testcase( op==TK_ISNULL );
  68267. testcase( op==TK_NOTNULL );
  68268. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  68269. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  68270. testcase( regFree1==0 );
  68271. addr = sqlite3VdbeAddOp1(v, op, r1);
  68272. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  68273. sqlite3VdbeJumpHere(v, addr);
  68274. break;
  68275. }
  68276. case TK_AGG_FUNCTION: {
  68277. AggInfo *pInfo = pExpr->pAggInfo;
  68278. if( pInfo==0 ){
  68279. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68280. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  68281. }else{
  68282. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  68283. }
  68284. break;
  68285. }
  68286. case TK_CONST_FUNC:
  68287. case TK_FUNCTION: {
  68288. ExprList *pFarg; /* List of function arguments */
  68289. int nFarg; /* Number of function arguments */
  68290. FuncDef *pDef; /* The function definition object */
  68291. int nId; /* Length of the function name in bytes */
  68292. const char *zId; /* The function name */
  68293. int constMask = 0; /* Mask of function arguments that are constant */
  68294. int i; /* Loop counter */
  68295. u8 enc = ENC(db); /* The text encoding used by this database */
  68296. CollSeq *pColl = 0; /* A collating sequence */
  68297. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  68298. testcase( op==TK_CONST_FUNC );
  68299. testcase( op==TK_FUNCTION );
  68300. if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
  68301. pFarg = 0;
  68302. }else{
  68303. pFarg = pExpr->x.pList;
  68304. }
  68305. nFarg = pFarg ? pFarg->nExpr : 0;
  68306. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68307. zId = pExpr->u.zToken;
  68308. nId = sqlite3Strlen30(zId);
  68309. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  68310. if( pDef==0 ){
  68311. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  68312. break;
  68313. }
  68314. /* Attempt a direct implementation of the built-in COALESCE() and
  68315. ** IFNULL() functions. This avoids unnecessary evalation of
  68316. ** arguments past the first non-NULL argument.
  68317. */
  68318. if( pDef->flags & SQLITE_FUNC_COALESCE ){
  68319. int endCoalesce = sqlite3VdbeMakeLabel(v);
  68320. assert( nFarg>=2 );
  68321. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  68322. for(i=1; i<nFarg; i++){
  68323. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  68324. sqlite3ExprCacheRemove(pParse, target, 1);
  68325. sqlite3ExprCachePush(pParse);
  68326. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  68327. sqlite3ExprCachePop(pParse, 1);
  68328. }
  68329. sqlite3VdbeResolveLabel(v, endCoalesce);
  68330. break;
  68331. }
  68332. if( pFarg ){
  68333. r1 = sqlite3GetTempRange(pParse, nFarg);
  68334. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  68335. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  68336. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  68337. }else{
  68338. r1 = 0;
  68339. }
  68340. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68341. /* Possibly overload the function if the first argument is
  68342. ** a virtual table column.
  68343. **
  68344. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  68345. ** second argument, not the first, as the argument to test to
  68346. ** see if it is a column in a virtual table. This is done because
  68347. ** the left operand of infix functions (the operand we want to
  68348. ** control overloading) ends up as the second argument to the
  68349. ** function. The expression "A glob B" is equivalent to
  68350. ** "glob(B,A). We want to use the A in "A glob B" to test
  68351. ** for function overloading. But we use the B term in "glob(B,A)".
  68352. */
  68353. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  68354. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  68355. }else if( nFarg>0 ){
  68356. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  68357. }
  68358. #endif
  68359. for(i=0; i<nFarg; i++){
  68360. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  68361. constMask |= (1<<i);
  68362. }
  68363. if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  68364. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  68365. }
  68366. }
  68367. if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
  68368. if( !pColl ) pColl = db->pDfltColl;
  68369. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  68370. }
  68371. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  68372. (char*)pDef, P4_FUNCDEF);
  68373. sqlite3VdbeChangeP5(v, (u8)nFarg);
  68374. if( nFarg ){
  68375. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  68376. }
  68377. break;
  68378. }
  68379. #ifndef SQLITE_OMIT_SUBQUERY
  68380. case TK_EXISTS:
  68381. case TK_SELECT: {
  68382. testcase( op==TK_EXISTS );
  68383. testcase( op==TK_SELECT );
  68384. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  68385. break;
  68386. }
  68387. case TK_IN: {
  68388. int destIfFalse = sqlite3VdbeMakeLabel(v);
  68389. int destIfNull = sqlite3VdbeMakeLabel(v);
  68390. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  68391. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  68392. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  68393. sqlite3VdbeResolveLabel(v, destIfFalse);
  68394. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  68395. sqlite3VdbeResolveLabel(v, destIfNull);
  68396. break;
  68397. }
  68398. #endif /* SQLITE_OMIT_SUBQUERY */
  68399. /*
  68400. ** x BETWEEN y AND z
  68401. **
  68402. ** This is equivalent to
  68403. **
  68404. ** x>=y AND x<=z
  68405. **
  68406. ** X is stored in pExpr->pLeft.
  68407. ** Y is stored in pExpr->pList->a[0].pExpr.
  68408. ** Z is stored in pExpr->pList->a[1].pExpr.
  68409. */
  68410. case TK_BETWEEN: {
  68411. Expr *pLeft = pExpr->pLeft;
  68412. struct ExprList_item *pLItem = pExpr->x.pList->a;
  68413. Expr *pRight = pLItem->pExpr;
  68414. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  68415. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  68416. testcase( regFree1==0 );
  68417. testcase( regFree2==0 );
  68418. r3 = sqlite3GetTempReg(pParse);
  68419. r4 = sqlite3GetTempReg(pParse);
  68420. codeCompare(pParse, pLeft, pRight, OP_Ge,
  68421. r1, r2, r3, SQLITE_STOREP2);
  68422. pLItem++;
  68423. pRight = pLItem->pExpr;
  68424. sqlite3ReleaseTempReg(pParse, regFree2);
  68425. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  68426. testcase( regFree2==0 );
  68427. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  68428. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  68429. sqlite3ReleaseTempReg(pParse, r3);
  68430. sqlite3ReleaseTempReg(pParse, r4);
  68431. break;
  68432. }
  68433. case TK_UPLUS: {
  68434. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  68435. break;
  68436. }
  68437. case TK_TRIGGER: {
  68438. /* If the opcode is TK_TRIGGER, then the expression is a reference
  68439. ** to a column in the new.* or old.* pseudo-tables available to
  68440. ** trigger programs. In this case Expr.iTable is set to 1 for the
  68441. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  68442. ** is set to the column of the pseudo-table to read, or to -1 to
  68443. ** read the rowid field.
  68444. **
  68445. ** The expression is implemented using an OP_Param opcode. The p1
  68446. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  68447. ** to reference another column of the old.* pseudo-table, where
  68448. ** i is the index of the column. For a new.rowid reference, p1 is
  68449. ** set to (n+1), where n is the number of columns in each pseudo-table.
  68450. ** For a reference to any other column in the new.* pseudo-table, p1
  68451. ** is set to (n+2+i), where n and i are as defined previously. For
  68452. ** example, if the table on which triggers are being fired is
  68453. ** declared as:
  68454. **
  68455. ** CREATE TABLE t1(a, b);
  68456. **
  68457. ** Then p1 is interpreted as follows:
  68458. **
  68459. ** p1==0 -> old.rowid p1==3 -> new.rowid
  68460. ** p1==1 -> old.a p1==4 -> new.a
  68461. ** p1==2 -> old.b p1==5 -> new.b
  68462. */
  68463. Table *pTab = pExpr->pTab;
  68464. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  68465. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  68466. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  68467. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  68468. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  68469. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  68470. VdbeComment((v, "%s.%s -> $%d",
  68471. (pExpr->iTable ? "new" : "old"),
  68472. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  68473. target
  68474. ));
  68475. #ifndef SQLITE_OMIT_FLOATING_POINT
  68476. /* If the column has REAL affinity, it may currently be stored as an
  68477. ** integer. Use OP_RealAffinity to make sure it is really real. */
  68478. if( pExpr->iColumn>=0
  68479. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  68480. ){
  68481. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  68482. }
  68483. #endif
  68484. break;
  68485. }
  68486. /*
  68487. ** Form A:
  68488. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  68489. **
  68490. ** Form B:
  68491. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  68492. **
  68493. ** Form A is can be transformed into the equivalent form B as follows:
  68494. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  68495. ** WHEN x=eN THEN rN ELSE y END
  68496. **
  68497. ** X (if it exists) is in pExpr->pLeft.
  68498. ** Y is in pExpr->pRight. The Y is also optional. If there is no
  68499. ** ELSE clause and no other term matches, then the result of the
  68500. ** exprssion is NULL.
  68501. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  68502. **
  68503. ** The result of the expression is the Ri for the first matching Ei,
  68504. ** or if there is no matching Ei, the ELSE term Y, or if there is
  68505. ** no ELSE term, NULL.
  68506. */
  68507. default: assert( op==TK_CASE ); {
  68508. int endLabel; /* GOTO label for end of CASE stmt */
  68509. int nextCase; /* GOTO label for next WHEN clause */
  68510. int nExpr; /* 2x number of WHEN terms */
  68511. int i; /* Loop counter */
  68512. ExprList *pEList; /* List of WHEN terms */
  68513. struct ExprList_item *aListelem; /* Array of WHEN terms */
  68514. Expr opCompare; /* The X==Ei expression */
  68515. Expr cacheX; /* Cached expression X */
  68516. Expr *pX; /* The X expression */
  68517. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  68518. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  68519. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  68520. assert((pExpr->x.pList->nExpr % 2) == 0);
  68521. assert(pExpr->x.pList->nExpr > 0);
  68522. pEList = pExpr->x.pList;
  68523. aListelem = pEList->a;
  68524. nExpr = pEList->nExpr;
  68525. endLabel = sqlite3VdbeMakeLabel(v);
  68526. if( (pX = pExpr->pLeft)!=0 ){
  68527. cacheX = *pX;
  68528. testcase( pX->op==TK_COLUMN );
  68529. testcase( pX->op==TK_REGISTER );
  68530. cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
  68531. testcase( regFree1==0 );
  68532. cacheX.op = TK_REGISTER;
  68533. opCompare.op = TK_EQ;
  68534. opCompare.pLeft = &cacheX;
  68535. pTest = &opCompare;
  68536. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  68537. ** The value in regFree1 might get SCopy-ed into the file result.
  68538. ** So make sure that the regFree1 register is not reused for other
  68539. ** purposes and possibly overwritten. */
  68540. regFree1 = 0;
  68541. }
  68542. for(i=0; i<nExpr; i=i+2){
  68543. sqlite3ExprCachePush(pParse);
  68544. if( pX ){
  68545. assert( pTest!=0 );
  68546. opCompare.pRight = aListelem[i].pExpr;
  68547. }else{
  68548. pTest = aListelem[i].pExpr;
  68549. }
  68550. nextCase = sqlite3VdbeMakeLabel(v);
  68551. testcase( pTest->op==TK_COLUMN );
  68552. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  68553. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  68554. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  68555. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  68556. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  68557. sqlite3ExprCachePop(pParse, 1);
  68558. sqlite3VdbeResolveLabel(v, nextCase);
  68559. }
  68560. if( pExpr->pRight ){
  68561. sqlite3ExprCachePush(pParse);
  68562. sqlite3ExprCode(pParse, pExpr->pRight, target);
  68563. sqlite3ExprCachePop(pParse, 1);
  68564. }else{
  68565. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  68566. }
  68567. assert( db->mallocFailed || pParse->nErr>0
  68568. || pParse->iCacheLevel==iCacheLevel );
  68569. sqlite3VdbeResolveLabel(v, endLabel);
  68570. break;
  68571. }
  68572. #ifndef SQLITE_OMIT_TRIGGER
  68573. case TK_RAISE: {
  68574. assert( pExpr->affinity==OE_Rollback
  68575. || pExpr->affinity==OE_Abort
  68576. || pExpr->affinity==OE_Fail
  68577. || pExpr->affinity==OE_Ignore
  68578. );
  68579. if( !pParse->pTriggerTab ){
  68580. sqlite3ErrorMsg(pParse,
  68581. "RAISE() may only be used within a trigger-program");
  68582. return 0;
  68583. }
  68584. if( pExpr->affinity==OE_Abort ){
  68585. sqlite3MayAbort(pParse);
  68586. }
  68587. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  68588. if( pExpr->affinity==OE_Ignore ){
  68589. sqlite3VdbeAddOp4(
  68590. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  68591. }else{
  68592. sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
  68593. }
  68594. break;
  68595. }
  68596. #endif
  68597. }
  68598. sqlite3ReleaseTempReg(pParse, regFree1);
  68599. sqlite3ReleaseTempReg(pParse, regFree2);
  68600. return inReg;
  68601. }
  68602. /*
  68603. ** Generate code to evaluate an expression and store the results
  68604. ** into a register. Return the register number where the results
  68605. ** are stored.
  68606. **
  68607. ** If the register is a temporary register that can be deallocated,
  68608. ** then write its number into *pReg. If the result register is not
  68609. ** a temporary, then set *pReg to zero.
  68610. */
  68611. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  68612. int r1 = sqlite3GetTempReg(pParse);
  68613. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  68614. if( r2==r1 ){
  68615. *pReg = r1;
  68616. }else{
  68617. sqlite3ReleaseTempReg(pParse, r1);
  68618. *pReg = 0;
  68619. }
  68620. return r2;
  68621. }
  68622. /*
  68623. ** Generate code that will evaluate expression pExpr and store the
  68624. ** results in register target. The results are guaranteed to appear
  68625. ** in register target.
  68626. */
  68627. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  68628. int inReg;
  68629. assert( target>0 && target<=pParse->nMem );
  68630. if( pExpr && pExpr->op==TK_REGISTER ){
  68631. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  68632. }else{
  68633. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  68634. assert( pParse->pVdbe || pParse->db->mallocFailed );
  68635. if( inReg!=target && pParse->pVdbe ){
  68636. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  68637. }
  68638. }
  68639. return target;
  68640. }
  68641. /*
  68642. ** Generate code that evalutes the given expression and puts the result
  68643. ** in register target.
  68644. **
  68645. ** Also make a copy of the expression results into another "cache" register
  68646. ** and modify the expression so that the next time it is evaluated,
  68647. ** the result is a copy of the cache register.
  68648. **
  68649. ** This routine is used for expressions that are used multiple
  68650. ** times. They are evaluated once and the results of the expression
  68651. ** are reused.
  68652. */
  68653. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  68654. Vdbe *v = pParse->pVdbe;
  68655. int inReg;
  68656. inReg = sqlite3ExprCode(pParse, pExpr, target);
  68657. assert( target>0 );
  68658. /* This routine is called for terms to INSERT or UPDATE. And the only
  68659. ** other place where expressions can be converted into TK_REGISTER is
  68660. ** in WHERE clause processing. So as currently implemented, there is
  68661. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  68662. ** keep the ALWAYS() in case the conditions above change with future
  68663. ** modifications or enhancements. */
  68664. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  68665. int iMem;
  68666. iMem = ++pParse->nMem;
  68667. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  68668. pExpr->iTable = iMem;
  68669. pExpr->op2 = pExpr->op;
  68670. pExpr->op = TK_REGISTER;
  68671. }
  68672. return inReg;
  68673. }
  68674. /*
  68675. ** Return TRUE if pExpr is an constant expression that is appropriate
  68676. ** for factoring out of a loop. Appropriate expressions are:
  68677. **
  68678. ** * Any expression that evaluates to two or more opcodes.
  68679. **
  68680. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  68681. ** or OP_Variable that does not need to be placed in a
  68682. ** specific register.
  68683. **
  68684. ** There is no point in factoring out single-instruction constant
  68685. ** expressions that need to be placed in a particular register.
  68686. ** We could factor them out, but then we would end up adding an
  68687. ** OP_SCopy instruction to move the value into the correct register
  68688. ** later. We might as well just use the original instruction and
  68689. ** avoid the OP_SCopy.
  68690. */
  68691. static int isAppropriateForFactoring(Expr *p){
  68692. if( !sqlite3ExprIsConstantNotJoin(p) ){
  68693. return 0; /* Only constant expressions are appropriate for factoring */
  68694. }
  68695. if( (p->flags & EP_FixedDest)==0 ){
  68696. return 1; /* Any constant without a fixed destination is appropriate */
  68697. }
  68698. while( p->op==TK_UPLUS ) p = p->pLeft;
  68699. switch( p->op ){
  68700. #ifndef SQLITE_OMIT_BLOB_LITERAL
  68701. case TK_BLOB:
  68702. #endif
  68703. case TK_VARIABLE:
  68704. case TK_INTEGER:
  68705. case TK_FLOAT:
  68706. case TK_NULL:
  68707. case TK_STRING: {
  68708. testcase( p->op==TK_BLOB );
  68709. testcase( p->op==TK_VARIABLE );
  68710. testcase( p->op==TK_INTEGER );
  68711. testcase( p->op==TK_FLOAT );
  68712. testcase( p->op==TK_NULL );
  68713. testcase( p->op==TK_STRING );
  68714. /* Single-instruction constants with a fixed destination are
  68715. ** better done in-line. If we factor them, they will just end
  68716. ** up generating an OP_SCopy to move the value to the destination
  68717. ** register. */
  68718. return 0;
  68719. }
  68720. case TK_UMINUS: {
  68721. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  68722. return 0;
  68723. }
  68724. break;
  68725. }
  68726. default: {
  68727. break;
  68728. }
  68729. }
  68730. return 1;
  68731. }
  68732. /*
  68733. ** If pExpr is a constant expression that is appropriate for
  68734. ** factoring out of a loop, then evaluate the expression
  68735. ** into a register and convert the expression into a TK_REGISTER
  68736. ** expression.
  68737. */
  68738. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  68739. Parse *pParse = pWalker->pParse;
  68740. switch( pExpr->op ){
  68741. case TK_IN:
  68742. case TK_REGISTER: {
  68743. return WRC_Prune;
  68744. }
  68745. case TK_FUNCTION:
  68746. case TK_AGG_FUNCTION:
  68747. case TK_CONST_FUNC: {
  68748. /* The arguments to a function have a fixed destination.
  68749. ** Mark them this way to avoid generated unneeded OP_SCopy
  68750. ** instructions.
  68751. */
  68752. ExprList *pList = pExpr->x.pList;
  68753. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  68754. if( pList ){
  68755. int i = pList->nExpr;
  68756. struct ExprList_item *pItem = pList->a;
  68757. for(; i>0; i--, pItem++){
  68758. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  68759. }
  68760. }
  68761. break;
  68762. }
  68763. }
  68764. if( isAppropriateForFactoring(pExpr) ){
  68765. int r1 = ++pParse->nMem;
  68766. int r2;
  68767. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  68768. if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
  68769. pExpr->op2 = pExpr->op;
  68770. pExpr->op = TK_REGISTER;
  68771. pExpr->iTable = r2;
  68772. return WRC_Prune;
  68773. }
  68774. return WRC_Continue;
  68775. }
  68776. /*
  68777. ** Preevaluate constant subexpressions within pExpr and store the
  68778. ** results in registers. Modify pExpr so that the constant subexpresions
  68779. ** are TK_REGISTER opcodes that refer to the precomputed values.
  68780. **
  68781. ** This routine is a no-op if the jump to the cookie-check code has
  68782. ** already occur. Since the cookie-check jump is generated prior to
  68783. ** any other serious processing, this check ensures that there is no
  68784. ** way to accidently bypass the constant initializations.
  68785. **
  68786. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  68787. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  68788. ** interface. This allows test logic to verify that the same answer is
  68789. ** obtained for queries regardless of whether or not constants are
  68790. ** precomputed into registers or if they are inserted in-line.
  68791. */
  68792. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  68793. Walker w;
  68794. if( pParse->cookieGoto ) return;
  68795. if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
  68796. w.xExprCallback = evalConstExpr;
  68797. w.xSelectCallback = 0;
  68798. w.pParse = pParse;
  68799. sqlite3WalkExpr(&w, pExpr);
  68800. }
  68801. /*
  68802. ** Generate code that pushes the value of every element of the given
  68803. ** expression list into a sequence of registers beginning at target.
  68804. **
  68805. ** Return the number of elements evaluated.
  68806. */
  68807. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  68808. Parse *pParse, /* Parsing context */
  68809. ExprList *pList, /* The expression list to be coded */
  68810. int target, /* Where to write results */
  68811. int doHardCopy /* Make a hard copy of every element */
  68812. ){
  68813. struct ExprList_item *pItem;
  68814. int i, n;
  68815. assert( pList!=0 );
  68816. assert( target>0 );
  68817. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  68818. n = pList->nExpr;
  68819. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  68820. Expr *pExpr = pItem->pExpr;
  68821. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  68822. if( inReg!=target+i ){
  68823. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  68824. inReg, target+i);
  68825. }
  68826. }
  68827. return n;
  68828. }
  68829. /*
  68830. ** Generate code for a BETWEEN operator.
  68831. **
  68832. ** x BETWEEN y AND z
  68833. **
  68834. ** The above is equivalent to
  68835. **
  68836. ** x>=y AND x<=z
  68837. **
  68838. ** Code it as such, taking care to do the common subexpression
  68839. ** elementation of x.
  68840. */
  68841. static void exprCodeBetween(
  68842. Parse *pParse, /* Parsing and code generating context */
  68843. Expr *pExpr, /* The BETWEEN expression */
  68844. int dest, /* Jump here if the jump is taken */
  68845. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  68846. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  68847. ){
  68848. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  68849. Expr compLeft; /* The x>=y term */
  68850. Expr compRight; /* The x<=z term */
  68851. Expr exprX; /* The x subexpression */
  68852. int regFree1 = 0; /* Temporary use register */
  68853. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  68854. exprX = *pExpr->pLeft;
  68855. exprAnd.op = TK_AND;
  68856. exprAnd.pLeft = &compLeft;
  68857. exprAnd.pRight = &compRight;
  68858. compLeft.op = TK_GE;
  68859. compLeft.pLeft = &exprX;
  68860. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  68861. compRight.op = TK_LE;
  68862. compRight.pLeft = &exprX;
  68863. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  68864. exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
  68865. exprX.op = TK_REGISTER;
  68866. if( jumpIfTrue ){
  68867. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  68868. }else{
  68869. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  68870. }
  68871. sqlite3ReleaseTempReg(pParse, regFree1);
  68872. /* Ensure adequate test coverage */
  68873. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  68874. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  68875. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  68876. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  68877. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  68878. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  68879. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  68880. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  68881. }
  68882. /*
  68883. ** Generate code for a boolean expression such that a jump is made
  68884. ** to the label "dest" if the expression is true but execution
  68885. ** continues straight thru if the expression is false.
  68886. **
  68887. ** If the expression evaluates to NULL (neither true nor false), then
  68888. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  68889. **
  68890. ** This code depends on the fact that certain token values (ex: TK_EQ)
  68891. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  68892. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  68893. ** the make process cause these values to align. Assert()s in the code
  68894. ** below verify that the numbers are aligned correctly.
  68895. */
  68896. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  68897. Vdbe *v = pParse->pVdbe;
  68898. int op = 0;
  68899. int regFree1 = 0;
  68900. int regFree2 = 0;
  68901. int r1, r2;
  68902. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  68903. if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
  68904. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  68905. op = pExpr->op;
  68906. switch( op ){
  68907. case TK_AND: {
  68908. int d2 = sqlite3VdbeMakeLabel(v);
  68909. testcase( jumpIfNull==0 );
  68910. sqlite3ExprCachePush(pParse);
  68911. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  68912. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  68913. sqlite3VdbeResolveLabel(v, d2);
  68914. sqlite3ExprCachePop(pParse, 1);
  68915. break;
  68916. }
  68917. case TK_OR: {
  68918. testcase( jumpIfNull==0 );
  68919. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  68920. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  68921. break;
  68922. }
  68923. case TK_NOT: {
  68924. testcase( jumpIfNull==0 );
  68925. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  68926. break;
  68927. }
  68928. case TK_LT:
  68929. case TK_LE:
  68930. case TK_GT:
  68931. case TK_GE:
  68932. case TK_NE:
  68933. case TK_EQ: {
  68934. assert( TK_LT==OP_Lt );
  68935. assert( TK_LE==OP_Le );
  68936. assert( TK_GT==OP_Gt );
  68937. assert( TK_GE==OP_Ge );
  68938. assert( TK_EQ==OP_Eq );
  68939. assert( TK_NE==OP_Ne );
  68940. testcase( op==TK_LT );
  68941. testcase( op==TK_LE );
  68942. testcase( op==TK_GT );
  68943. testcase( op==TK_GE );
  68944. testcase( op==TK_EQ );
  68945. testcase( op==TK_NE );
  68946. testcase( jumpIfNull==0 );
  68947. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  68948. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  68949. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  68950. r1, r2, dest, jumpIfNull);
  68951. testcase( regFree1==0 );
  68952. testcase( regFree2==0 );
  68953. break;
  68954. }
  68955. case TK_IS:
  68956. case TK_ISNOT: {
  68957. testcase( op==TK_IS );
  68958. testcase( op==TK_ISNOT );
  68959. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  68960. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  68961. op = (op==TK_IS) ? TK_EQ : TK_NE;
  68962. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  68963. r1, r2, dest, SQLITE_NULLEQ);
  68964. testcase( regFree1==0 );
  68965. testcase( regFree2==0 );
  68966. break;
  68967. }
  68968. case TK_ISNULL:
  68969. case TK_NOTNULL: {
  68970. assert( TK_ISNULL==OP_IsNull );
  68971. assert( TK_NOTNULL==OP_NotNull );
  68972. testcase( op==TK_ISNULL );
  68973. testcase( op==TK_NOTNULL );
  68974. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  68975. sqlite3VdbeAddOp2(v, op, r1, dest);
  68976. testcase( regFree1==0 );
  68977. break;
  68978. }
  68979. case TK_BETWEEN: {
  68980. testcase( jumpIfNull==0 );
  68981. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  68982. break;
  68983. }
  68984. #ifndef SQLITE_OMIT_SUBQUERY
  68985. case TK_IN: {
  68986. int destIfFalse = sqlite3VdbeMakeLabel(v);
  68987. int destIfNull = jumpIfNull ? dest : destIfFalse;
  68988. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  68989. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  68990. sqlite3VdbeResolveLabel(v, destIfFalse);
  68991. break;
  68992. }
  68993. #endif
  68994. default: {
  68995. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  68996. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  68997. testcase( regFree1==0 );
  68998. testcase( jumpIfNull==0 );
  68999. break;
  69000. }
  69001. }
  69002. sqlite3ReleaseTempReg(pParse, regFree1);
  69003. sqlite3ReleaseTempReg(pParse, regFree2);
  69004. }
  69005. /*
  69006. ** Generate code for a boolean expression such that a jump is made
  69007. ** to the label "dest" if the expression is false but execution
  69008. ** continues straight thru if the expression is true.
  69009. **
  69010. ** If the expression evaluates to NULL (neither true nor false) then
  69011. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  69012. ** is 0.
  69013. */
  69014. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  69015. Vdbe *v = pParse->pVdbe;
  69016. int op = 0;
  69017. int regFree1 = 0;
  69018. int regFree2 = 0;
  69019. int r1, r2;
  69020. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  69021. if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
  69022. if( pExpr==0 ) return;
  69023. /* The value of pExpr->op and op are related as follows:
  69024. **
  69025. ** pExpr->op op
  69026. ** --------- ----------
  69027. ** TK_ISNULL OP_NotNull
  69028. ** TK_NOTNULL OP_IsNull
  69029. ** TK_NE OP_Eq
  69030. ** TK_EQ OP_Ne
  69031. ** TK_GT OP_Le
  69032. ** TK_LE OP_Gt
  69033. ** TK_GE OP_Lt
  69034. ** TK_LT OP_Ge
  69035. **
  69036. ** For other values of pExpr->op, op is undefined and unused.
  69037. ** The value of TK_ and OP_ constants are arranged such that we
  69038. ** can compute the mapping above using the following expression.
  69039. ** Assert()s verify that the computation is correct.
  69040. */
  69041. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  69042. /* Verify correct alignment of TK_ and OP_ constants
  69043. */
  69044. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  69045. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  69046. assert( pExpr->op!=TK_NE || op==OP_Eq );
  69047. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  69048. assert( pExpr->op!=TK_LT || op==OP_Ge );
  69049. assert( pExpr->op!=TK_LE || op==OP_Gt );
  69050. assert( pExpr->op!=TK_GT || op==OP_Le );
  69051. assert( pExpr->op!=TK_GE || op==OP_Lt );
  69052. switch( pExpr->op ){
  69053. case TK_AND: {
  69054. testcase( jumpIfNull==0 );
  69055. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  69056. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  69057. break;
  69058. }
  69059. case TK_OR: {
  69060. int d2 = sqlite3VdbeMakeLabel(v);
  69061. testcase( jumpIfNull==0 );
  69062. sqlite3ExprCachePush(pParse);
  69063. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  69064. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  69065. sqlite3VdbeResolveLabel(v, d2);
  69066. sqlite3ExprCachePop(pParse, 1);
  69067. break;
  69068. }
  69069. case TK_NOT: {
  69070. testcase( jumpIfNull==0 );
  69071. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  69072. break;
  69073. }
  69074. case TK_LT:
  69075. case TK_LE:
  69076. case TK_GT:
  69077. case TK_GE:
  69078. case TK_NE:
  69079. case TK_EQ: {
  69080. testcase( op==TK_LT );
  69081. testcase( op==TK_LE );
  69082. testcase( op==TK_GT );
  69083. testcase( op==TK_GE );
  69084. testcase( op==TK_EQ );
  69085. testcase( op==TK_NE );
  69086. testcase( jumpIfNull==0 );
  69087. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  69088. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  69089. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  69090. r1, r2, dest, jumpIfNull);
  69091. testcase( regFree1==0 );
  69092. testcase( regFree2==0 );
  69093. break;
  69094. }
  69095. case TK_IS:
  69096. case TK_ISNOT: {
  69097. testcase( pExpr->op==TK_IS );
  69098. testcase( pExpr->op==TK_ISNOT );
  69099. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  69100. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  69101. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  69102. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  69103. r1, r2, dest, SQLITE_NULLEQ);
  69104. testcase( regFree1==0 );
  69105. testcase( regFree2==0 );
  69106. break;
  69107. }
  69108. case TK_ISNULL:
  69109. case TK_NOTNULL: {
  69110. testcase( op==TK_ISNULL );
  69111. testcase( op==TK_NOTNULL );
  69112. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  69113. sqlite3VdbeAddOp2(v, op, r1, dest);
  69114. testcase( regFree1==0 );
  69115. break;
  69116. }
  69117. case TK_BETWEEN: {
  69118. testcase( jumpIfNull==0 );
  69119. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  69120. break;
  69121. }
  69122. #ifndef SQLITE_OMIT_SUBQUERY
  69123. case TK_IN: {
  69124. if( jumpIfNull ){
  69125. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  69126. }else{
  69127. int destIfNull = sqlite3VdbeMakeLabel(v);
  69128. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  69129. sqlite3VdbeResolveLabel(v, destIfNull);
  69130. }
  69131. break;
  69132. }
  69133. #endif
  69134. default: {
  69135. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  69136. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  69137. testcase( regFree1==0 );
  69138. testcase( jumpIfNull==0 );
  69139. break;
  69140. }
  69141. }
  69142. sqlite3ReleaseTempReg(pParse, regFree1);
  69143. sqlite3ReleaseTempReg(pParse, regFree2);
  69144. }
  69145. /*
  69146. ** Do a deep comparison of two expression trees. Return 0 if the two
  69147. ** expressions are completely identical. Return 1 if they differ only
  69148. ** by a COLLATE operator at the top level. Return 2 if there are differences
  69149. ** other than the top-level COLLATE operator.
  69150. **
  69151. ** Sometimes this routine will return 2 even if the two expressions
  69152. ** really are equivalent. If we cannot prove that the expressions are
  69153. ** identical, we return 2 just to be safe. So if this routine
  69154. ** returns 2, then you do not really know for certain if the two
  69155. ** expressions are the same. But if you get a 0 or 1 return, then you
  69156. ** can be sure the expressions are the same. In the places where
  69157. ** this routine is used, it does not hurt to get an extra 2 - that
  69158. ** just might result in some slightly slower code. But returning
  69159. ** an incorrect 0 or 1 could lead to a malfunction.
  69160. */
  69161. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
  69162. if( pA==0||pB==0 ){
  69163. return pB==pA ? 0 : 2;
  69164. }
  69165. assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
  69166. assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
  69167. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  69168. return 2;
  69169. }
  69170. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  69171. if( pA->op!=pB->op ) return 2;
  69172. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
  69173. if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
  69174. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
  69175. if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
  69176. if( ExprHasProperty(pA, EP_IntValue) ){
  69177. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  69178. return 2;
  69179. }
  69180. }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
  69181. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  69182. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
  69183. return 2;
  69184. }
  69185. }
  69186. if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
  69187. if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
  69188. return 0;
  69189. }
  69190. /*
  69191. ** Compare two ExprList objects. Return 0 if they are identical and
  69192. ** non-zero if they differ in any way.
  69193. **
  69194. ** This routine might return non-zero for equivalent ExprLists. The
  69195. ** only consequence will be disabled optimizations. But this routine
  69196. ** must never return 0 if the two ExprList objects are different, or
  69197. ** a malfunction will result.
  69198. **
  69199. ** Two NULL pointers are considered to be the same. But a NULL pointer
  69200. ** always differs from a non-NULL pointer.
  69201. */
  69202. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
  69203. int i;
  69204. if( pA==0 && pB==0 ) return 0;
  69205. if( pA==0 || pB==0 ) return 1;
  69206. if( pA->nExpr!=pB->nExpr ) return 1;
  69207. for(i=0; i<pA->nExpr; i++){
  69208. Expr *pExprA = pA->a[i].pExpr;
  69209. Expr *pExprB = pB->a[i].pExpr;
  69210. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  69211. if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
  69212. }
  69213. return 0;
  69214. }
  69215. /*
  69216. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  69217. ** the new element. Return a negative number if malloc fails.
  69218. */
  69219. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  69220. int i;
  69221. pInfo->aCol = sqlite3ArrayAllocate(
  69222. db,
  69223. pInfo->aCol,
  69224. sizeof(pInfo->aCol[0]),
  69225. 3,
  69226. &pInfo->nColumn,
  69227. &pInfo->nColumnAlloc,
  69228. &i
  69229. );
  69230. return i;
  69231. }
  69232. /*
  69233. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  69234. ** the new element. Return a negative number if malloc fails.
  69235. */
  69236. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  69237. int i;
  69238. pInfo->aFunc = sqlite3ArrayAllocate(
  69239. db,
  69240. pInfo->aFunc,
  69241. sizeof(pInfo->aFunc[0]),
  69242. 3,
  69243. &pInfo->nFunc,
  69244. &pInfo->nFuncAlloc,
  69245. &i
  69246. );
  69247. return i;
  69248. }
  69249. /*
  69250. ** This is the xExprCallback for a tree walker. It is used to
  69251. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  69252. ** for additional information.
  69253. */
  69254. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  69255. int i;
  69256. NameContext *pNC = pWalker->u.pNC;
  69257. Parse *pParse = pNC->pParse;
  69258. SrcList *pSrcList = pNC->pSrcList;
  69259. AggInfo *pAggInfo = pNC->pAggInfo;
  69260. switch( pExpr->op ){
  69261. case TK_AGG_COLUMN:
  69262. case TK_COLUMN: {
  69263. testcase( pExpr->op==TK_AGG_COLUMN );
  69264. testcase( pExpr->op==TK_COLUMN );
  69265. /* Check to see if the column is in one of the tables in the FROM
  69266. ** clause of the aggregate query */
  69267. if( ALWAYS(pSrcList!=0) ){
  69268. struct SrcList_item *pItem = pSrcList->a;
  69269. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  69270. struct AggInfo_col *pCol;
  69271. assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  69272. if( pExpr->iTable==pItem->iCursor ){
  69273. /* If we reach this point, it means that pExpr refers to a table
  69274. ** that is in the FROM clause of the aggregate query.
  69275. **
  69276. ** Make an entry for the column in pAggInfo->aCol[] if there
  69277. ** is not an entry there already.
  69278. */
  69279. int k;
  69280. pCol = pAggInfo->aCol;
  69281. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  69282. if( pCol->iTable==pExpr->iTable &&
  69283. pCol->iColumn==pExpr->iColumn ){
  69284. break;
  69285. }
  69286. }
  69287. if( (k>=pAggInfo->nColumn)
  69288. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  69289. ){
  69290. pCol = &pAggInfo->aCol[k];
  69291. pCol->pTab = pExpr->pTab;
  69292. pCol->iTable = pExpr->iTable;
  69293. pCol->iColumn = pExpr->iColumn;
  69294. pCol->iMem = ++pParse->nMem;
  69295. pCol->iSorterColumn = -1;
  69296. pCol->pExpr = pExpr;
  69297. if( pAggInfo->pGroupBy ){
  69298. int j, n;
  69299. ExprList *pGB = pAggInfo->pGroupBy;
  69300. struct ExprList_item *pTerm = pGB->a;
  69301. n = pGB->nExpr;
  69302. for(j=0; j<n; j++, pTerm++){
  69303. Expr *pE = pTerm->pExpr;
  69304. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  69305. pE->iColumn==pExpr->iColumn ){
  69306. pCol->iSorterColumn = j;
  69307. break;
  69308. }
  69309. }
  69310. }
  69311. if( pCol->iSorterColumn<0 ){
  69312. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  69313. }
  69314. }
  69315. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  69316. ** because it was there before or because we just created it).
  69317. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  69318. ** pAggInfo->aCol[] entry.
  69319. */
  69320. ExprSetIrreducible(pExpr);
  69321. pExpr->pAggInfo = pAggInfo;
  69322. pExpr->op = TK_AGG_COLUMN;
  69323. pExpr->iAgg = (i16)k;
  69324. break;
  69325. } /* endif pExpr->iTable==pItem->iCursor */
  69326. } /* end loop over pSrcList */
  69327. }
  69328. return WRC_Prune;
  69329. }
  69330. case TK_AGG_FUNCTION: {
  69331. /* The pNC->nDepth==0 test causes aggregate functions in subqueries
  69332. ** to be ignored */
  69333. if( pNC->nDepth==0 ){
  69334. /* Check to see if pExpr is a duplicate of another aggregate
  69335. ** function that is already in the pAggInfo structure
  69336. */
  69337. struct AggInfo_func *pItem = pAggInfo->aFunc;
  69338. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  69339. if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
  69340. break;
  69341. }
  69342. }
  69343. if( i>=pAggInfo->nFunc ){
  69344. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  69345. */
  69346. u8 enc = ENC(pParse->db);
  69347. i = addAggInfoFunc(pParse->db, pAggInfo);
  69348. if( i>=0 ){
  69349. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  69350. pItem = &pAggInfo->aFunc[i];
  69351. pItem->pExpr = pExpr;
  69352. pItem->iMem = ++pParse->nMem;
  69353. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  69354. pItem->pFunc = sqlite3FindFunction(pParse->db,
  69355. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  69356. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  69357. if( pExpr->flags & EP_Distinct ){
  69358. pItem->iDistinct = pParse->nTab++;
  69359. }else{
  69360. pItem->iDistinct = -1;
  69361. }
  69362. }
  69363. }
  69364. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  69365. */
  69366. assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  69367. ExprSetIrreducible(pExpr);
  69368. pExpr->iAgg = (i16)i;
  69369. pExpr->pAggInfo = pAggInfo;
  69370. return WRC_Prune;
  69371. }
  69372. }
  69373. }
  69374. return WRC_Continue;
  69375. }
  69376. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  69377. NameContext *pNC = pWalker->u.pNC;
  69378. if( pNC->nDepth==0 ){
  69379. pNC->nDepth++;
  69380. sqlite3WalkSelect(pWalker, pSelect);
  69381. pNC->nDepth--;
  69382. return WRC_Prune;
  69383. }else{
  69384. return WRC_Continue;
  69385. }
  69386. }
  69387. /*
  69388. ** Analyze the given expression looking for aggregate functions and
  69389. ** for variables that need to be added to the pParse->aAgg[] array.
  69390. ** Make additional entries to the pParse->aAgg[] array as necessary.
  69391. **
  69392. ** This routine should only be called after the expression has been
  69393. ** analyzed by sqlite3ResolveExprNames().
  69394. */
  69395. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  69396. Walker w;
  69397. w.xExprCallback = analyzeAggregate;
  69398. w.xSelectCallback = analyzeAggregatesInSelect;
  69399. w.u.pNC = pNC;
  69400. assert( pNC->pSrcList!=0 );
  69401. sqlite3WalkExpr(&w, pExpr);
  69402. }
  69403. /*
  69404. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  69405. ** expression list. Return the number of errors.
  69406. **
  69407. ** If an error is found, the analysis is cut short.
  69408. */
  69409. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  69410. struct ExprList_item *pItem;
  69411. int i;
  69412. if( pList ){
  69413. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  69414. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  69415. }
  69416. }
  69417. }
  69418. /*
  69419. ** Allocate a single new register for use to hold some intermediate result.
  69420. */
  69421. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  69422. if( pParse->nTempReg==0 ){
  69423. return ++pParse->nMem;
  69424. }
  69425. return pParse->aTempReg[--pParse->nTempReg];
  69426. }
  69427. /*
  69428. ** Deallocate a register, making available for reuse for some other
  69429. ** purpose.
  69430. **
  69431. ** If a register is currently being used by the column cache, then
  69432. ** the dallocation is deferred until the column cache line that uses
  69433. ** the register becomes stale.
  69434. */
  69435. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  69436. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  69437. int i;
  69438. struct yColCache *p;
  69439. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  69440. if( p->iReg==iReg ){
  69441. p->tempReg = 1;
  69442. return;
  69443. }
  69444. }
  69445. pParse->aTempReg[pParse->nTempReg++] = iReg;
  69446. }
  69447. }
  69448. /*
  69449. ** Allocate or deallocate a block of nReg consecutive registers
  69450. */
  69451. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  69452. int i, n;
  69453. i = pParse->iRangeReg;
  69454. n = pParse->nRangeReg;
  69455. if( nReg<=n ){
  69456. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  69457. pParse->iRangeReg += nReg;
  69458. pParse->nRangeReg -= nReg;
  69459. }else{
  69460. i = pParse->nMem+1;
  69461. pParse->nMem += nReg;
  69462. }
  69463. return i;
  69464. }
  69465. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  69466. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  69467. if( nReg>pParse->nRangeReg ){
  69468. pParse->nRangeReg = nReg;
  69469. pParse->iRangeReg = iReg;
  69470. }
  69471. }
  69472. /************** End of expr.c ************************************************/
  69473. /************** Begin file alter.c *******************************************/
  69474. /*
  69475. ** 2005 February 15
  69476. **
  69477. ** The author disclaims copyright to this source code. In place of
  69478. ** a legal notice, here is a blessing:
  69479. **
  69480. ** May you do good and not evil.
  69481. ** May you find forgiveness for yourself and forgive others.
  69482. ** May you share freely, never taking more than you give.
  69483. **
  69484. *************************************************************************
  69485. ** This file contains C code routines that used to generate VDBE code
  69486. ** that implements the ALTER TABLE command.
  69487. */
  69488. /*
  69489. ** The code in this file only exists if we are not omitting the
  69490. ** ALTER TABLE logic from the build.
  69491. */
  69492. #ifndef SQLITE_OMIT_ALTERTABLE
  69493. /*
  69494. ** This function is used by SQL generated to implement the
  69495. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  69496. ** CREATE INDEX command. The second is a table name. The table name in
  69497. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  69498. ** argument and the result returned. Examples:
  69499. **
  69500. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  69501. ** -> 'CREATE TABLE def(a, b, c)'
  69502. **
  69503. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  69504. ** -> 'CREATE INDEX i ON def(a, b, c)'
  69505. */
  69506. static void renameTableFunc(
  69507. sqlite3_context *context,
  69508. int NotUsed,
  69509. sqlite3_value **argv
  69510. ){
  69511. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  69512. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  69513. int token;
  69514. Token tname;
  69515. unsigned char const *zCsr = zSql;
  69516. int len = 0;
  69517. char *zRet;
  69518. sqlite3 *db = sqlite3_context_db_handle(context);
  69519. UNUSED_PARAMETER(NotUsed);
  69520. /* The principle used to locate the table name in the CREATE TABLE
  69521. ** statement is that the table name is the first non-space token that
  69522. ** is immediately followed by a TK_LP or TK_USING token.
  69523. */
  69524. if( zSql ){
  69525. do {
  69526. if( !*zCsr ){
  69527. /* Ran out of input before finding an opening bracket. Return NULL. */
  69528. return;
  69529. }
  69530. /* Store the token that zCsr points to in tname. */
  69531. tname.z = (char*)zCsr;
  69532. tname.n = len;
  69533. /* Advance zCsr to the next token. Store that token type in 'token',
  69534. ** and its length in 'len' (to be used next iteration of this loop).
  69535. */
  69536. do {
  69537. zCsr += len;
  69538. len = sqlite3GetToken(zCsr, &token);
  69539. } while( token==TK_SPACE );
  69540. assert( len>0 );
  69541. } while( token!=TK_LP && token!=TK_USING );
  69542. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  69543. zTableName, tname.z+tname.n);
  69544. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  69545. }
  69546. }
  69547. /*
  69548. ** This C function implements an SQL user function that is used by SQL code
  69549. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  69550. ** of any foreign key constraints that use the table being renamed as the
  69551. ** parent table. It is passed three arguments:
  69552. **
  69553. ** 1) The complete text of the CREATE TABLE statement being modified,
  69554. ** 2) The old name of the table being renamed, and
  69555. ** 3) The new name of the table being renamed.
  69556. **
  69557. ** It returns the new CREATE TABLE statement. For example:
  69558. **
  69559. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  69560. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  69561. */
  69562. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69563. static void renameParentFunc(
  69564. sqlite3_context *context,
  69565. int NotUsed,
  69566. sqlite3_value **argv
  69567. ){
  69568. sqlite3 *db = sqlite3_context_db_handle(context);
  69569. char *zOutput = 0;
  69570. char *zResult;
  69571. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  69572. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  69573. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  69574. unsigned const char *z; /* Pointer to token */
  69575. int n; /* Length of token z */
  69576. int token; /* Type of token */
  69577. UNUSED_PARAMETER(NotUsed);
  69578. for(z=zInput; *z; z=z+n){
  69579. n = sqlite3GetToken(z, &token);
  69580. if( token==TK_REFERENCES ){
  69581. char *zParent;
  69582. do {
  69583. z += n;
  69584. n = sqlite3GetToken(z, &token);
  69585. }while( token==TK_SPACE );
  69586. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  69587. if( zParent==0 ) break;
  69588. sqlite3Dequote(zParent);
  69589. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  69590. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  69591. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  69592. );
  69593. sqlite3DbFree(db, zOutput);
  69594. zOutput = zOut;
  69595. zInput = &z[n];
  69596. }
  69597. sqlite3DbFree(db, zParent);
  69598. }
  69599. }
  69600. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  69601. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  69602. sqlite3DbFree(db, zOutput);
  69603. }
  69604. #endif
  69605. #ifndef SQLITE_OMIT_TRIGGER
  69606. /* This function is used by SQL generated to implement the
  69607. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  69608. ** statement. The second is a table name. The table name in the CREATE
  69609. ** TRIGGER statement is replaced with the third argument and the result
  69610. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  69611. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  69612. */
  69613. static void renameTriggerFunc(
  69614. sqlite3_context *context,
  69615. int NotUsed,
  69616. sqlite3_value **argv
  69617. ){
  69618. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  69619. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  69620. int token;
  69621. Token tname;
  69622. int dist = 3;
  69623. unsigned char const *zCsr = zSql;
  69624. int len = 0;
  69625. char *zRet;
  69626. sqlite3 *db = sqlite3_context_db_handle(context);
  69627. UNUSED_PARAMETER(NotUsed);
  69628. /* The principle used to locate the table name in the CREATE TRIGGER
  69629. ** statement is that the table name is the first token that is immediatedly
  69630. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  69631. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  69632. */
  69633. if( zSql ){
  69634. do {
  69635. if( !*zCsr ){
  69636. /* Ran out of input before finding the table name. Return NULL. */
  69637. return;
  69638. }
  69639. /* Store the token that zCsr points to in tname. */
  69640. tname.z = (char*)zCsr;
  69641. tname.n = len;
  69642. /* Advance zCsr to the next token. Store that token type in 'token',
  69643. ** and its length in 'len' (to be used next iteration of this loop).
  69644. */
  69645. do {
  69646. zCsr += len;
  69647. len = sqlite3GetToken(zCsr, &token);
  69648. }while( token==TK_SPACE );
  69649. assert( len>0 );
  69650. /* Variable 'dist' stores the number of tokens read since the most
  69651. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  69652. ** token is read and 'dist' equals 2, the condition stated above
  69653. ** to be met.
  69654. **
  69655. ** Note that ON cannot be a database, table or column name, so
  69656. ** there is no need to worry about syntax like
  69657. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  69658. */
  69659. dist++;
  69660. if( token==TK_DOT || token==TK_ON ){
  69661. dist = 0;
  69662. }
  69663. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  69664. /* Variable tname now contains the token that is the old table-name
  69665. ** in the CREATE TRIGGER statement.
  69666. */
  69667. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  69668. zTableName, tname.z+tname.n);
  69669. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  69670. }
  69671. }
  69672. #endif /* !SQLITE_OMIT_TRIGGER */
  69673. /*
  69674. ** Register built-in functions used to help implement ALTER TABLE
  69675. */
  69676. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  69677. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  69678. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  69679. #ifndef SQLITE_OMIT_TRIGGER
  69680. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  69681. #endif
  69682. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69683. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  69684. #endif
  69685. };
  69686. int i;
  69687. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  69688. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  69689. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  69690. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  69691. }
  69692. }
  69693. /*
  69694. ** This function is used to create the text of expressions of the form:
  69695. **
  69696. ** name=<constant1> OR name=<constant2> OR ...
  69697. **
  69698. ** If argument zWhere is NULL, then a pointer string containing the text
  69699. ** "name=<constant>" is returned, where <constant> is the quoted version
  69700. ** of the string passed as argument zConstant. The returned buffer is
  69701. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  69702. ** caller to ensure that it is eventually freed.
  69703. **
  69704. ** If argument zWhere is not NULL, then the string returned is
  69705. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  69706. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  69707. **
  69708. */
  69709. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  69710. char *zNew;
  69711. if( !zWhere ){
  69712. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  69713. }else{
  69714. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  69715. sqlite3DbFree(db, zWhere);
  69716. }
  69717. return zNew;
  69718. }
  69719. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  69720. /*
  69721. ** Generate the text of a WHERE expression which can be used to select all
  69722. ** tables that have foreign key constraints that refer to table pTab (i.e.
  69723. ** constraints for which pTab is the parent table) from the sqlite_master
  69724. ** table.
  69725. */
  69726. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  69727. FKey *p;
  69728. char *zWhere = 0;
  69729. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  69730. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  69731. }
  69732. return zWhere;
  69733. }
  69734. #endif
  69735. /*
  69736. ** Generate the text of a WHERE expression which can be used to select all
  69737. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  69738. ** table pTab has no temporary triggers, or is itself stored in the
  69739. ** temporary database, NULL is returned.
  69740. */
  69741. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  69742. Trigger *pTrig;
  69743. char *zWhere = 0;
  69744. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  69745. /* If the table is not located in the temp-db (in which case NULL is
  69746. ** returned, loop through the tables list of triggers. For each trigger
  69747. ** that is not part of the temp-db schema, add a clause to the WHERE
  69748. ** expression being built up in zWhere.
  69749. */
  69750. if( pTab->pSchema!=pTempSchema ){
  69751. sqlite3 *db = pParse->db;
  69752. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  69753. if( pTrig->pSchema==pTempSchema ){
  69754. zWhere = whereOrName(db, zWhere, pTrig->zName);
  69755. }
  69756. }
  69757. }
  69758. if( zWhere ){
  69759. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  69760. sqlite3DbFree(pParse->db, zWhere);
  69761. zWhere = zNew;
  69762. }
  69763. return zWhere;
  69764. }
  69765. /*
  69766. ** Generate code to drop and reload the internal representation of table
  69767. ** pTab from the database, including triggers and temporary triggers.
  69768. ** Argument zName is the name of the table in the database schema at
  69769. ** the time the generated code is executed. This can be different from
  69770. ** pTab->zName if this function is being called to code part of an
  69771. ** "ALTER TABLE RENAME TO" statement.
  69772. */
  69773. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  69774. Vdbe *v;
  69775. char *zWhere;
  69776. int iDb; /* Index of database containing pTab */
  69777. #ifndef SQLITE_OMIT_TRIGGER
  69778. Trigger *pTrig;
  69779. #endif
  69780. v = sqlite3GetVdbe(pParse);
  69781. if( NEVER(v==0) ) return;
  69782. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  69783. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  69784. assert( iDb>=0 );
  69785. #ifndef SQLITE_OMIT_TRIGGER
  69786. /* Drop any table triggers from the internal schema. */
  69787. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  69788. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  69789. assert( iTrigDb==iDb || iTrigDb==1 );
  69790. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  69791. }
  69792. #endif
  69793. /* Drop the table and index from the internal schema. */
  69794. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  69795. /* Reload the table, index and permanent trigger schemas. */
  69796. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  69797. if( !zWhere ) return;
  69798. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  69799. #ifndef SQLITE_OMIT_TRIGGER
  69800. /* Now, if the table is not stored in the temp database, reload any temp
  69801. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  69802. */
  69803. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  69804. sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
  69805. }
  69806. #endif
  69807. }
  69808. /*
  69809. ** Parameter zName is the name of a table that is about to be altered
  69810. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  69811. ** If the table is a system table, this function leaves an error message
  69812. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  69813. **
  69814. ** Or, if zName is not a system table, zero is returned.
  69815. */
  69816. static int isSystemTable(Parse *pParse, const char *zName){
  69817. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  69818. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  69819. return 1;
  69820. }
  69821. return 0;
  69822. }
  69823. /*
  69824. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  69825. ** command.
  69826. */
  69827. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  69828. Parse *pParse, /* Parser context. */
  69829. SrcList *pSrc, /* The table to rename. */
  69830. Token *pName /* The new table name. */
  69831. ){
  69832. int iDb; /* Database that contains the table */
  69833. char *zDb; /* Name of database iDb */
  69834. Table *pTab; /* Table being renamed */
  69835. char *zName = 0; /* NULL-terminated version of pName */
  69836. sqlite3 *db = pParse->db; /* Database connection */
  69837. int nTabName; /* Number of UTF-8 characters in zTabName */
  69838. const char *zTabName; /* Original name of the table */
  69839. Vdbe *v;
  69840. #ifndef SQLITE_OMIT_TRIGGER
  69841. char *zWhere = 0; /* Where clause to locate temp triggers */
  69842. #endif
  69843. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  69844. int savedDbFlags; /* Saved value of db->flags */
  69845. savedDbFlags = db->flags;
  69846. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  69847. assert( pSrc->nSrc==1 );
  69848. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  69849. pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  69850. if( !pTab ) goto exit_rename_table;
  69851. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  69852. zDb = db->aDb[iDb].zName;
  69853. db->flags |= SQLITE_PreferBuiltin;
  69854. /* Get a NULL terminated version of the new table name. */
  69855. zName = sqlite3NameFromToken(db, pName);
  69856. if( !zName ) goto exit_rename_table;
  69857. /* Check that a table or index named 'zName' does not already exist
  69858. ** in database iDb. If so, this is an error.
  69859. */
  69860. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  69861. sqlite3ErrorMsg(pParse,
  69862. "there is already another table or index with this name: %s", zName);
  69863. goto exit_rename_table;
  69864. }
  69865. /* Make sure it is not a system table being altered, or a reserved name
  69866. ** that the table is being renamed to.
  69867. */
  69868. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  69869. goto exit_rename_table;
  69870. }
  69871. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  69872. exit_rename_table;
  69873. }
  69874. #ifndef SQLITE_OMIT_VIEW
  69875. if( pTab->pSelect ){
  69876. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  69877. goto exit_rename_table;
  69878. }
  69879. #endif
  69880. #ifndef SQLITE_OMIT_AUTHORIZATION
  69881. /* Invoke the authorization callback. */
  69882. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  69883. goto exit_rename_table;
  69884. }
  69885. #endif
  69886. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69887. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  69888. goto exit_rename_table;
  69889. }
  69890. if( IsVirtual(pTab) ){
  69891. pVTab = sqlite3GetVTable(db, pTab);
  69892. if( pVTab->pVtab->pModule->xRename==0 ){
  69893. pVTab = 0;
  69894. }
  69895. }
  69896. #endif
  69897. /* Begin a transaction and code the VerifyCookie for database iDb.
  69898. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  69899. ** schema). Open a statement transaction if the table is a virtual
  69900. ** table.
  69901. */
  69902. v = sqlite3GetVdbe(pParse);
  69903. if( v==0 ){
  69904. goto exit_rename_table;
  69905. }
  69906. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  69907. sqlite3ChangeCookie(pParse, iDb);
  69908. /* If this is a virtual table, invoke the xRename() function if
  69909. ** one is defined. The xRename() callback will modify the names
  69910. ** of any resources used by the v-table implementation (including other
  69911. ** SQLite tables) that are identified by the name of the virtual table.
  69912. */
  69913. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69914. if( pVTab ){
  69915. int i = ++pParse->nMem;
  69916. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  69917. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  69918. sqlite3MayAbort(pParse);
  69919. }
  69920. #endif
  69921. /* figure out how many UTF-8 characters are in zName */
  69922. zTabName = pTab->zName;
  69923. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  69924. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  69925. if( db->flags&SQLITE_ForeignKeys ){
  69926. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  69927. ** statements corresponding to all child tables of foreign key constraints
  69928. ** for which the renamed table is the parent table. */
  69929. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  69930. sqlite3NestedParse(pParse,
  69931. "UPDATE \"%w\".%s SET "
  69932. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  69933. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  69934. sqlite3DbFree(db, zWhere);
  69935. }
  69936. }
  69937. #endif
  69938. /* Modify the sqlite_master table to use the new table name. */
  69939. sqlite3NestedParse(pParse,
  69940. "UPDATE %Q.%s SET "
  69941. #ifdef SQLITE_OMIT_TRIGGER
  69942. "sql = sqlite_rename_table(sql, %Q), "
  69943. #else
  69944. "sql = CASE "
  69945. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  69946. "ELSE sqlite_rename_table(sql, %Q) END, "
  69947. #endif
  69948. "tbl_name = %Q, "
  69949. "name = CASE "
  69950. "WHEN type='table' THEN %Q "
  69951. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  69952. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  69953. "ELSE name END "
  69954. "WHERE tbl_name=%Q AND "
  69955. "(type='table' OR type='index' OR type='trigger');",
  69956. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  69957. #ifndef SQLITE_OMIT_TRIGGER
  69958. zName,
  69959. #endif
  69960. zName, nTabName, zTabName
  69961. );
  69962. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69963. /* If the sqlite_sequence table exists in this database, then update
  69964. ** it with the new table name.
  69965. */
  69966. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  69967. sqlite3NestedParse(pParse,
  69968. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  69969. zDb, zName, pTab->zName);
  69970. }
  69971. #endif
  69972. #ifndef SQLITE_OMIT_TRIGGER
  69973. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  69974. ** table. Don't do this if the table being ALTERed is itself located in
  69975. ** the temp database.
  69976. */
  69977. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  69978. sqlite3NestedParse(pParse,
  69979. "UPDATE sqlite_temp_master SET "
  69980. "sql = sqlite_rename_trigger(sql, %Q), "
  69981. "tbl_name = %Q "
  69982. "WHERE %s;", zName, zName, zWhere);
  69983. sqlite3DbFree(db, zWhere);
  69984. }
  69985. #endif
  69986. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  69987. if( db->flags&SQLITE_ForeignKeys ){
  69988. FKey *p;
  69989. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  69990. Table *pFrom = p->pFrom;
  69991. if( pFrom!=pTab ){
  69992. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  69993. }
  69994. }
  69995. }
  69996. #endif
  69997. /* Drop and reload the internal table schema. */
  69998. reloadTableSchema(pParse, pTab, zName);
  69999. exit_rename_table:
  70000. sqlite3SrcListDelete(db, pSrc);
  70001. sqlite3DbFree(db, zName);
  70002. db->flags = savedDbFlags;
  70003. }
  70004. /*
  70005. ** Generate code to make sure the file format number is at least minFormat.
  70006. ** The generated code will increase the file format number if necessary.
  70007. */
  70008. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  70009. Vdbe *v;
  70010. v = sqlite3GetVdbe(pParse);
  70011. /* The VDBE should have been allocated before this routine is called.
  70012. ** If that allocation failed, we would have quit before reaching this
  70013. ** point */
  70014. if( ALWAYS(v) ){
  70015. int r1 = sqlite3GetTempReg(pParse);
  70016. int r2 = sqlite3GetTempReg(pParse);
  70017. int j1;
  70018. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  70019. sqlite3VdbeUsesBtree(v, iDb);
  70020. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  70021. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  70022. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  70023. sqlite3VdbeJumpHere(v, j1);
  70024. sqlite3ReleaseTempReg(pParse, r1);
  70025. sqlite3ReleaseTempReg(pParse, r2);
  70026. }
  70027. }
  70028. /*
  70029. ** This function is called after an "ALTER TABLE ... ADD" statement
  70030. ** has been parsed. Argument pColDef contains the text of the new
  70031. ** column definition.
  70032. **
  70033. ** The Table structure pParse->pNewTable was extended to include
  70034. ** the new column during parsing.
  70035. */
  70036. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  70037. Table *pNew; /* Copy of pParse->pNewTable */
  70038. Table *pTab; /* Table being altered */
  70039. int iDb; /* Database number */
  70040. const char *zDb; /* Database name */
  70041. const char *zTab; /* Table name */
  70042. char *zCol; /* Null-terminated column definition */
  70043. Column *pCol; /* The new column */
  70044. Expr *pDflt; /* Default value for the new column */
  70045. sqlite3 *db; /* The database connection; */
  70046. db = pParse->db;
  70047. if( pParse->nErr || db->mallocFailed ) return;
  70048. pNew = pParse->pNewTable;
  70049. assert( pNew );
  70050. assert( sqlite3BtreeHoldsAllMutexes(db) );
  70051. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  70052. zDb = db->aDb[iDb].zName;
  70053. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  70054. pCol = &pNew->aCol[pNew->nCol-1];
  70055. pDflt = pCol->pDflt;
  70056. pTab = sqlite3FindTable(db, zTab, zDb);
  70057. assert( pTab );
  70058. #ifndef SQLITE_OMIT_AUTHORIZATION
  70059. /* Invoke the authorization callback. */
  70060. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  70061. return;
  70062. }
  70063. #endif
  70064. /* If the default value for the new column was specified with a
  70065. ** literal NULL, then set pDflt to 0. This simplifies checking
  70066. ** for an SQL NULL default below.
  70067. */
  70068. if( pDflt && pDflt->op==TK_NULL ){
  70069. pDflt = 0;
  70070. }
  70071. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  70072. ** If there is a NOT NULL constraint, then the default value for the
  70073. ** column must not be NULL.
  70074. */
  70075. if( pCol->isPrimKey ){
  70076. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  70077. return;
  70078. }
  70079. if( pNew->pIndex ){
  70080. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  70081. return;
  70082. }
  70083. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  70084. sqlite3ErrorMsg(pParse,
  70085. "Cannot add a REFERENCES column with non-NULL default value");
  70086. return;
  70087. }
  70088. if( pCol->notNull && !pDflt ){
  70089. sqlite3ErrorMsg(pParse,
  70090. "Cannot add a NOT NULL column with default value NULL");
  70091. return;
  70092. }
  70093. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  70094. ** can handle (i.e. not CURRENT_TIME etc.)
  70095. */
  70096. if( pDflt ){
  70097. sqlite3_value *pVal;
  70098. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  70099. db->mallocFailed = 1;
  70100. return;
  70101. }
  70102. if( !pVal ){
  70103. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  70104. return;
  70105. }
  70106. sqlite3ValueFree(pVal);
  70107. }
  70108. /* Modify the CREATE TABLE statement. */
  70109. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  70110. if( zCol ){
  70111. char *zEnd = &zCol[pColDef->n-1];
  70112. int savedDbFlags = db->flags;
  70113. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  70114. *zEnd-- = '\0';
  70115. }
  70116. db->flags |= SQLITE_PreferBuiltin;
  70117. sqlite3NestedParse(pParse,
  70118. "UPDATE \"%w\".%s SET "
  70119. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  70120. "WHERE type = 'table' AND name = %Q",
  70121. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  70122. zTab
  70123. );
  70124. sqlite3DbFree(db, zCol);
  70125. db->flags = savedDbFlags;
  70126. }
  70127. /* If the default value of the new column is NULL, then set the file
  70128. ** format to 2. If the default value of the new column is not NULL,
  70129. ** the file format becomes 3.
  70130. */
  70131. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  70132. /* Reload the schema of the modified table. */
  70133. reloadTableSchema(pParse, pTab, pTab->zName);
  70134. }
  70135. /*
  70136. ** This function is called by the parser after the table-name in
  70137. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  70138. ** pSrc is the full-name of the table being altered.
  70139. **
  70140. ** This routine makes a (partial) copy of the Table structure
  70141. ** for the table being altered and sets Parse.pNewTable to point
  70142. ** to it. Routines called by the parser as the column definition
  70143. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  70144. ** the copy. The copy of the Table structure is deleted by tokenize.c
  70145. ** after parsing is finished.
  70146. **
  70147. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  70148. ** coding the "ALTER TABLE ... ADD" statement.
  70149. */
  70150. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  70151. Table *pNew;
  70152. Table *pTab;
  70153. Vdbe *v;
  70154. int iDb;
  70155. int i;
  70156. int nAlloc;
  70157. sqlite3 *db = pParse->db;
  70158. /* Look up the table being altered. */
  70159. assert( pParse->pNewTable==0 );
  70160. assert( sqlite3BtreeHoldsAllMutexes(db) );
  70161. if( db->mallocFailed ) goto exit_begin_add_column;
  70162. pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  70163. if( !pTab ) goto exit_begin_add_column;
  70164. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70165. if( IsVirtual(pTab) ){
  70166. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  70167. goto exit_begin_add_column;
  70168. }
  70169. #endif
  70170. /* Make sure this is not an attempt to ALTER a view. */
  70171. if( pTab->pSelect ){
  70172. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  70173. goto exit_begin_add_column;
  70174. }
  70175. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  70176. goto exit_begin_add_column;
  70177. }
  70178. assert( pTab->addColOffset>0 );
  70179. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  70180. /* Put a copy of the Table struct in Parse.pNewTable for the
  70181. ** sqlite3AddColumn() function and friends to modify. But modify
  70182. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  70183. ** prefix, we insure that the name will not collide with an existing
  70184. ** table because user table are not allowed to have the "sqlite_"
  70185. ** prefix on their name.
  70186. */
  70187. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  70188. if( !pNew ) goto exit_begin_add_column;
  70189. pParse->pNewTable = pNew;
  70190. pNew->nRef = 1;
  70191. pNew->nCol = pTab->nCol;
  70192. assert( pNew->nCol>0 );
  70193. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  70194. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  70195. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  70196. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  70197. if( !pNew->aCol || !pNew->zName ){
  70198. db->mallocFailed = 1;
  70199. goto exit_begin_add_column;
  70200. }
  70201. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  70202. for(i=0; i<pNew->nCol; i++){
  70203. Column *pCol = &pNew->aCol[i];
  70204. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  70205. pCol->zColl = 0;
  70206. pCol->zType = 0;
  70207. pCol->pDflt = 0;
  70208. pCol->zDflt = 0;
  70209. }
  70210. pNew->pSchema = db->aDb[iDb].pSchema;
  70211. pNew->addColOffset = pTab->addColOffset;
  70212. pNew->nRef = 1;
  70213. /* Begin a transaction and increment the schema cookie. */
  70214. sqlite3BeginWriteOperation(pParse, 0, iDb);
  70215. v = sqlite3GetVdbe(pParse);
  70216. if( !v ) goto exit_begin_add_column;
  70217. sqlite3ChangeCookie(pParse, iDb);
  70218. exit_begin_add_column:
  70219. sqlite3SrcListDelete(db, pSrc);
  70220. return;
  70221. }
  70222. #endif /* SQLITE_ALTER_TABLE */
  70223. /************** End of alter.c ***********************************************/
  70224. /************** Begin file analyze.c *****************************************/
  70225. /*
  70226. ** 2005 July 8
  70227. **
  70228. ** The author disclaims copyright to this source code. In place of
  70229. ** a legal notice, here is a blessing:
  70230. **
  70231. ** May you do good and not evil.
  70232. ** May you find forgiveness for yourself and forgive others.
  70233. ** May you share freely, never taking more than you give.
  70234. **
  70235. *************************************************************************
  70236. ** This file contains code associated with the ANALYZE command.
  70237. */
  70238. #ifndef SQLITE_OMIT_ANALYZE
  70239. /*
  70240. ** This routine generates code that opens the sqlite_stat1 table for
  70241. ** writing with cursor iStatCur. If the library was built with the
  70242. ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
  70243. ** opened for writing using cursor (iStatCur+1)
  70244. **
  70245. ** If the sqlite_stat1 tables does not previously exist, it is created.
  70246. ** Similarly, if the sqlite_stat2 table does not exist and the library
  70247. ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
  70248. **
  70249. ** Argument zWhere may be a pointer to a buffer containing a table name,
  70250. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  70251. ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
  70252. ** with the named table are deleted. If zWhere==0, then code is generated
  70253. ** to delete all stat table entries.
  70254. */
  70255. static void openStatTable(
  70256. Parse *pParse, /* Parsing context */
  70257. int iDb, /* The database we are looking in */
  70258. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  70259. const char *zWhere, /* Delete entries for this table or index */
  70260. const char *zWhereType /* Either "tbl" or "idx" */
  70261. ){
  70262. static const struct {
  70263. const char *zName;
  70264. const char *zCols;
  70265. } aTable[] = {
  70266. { "sqlite_stat1", "tbl,idx,stat" },
  70267. #ifdef SQLITE_ENABLE_STAT2
  70268. { "sqlite_stat2", "tbl,idx,sampleno,sample" },
  70269. #endif
  70270. };
  70271. int aRoot[] = {0, 0};
  70272. u8 aCreateTbl[] = {0, 0};
  70273. int i;
  70274. sqlite3 *db = pParse->db;
  70275. Db *pDb;
  70276. Vdbe *v = sqlite3GetVdbe(pParse);
  70277. if( v==0 ) return;
  70278. assert( sqlite3BtreeHoldsAllMutexes(db) );
  70279. assert( sqlite3VdbeDb(v)==db );
  70280. pDb = &db->aDb[iDb];
  70281. for(i=0; i<ArraySize(aTable); i++){
  70282. const char *zTab = aTable[i].zName;
  70283. Table *pStat;
  70284. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  70285. /* The sqlite_stat[12] table does not exist. Create it. Note that a
  70286. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  70287. ** of the new table in register pParse->regRoot. This is important
  70288. ** because the OpenWrite opcode below will be needing it. */
  70289. sqlite3NestedParse(pParse,
  70290. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  70291. );
  70292. aRoot[i] = pParse->regRoot;
  70293. aCreateTbl[i] = 1;
  70294. }else{
  70295. /* The table already exists. If zWhere is not NULL, delete all entries
  70296. ** associated with the table zWhere. If zWhere is NULL, delete the
  70297. ** entire contents of the table. */
  70298. aRoot[i] = pStat->tnum;
  70299. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  70300. if( zWhere ){
  70301. sqlite3NestedParse(pParse,
  70302. "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
  70303. );
  70304. }else{
  70305. /* The sqlite_stat[12] table already exists. Delete all rows. */
  70306. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  70307. }
  70308. }
  70309. }
  70310. /* Open the sqlite_stat[12] tables for writing. */
  70311. for(i=0; i<ArraySize(aTable); i++){
  70312. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
  70313. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  70314. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  70315. }
  70316. }
  70317. /*
  70318. ** Generate code to do an analysis of all indices associated with
  70319. ** a single table.
  70320. */
  70321. static void analyzeOneTable(
  70322. Parse *pParse, /* Parser context */
  70323. Table *pTab, /* Table whose indices are to be analyzed */
  70324. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  70325. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  70326. int iMem /* Available memory locations begin here */
  70327. ){
  70328. sqlite3 *db = pParse->db; /* Database handle */
  70329. Index *pIdx; /* An index to being analyzed */
  70330. int iIdxCur; /* Cursor open on index being analyzed */
  70331. Vdbe *v; /* The virtual machine being built up */
  70332. int i; /* Loop counter */
  70333. int topOfLoop; /* The top of the loop */
  70334. int endOfLoop; /* The end of the loop */
  70335. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  70336. int iDb; /* Index of database containing pTab */
  70337. int regTabname = iMem++; /* Register containing table name */
  70338. int regIdxname = iMem++; /* Register containing index name */
  70339. int regSampleno = iMem++; /* Register containing next sample number */
  70340. int regCol = iMem++; /* Content of a column analyzed table */
  70341. int regRec = iMem++; /* Register holding completed record */
  70342. int regTemp = iMem++; /* Temporary use register */
  70343. int regRowid = iMem++; /* Rowid for the inserted record */
  70344. #ifdef SQLITE_ENABLE_STAT2
  70345. int addr = 0; /* Instruction address */
  70346. int regTemp2 = iMem++; /* Temporary use register */
  70347. int regSamplerecno = iMem++; /* Index of next sample to record */
  70348. int regRecno = iMem++; /* Current sample index */
  70349. int regLast = iMem++; /* Index of last sample to record */
  70350. int regFirst = iMem++; /* Index of first sample to record */
  70351. #endif
  70352. v = sqlite3GetVdbe(pParse);
  70353. if( v==0 || NEVER(pTab==0) ){
  70354. return;
  70355. }
  70356. if( pTab->tnum==0 ){
  70357. /* Do not gather statistics on views or virtual tables */
  70358. return;
  70359. }
  70360. if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
  70361. /* Do not gather statistics on system tables */
  70362. return;
  70363. }
  70364. assert( sqlite3BtreeHoldsAllMutexes(db) );
  70365. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  70366. assert( iDb>=0 );
  70367. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70368. #ifndef SQLITE_OMIT_AUTHORIZATION
  70369. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  70370. db->aDb[iDb].zName ) ){
  70371. return;
  70372. }
  70373. #endif
  70374. /* Establish a read-lock on the table at the shared-cache level. */
  70375. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  70376. iIdxCur = pParse->nTab++;
  70377. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  70378. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  70379. int nCol;
  70380. KeyInfo *pKey;
  70381. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  70382. nCol = pIdx->nColumn;
  70383. pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  70384. if( iMem+1+(nCol*2)>pParse->nMem ){
  70385. pParse->nMem = iMem+1+(nCol*2);
  70386. }
  70387. /* Open a cursor to the index to be analyzed. */
  70388. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  70389. sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
  70390. (char *)pKey, P4_KEYINFO_HANDOFF);
  70391. VdbeComment((v, "%s", pIdx->zName));
  70392. /* Populate the register containing the index name. */
  70393. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
  70394. #ifdef SQLITE_ENABLE_STAT2
  70395. /* If this iteration of the loop is generating code to analyze the
  70396. ** first index in the pTab->pIndex list, then register regLast has
  70397. ** not been populated. In this case populate it now. */
  70398. if( pTab->pIndex==pIdx ){
  70399. sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
  70400. sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
  70401. sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
  70402. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
  70403. sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
  70404. addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
  70405. sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
  70406. sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
  70407. sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
  70408. sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regLast);
  70409. sqlite3VdbeJumpHere(v, addr);
  70410. }
  70411. /* Zero the regSampleno and regRecno registers. */
  70412. sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
  70413. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
  70414. sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
  70415. #endif
  70416. /* The block of memory cells initialized here is used as follows.
  70417. **
  70418. ** iMem:
  70419. ** The total number of rows in the table.
  70420. **
  70421. ** iMem+1 .. iMem+nCol:
  70422. ** Number of distinct entries in index considering the
  70423. ** left-most N columns only, where N is between 1 and nCol,
  70424. ** inclusive.
  70425. **
  70426. ** iMem+nCol+1 .. Mem+2*nCol:
  70427. ** Previous value of indexed columns, from left to right.
  70428. **
  70429. ** Cells iMem through iMem+nCol are initialized to 0. The others are
  70430. ** initialized to contain an SQL NULL.
  70431. */
  70432. for(i=0; i<=nCol; i++){
  70433. sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
  70434. }
  70435. for(i=0; i<nCol; i++){
  70436. sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
  70437. }
  70438. /* Start the analysis loop. This loop runs through all the entries in
  70439. ** the index b-tree. */
  70440. endOfLoop = sqlite3VdbeMakeLabel(v);
  70441. sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
  70442. topOfLoop = sqlite3VdbeCurrentAddr(v);
  70443. sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
  70444. for(i=0; i<nCol; i++){
  70445. CollSeq *pColl;
  70446. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
  70447. if( i==0 ){
  70448. #ifdef SQLITE_ENABLE_STAT2
  70449. /* Check if the record that cursor iIdxCur points to contains a
  70450. ** value that should be stored in the sqlite_stat2 table. If so,
  70451. ** store it. */
  70452. int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
  70453. assert( regTabname+1==regIdxname
  70454. && regTabname+2==regSampleno
  70455. && regTabname+3==regCol
  70456. );
  70457. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  70458. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
  70459. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
  70460. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
  70461. /* Calculate new values for regSamplerecno and regSampleno.
  70462. **
  70463. ** sampleno = sampleno + 1
  70464. ** samplerecno = samplerecno+(remaining records)/(remaining samples)
  70465. */
  70466. sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
  70467. sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
  70468. sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
  70469. sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
  70470. sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
  70471. sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
  70472. sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
  70473. sqlite3VdbeJumpHere(v, ne);
  70474. sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
  70475. #endif
  70476. /* Always record the very first row */
  70477. sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
  70478. }
  70479. assert( pIdx->azColl!=0 );
  70480. assert( pIdx->azColl[i]!=0 );
  70481. pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  70482. sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
  70483. (char*)pColl, P4_COLLSEQ);
  70484. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  70485. }
  70486. if( db->mallocFailed ){
  70487. /* If a malloc failure has occurred, then the result of the expression
  70488. ** passed as the second argument to the call to sqlite3VdbeJumpHere()
  70489. ** below may be negative. Which causes an assert() to fail (or an
  70490. ** out-of-bounds write if SQLITE_DEBUG is not defined). */
  70491. return;
  70492. }
  70493. sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
  70494. for(i=0; i<nCol; i++){
  70495. int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
  70496. if( i==0 ){
  70497. sqlite3VdbeJumpHere(v, addr2-1); /* Set jump dest for the OP_IfNot */
  70498. }
  70499. sqlite3VdbeJumpHere(v, addr2); /* Set jump dest for the OP_Ne */
  70500. sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
  70501. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
  70502. }
  70503. /* End of the analysis loop. */
  70504. sqlite3VdbeResolveLabel(v, endOfLoop);
  70505. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
  70506. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
  70507. /* Store the results in sqlite_stat1.
  70508. **
  70509. ** The result is a single row of the sqlite_stat1 table. The first
  70510. ** two columns are the names of the table and index. The third column
  70511. ** is a string composed of a list of integer statistics about the
  70512. ** index. The first integer in the list is the total number of entries
  70513. ** in the index. There is one additional integer in the list for each
  70514. ** column of the table. This additional integer is a guess of how many
  70515. ** rows of the table the index will select. If D is the count of distinct
  70516. ** values and K is the total number of rows, then the integer is computed
  70517. ** as:
  70518. **
  70519. ** I = (K+D-1)/D
  70520. **
  70521. ** If K==0 then no entry is made into the sqlite_stat1 table.
  70522. ** If K>0 then it is always the case the D>0 so division by zero
  70523. ** is never possible.
  70524. */
  70525. sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
  70526. if( jZeroRows<0 ){
  70527. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
  70528. }
  70529. for(i=0; i<nCol; i++){
  70530. sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
  70531. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
  70532. sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
  70533. sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
  70534. sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
  70535. sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
  70536. sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
  70537. }
  70538. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
  70539. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
  70540. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
  70541. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  70542. }
  70543. /* If the table has no indices, create a single sqlite_stat1 entry
  70544. ** containing NULL as the index name and the row count as the content.
  70545. */
  70546. if( pTab->pIndex==0 ){
  70547. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
  70548. VdbeComment((v, "%s", pTab->zName));
  70549. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
  70550. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
  70551. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
  70552. }else{
  70553. sqlite3VdbeJumpHere(v, jZeroRows);
  70554. jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
  70555. }
  70556. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  70557. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
  70558. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
  70559. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
  70560. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  70561. if( pParse->nMem<regRec ) pParse->nMem = regRec;
  70562. sqlite3VdbeJumpHere(v, jZeroRows);
  70563. }
  70564. /*
  70565. ** Generate code that will cause the most recent index analysis to
  70566. ** be loaded into internal hash tables where is can be used.
  70567. */
  70568. static void loadAnalysis(Parse *pParse, int iDb){
  70569. Vdbe *v = sqlite3GetVdbe(pParse);
  70570. if( v ){
  70571. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  70572. }
  70573. }
  70574. /*
  70575. ** Generate code that will do an analysis of an entire database
  70576. */
  70577. static void analyzeDatabase(Parse *pParse, int iDb){
  70578. sqlite3 *db = pParse->db;
  70579. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  70580. HashElem *k;
  70581. int iStatCur;
  70582. int iMem;
  70583. sqlite3BeginWriteOperation(pParse, 0, iDb);
  70584. iStatCur = pParse->nTab;
  70585. pParse->nTab += 2;
  70586. openStatTable(pParse, iDb, iStatCur, 0, 0);
  70587. iMem = pParse->nMem+1;
  70588. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70589. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  70590. Table *pTab = (Table*)sqliteHashData(k);
  70591. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
  70592. }
  70593. loadAnalysis(pParse, iDb);
  70594. }
  70595. /*
  70596. ** Generate code that will do an analysis of a single table in
  70597. ** a database. If pOnlyIdx is not NULL then it is a single index
  70598. ** in pTab that should be analyzed.
  70599. */
  70600. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  70601. int iDb;
  70602. int iStatCur;
  70603. assert( pTab!=0 );
  70604. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  70605. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  70606. sqlite3BeginWriteOperation(pParse, 0, iDb);
  70607. iStatCur = pParse->nTab;
  70608. pParse->nTab += 2;
  70609. if( pOnlyIdx ){
  70610. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  70611. }else{
  70612. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  70613. }
  70614. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
  70615. loadAnalysis(pParse, iDb);
  70616. }
  70617. /*
  70618. ** Generate code for the ANALYZE command. The parser calls this routine
  70619. ** when it recognizes an ANALYZE command.
  70620. **
  70621. ** ANALYZE -- 1
  70622. ** ANALYZE <database> -- 2
  70623. ** ANALYZE ?<database>.?<tablename> -- 3
  70624. **
  70625. ** Form 1 causes all indices in all attached databases to be analyzed.
  70626. ** Form 2 analyzes all indices the single database named.
  70627. ** Form 3 analyzes all indices associated with the named table.
  70628. */
  70629. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  70630. sqlite3 *db = pParse->db;
  70631. int iDb;
  70632. int i;
  70633. char *z, *zDb;
  70634. Table *pTab;
  70635. Index *pIdx;
  70636. Token *pTableName;
  70637. /* Read the database schema. If an error occurs, leave an error message
  70638. ** and code in pParse and return NULL. */
  70639. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  70640. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  70641. return;
  70642. }
  70643. assert( pName2!=0 || pName1==0 );
  70644. if( pName1==0 ){
  70645. /* Form 1: Analyze everything */
  70646. for(i=0; i<db->nDb; i++){
  70647. if( i==1 ) continue; /* Do not analyze the TEMP database */
  70648. analyzeDatabase(pParse, i);
  70649. }
  70650. }else if( pName2->n==0 ){
  70651. /* Form 2: Analyze the database or table named */
  70652. iDb = sqlite3FindDb(db, pName1);
  70653. if( iDb>=0 ){
  70654. analyzeDatabase(pParse, iDb);
  70655. }else{
  70656. z = sqlite3NameFromToken(db, pName1);
  70657. if( z ){
  70658. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  70659. analyzeTable(pParse, pIdx->pTable, pIdx);
  70660. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  70661. analyzeTable(pParse, pTab, 0);
  70662. }
  70663. sqlite3DbFree(db, z);
  70664. }
  70665. }
  70666. }else{
  70667. /* Form 3: Analyze the fully qualified table name */
  70668. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  70669. if( iDb>=0 ){
  70670. zDb = db->aDb[iDb].zName;
  70671. z = sqlite3NameFromToken(db, pTableName);
  70672. if( z ){
  70673. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  70674. analyzeTable(pParse, pIdx->pTable, pIdx);
  70675. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  70676. analyzeTable(pParse, pTab, 0);
  70677. }
  70678. sqlite3DbFree(db, z);
  70679. }
  70680. }
  70681. }
  70682. }
  70683. /*
  70684. ** Used to pass information from the analyzer reader through to the
  70685. ** callback routine.
  70686. */
  70687. typedef struct analysisInfo analysisInfo;
  70688. struct analysisInfo {
  70689. sqlite3 *db;
  70690. const char *zDatabase;
  70691. };
  70692. /*
  70693. ** This callback is invoked once for each index when reading the
  70694. ** sqlite_stat1 table.
  70695. **
  70696. ** argv[0] = name of the table
  70697. ** argv[1] = name of the index (might be NULL)
  70698. ** argv[2] = results of analysis - on integer for each column
  70699. **
  70700. ** Entries for which argv[1]==NULL simply record the number of rows in
  70701. ** the table.
  70702. */
  70703. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  70704. analysisInfo *pInfo = (analysisInfo*)pData;
  70705. Index *pIndex;
  70706. Table *pTable;
  70707. int i, c, n;
  70708. unsigned int v;
  70709. const char *z;
  70710. assert( argc==3 );
  70711. UNUSED_PARAMETER2(NotUsed, argc);
  70712. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  70713. return 0;
  70714. }
  70715. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  70716. if( pTable==0 ){
  70717. return 0;
  70718. }
  70719. if( argv[1] ){
  70720. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  70721. }else{
  70722. pIndex = 0;
  70723. }
  70724. n = pIndex ? pIndex->nColumn : 0;
  70725. z = argv[2];
  70726. for(i=0; *z && i<=n; i++){
  70727. v = 0;
  70728. while( (c=z[0])>='0' && c<='9' ){
  70729. v = v*10 + c - '0';
  70730. z++;
  70731. }
  70732. if( i==0 ) pTable->nRowEst = v;
  70733. if( pIndex==0 ) break;
  70734. pIndex->aiRowEst[i] = v;
  70735. if( *z==' ' ) z++;
  70736. if( memcmp(z, "unordered", 10)==0 ){
  70737. pIndex->bUnordered = 1;
  70738. break;
  70739. }
  70740. }
  70741. return 0;
  70742. }
  70743. /*
  70744. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  70745. ** and its contents.
  70746. */
  70747. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  70748. #ifdef SQLITE_ENABLE_STAT2
  70749. if( pIdx->aSample ){
  70750. int j;
  70751. for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
  70752. IndexSample *p = &pIdx->aSample[j];
  70753. if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
  70754. sqlite3DbFree(db, p->u.z);
  70755. }
  70756. }
  70757. sqlite3DbFree(db, pIdx->aSample);
  70758. }
  70759. #else
  70760. UNUSED_PARAMETER(db);
  70761. UNUSED_PARAMETER(pIdx);
  70762. #endif
  70763. }
  70764. /*
  70765. ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
  70766. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  70767. ** arrays. The contents of sqlite_stat2 are used to populate the
  70768. ** Index.aSample[] arrays.
  70769. **
  70770. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  70771. ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
  70772. ** during compilation and the sqlite_stat2 table is present, no data is
  70773. ** read from it.
  70774. **
  70775. ** If SQLITE_ENABLE_STAT2 was defined during compilation and the
  70776. ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
  70777. ** returned. However, in this case, data is read from the sqlite_stat1
  70778. ** table (if it is present) before returning.
  70779. **
  70780. ** If an OOM error occurs, this function always sets db->mallocFailed.
  70781. ** This means if the caller does not care about other errors, the return
  70782. ** code may be ignored.
  70783. */
  70784. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  70785. analysisInfo sInfo;
  70786. HashElem *i;
  70787. char *zSql;
  70788. int rc;
  70789. assert( iDb>=0 && iDb<db->nDb );
  70790. assert( db->aDb[iDb].pBt!=0 );
  70791. /* Clear any prior statistics */
  70792. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70793. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  70794. Index *pIdx = sqliteHashData(i);
  70795. sqlite3DefaultRowEst(pIdx);
  70796. sqlite3DeleteIndexSamples(db, pIdx);
  70797. pIdx->aSample = 0;
  70798. }
  70799. /* Check to make sure the sqlite_stat1 table exists */
  70800. sInfo.db = db;
  70801. sInfo.zDatabase = db->aDb[iDb].zName;
  70802. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  70803. return SQLITE_ERROR;
  70804. }
  70805. /* Load new statistics out of the sqlite_stat1 table */
  70806. zSql = sqlite3MPrintf(db,
  70807. "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  70808. if( zSql==0 ){
  70809. rc = SQLITE_NOMEM;
  70810. }else{
  70811. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  70812. sqlite3DbFree(db, zSql);
  70813. }
  70814. /* Load the statistics from the sqlite_stat2 table. */
  70815. #ifdef SQLITE_ENABLE_STAT2
  70816. if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
  70817. rc = SQLITE_ERROR;
  70818. }
  70819. if( rc==SQLITE_OK ){
  70820. sqlite3_stmt *pStmt = 0;
  70821. zSql = sqlite3MPrintf(db,
  70822. "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
  70823. if( !zSql ){
  70824. rc = SQLITE_NOMEM;
  70825. }else{
  70826. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  70827. sqlite3DbFree(db, zSql);
  70828. }
  70829. if( rc==SQLITE_OK ){
  70830. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  70831. char *zIndex; /* Index name */
  70832. Index *pIdx; /* Pointer to the index object */
  70833. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  70834. pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
  70835. if( pIdx ){
  70836. int iSample = sqlite3_column_int(pStmt, 1);
  70837. if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
  70838. int eType = sqlite3_column_type(pStmt, 2);
  70839. if( pIdx->aSample==0 ){
  70840. static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
  70841. pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
  70842. if( pIdx->aSample==0 ){
  70843. db->mallocFailed = 1;
  70844. break;
  70845. }
  70846. memset(pIdx->aSample, 0, sz);
  70847. }
  70848. assert( pIdx->aSample );
  70849. {
  70850. IndexSample *pSample = &pIdx->aSample[iSample];
  70851. pSample->eType = (u8)eType;
  70852. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  70853. pSample->u.r = sqlite3_column_double(pStmt, 2);
  70854. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  70855. const char *z = (const char *)(
  70856. (eType==SQLITE_BLOB) ?
  70857. sqlite3_column_blob(pStmt, 2):
  70858. sqlite3_column_text(pStmt, 2)
  70859. );
  70860. int n = sqlite3_column_bytes(pStmt, 2);
  70861. if( n>24 ){
  70862. n = 24;
  70863. }
  70864. pSample->nByte = (u8)n;
  70865. if( n < 1){
  70866. pSample->u.z = 0;
  70867. }else{
  70868. pSample->u.z = sqlite3DbStrNDup(0, z, n);
  70869. if( pSample->u.z==0 ){
  70870. db->mallocFailed = 1;
  70871. break;
  70872. }
  70873. }
  70874. }
  70875. }
  70876. }
  70877. }
  70878. }
  70879. rc = sqlite3_finalize(pStmt);
  70880. }
  70881. }
  70882. #endif
  70883. if( rc==SQLITE_NOMEM ){
  70884. db->mallocFailed = 1;
  70885. }
  70886. return rc;
  70887. }
  70888. #endif /* SQLITE_OMIT_ANALYZE */
  70889. /************** End of analyze.c *********************************************/
  70890. /************** Begin file attach.c ******************************************/
  70891. /*
  70892. ** 2003 April 6
  70893. **
  70894. ** The author disclaims copyright to this source code. In place of
  70895. ** a legal notice, here is a blessing:
  70896. **
  70897. ** May you do good and not evil.
  70898. ** May you find forgiveness for yourself and forgive others.
  70899. ** May you share freely, never taking more than you give.
  70900. **
  70901. *************************************************************************
  70902. ** This file contains code used to implement the ATTACH and DETACH commands.
  70903. */
  70904. #ifndef SQLITE_OMIT_ATTACH
  70905. /*
  70906. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  70907. ** is slightly different from resolving a normal SQL expression, because simple
  70908. ** identifiers are treated as strings, not possible column names or aliases.
  70909. **
  70910. ** i.e. if the parser sees:
  70911. **
  70912. ** ATTACH DATABASE abc AS def
  70913. **
  70914. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  70915. ** looking for columns of the same name.
  70916. **
  70917. ** This only applies to the root node of pExpr, so the statement:
  70918. **
  70919. ** ATTACH DATABASE abc||def AS 'db2'
  70920. **
  70921. ** will fail because neither abc or def can be resolved.
  70922. */
  70923. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  70924. {
  70925. int rc = SQLITE_OK;
  70926. if( pExpr ){
  70927. if( pExpr->op!=TK_ID ){
  70928. rc = sqlite3ResolveExprNames(pName, pExpr);
  70929. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  70930. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
  70931. return SQLITE_ERROR;
  70932. }
  70933. }else{
  70934. pExpr->op = TK_STRING;
  70935. }
  70936. }
  70937. return rc;
  70938. }
  70939. /*
  70940. ** An SQL user-function registered to do the work of an ATTACH statement. The
  70941. ** three arguments to the function come directly from an attach statement:
  70942. **
  70943. ** ATTACH DATABASE x AS y KEY z
  70944. **
  70945. ** SELECT sqlite_attach(x, y, z)
  70946. **
  70947. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  70948. ** third argument.
  70949. */
  70950. static void attachFunc(
  70951. sqlite3_context *context,
  70952. int NotUsed,
  70953. sqlite3_value **argv
  70954. ){
  70955. int i;
  70956. int rc = 0;
  70957. sqlite3 *db = sqlite3_context_db_handle(context);
  70958. const char *zName;
  70959. const char *zFile;
  70960. Db *aNew;
  70961. char *zErrDyn = 0;
  70962. UNUSED_PARAMETER(NotUsed);
  70963. zFile = (const char *)sqlite3_value_text(argv[0]);
  70964. zName = (const char *)sqlite3_value_text(argv[1]);
  70965. if( zFile==0 ) zFile = "";
  70966. if( zName==0 ) zName = "";
  70967. /* Check for the following errors:
  70968. **
  70969. ** * Too many attached databases,
  70970. ** * Transaction currently open
  70971. ** * Specified database name already being used.
  70972. */
  70973. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  70974. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  70975. db->aLimit[SQLITE_LIMIT_ATTACHED]
  70976. );
  70977. goto attach_error;
  70978. }
  70979. if( !db->autoCommit ){
  70980. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  70981. goto attach_error;
  70982. }
  70983. for(i=0; i<db->nDb; i++){
  70984. char *z = db->aDb[i].zName;
  70985. assert( z && zName );
  70986. if( sqlite3StrICmp(z, zName)==0 ){
  70987. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  70988. goto attach_error;
  70989. }
  70990. }
  70991. /* Allocate the new entry in the db->aDb[] array and initialise the schema
  70992. ** hash tables.
  70993. */
  70994. if( db->aDb==db->aDbStatic ){
  70995. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  70996. if( aNew==0 ) return;
  70997. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  70998. }else{
  70999. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  71000. if( aNew==0 ) return;
  71001. }
  71002. db->aDb = aNew;
  71003. aNew = &db->aDb[db->nDb];
  71004. memset(aNew, 0, sizeof(*aNew));
  71005. /* Open the database file. If the btree is successfully opened, use
  71006. ** it to obtain the database schema. At this point the schema may
  71007. ** or may not be initialised.
  71008. */
  71009. rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
  71010. db->openFlags | SQLITE_OPEN_MAIN_DB);
  71011. db->nDb++;
  71012. if( rc==SQLITE_CONSTRAINT ){
  71013. rc = SQLITE_ERROR;
  71014. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  71015. }else if( rc==SQLITE_OK ){
  71016. Pager *pPager;
  71017. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  71018. if( !aNew->pSchema ){
  71019. rc = SQLITE_NOMEM;
  71020. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  71021. zErrDyn = sqlite3MPrintf(db,
  71022. "attached databases must use the same text encoding as main database");
  71023. rc = SQLITE_ERROR;
  71024. }
  71025. pPager = sqlite3BtreePager(aNew->pBt);
  71026. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  71027. sqlite3BtreeSecureDelete(aNew->pBt,
  71028. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  71029. }
  71030. aNew->safety_level = 3;
  71031. aNew->zName = sqlite3DbStrDup(db, zName);
  71032. if( rc==SQLITE_OK && aNew->zName==0 ){
  71033. rc = SQLITE_NOMEM;
  71034. }
  71035. #ifdef SQLITE_HAS_CODEC
  71036. if( rc==SQLITE_OK ){
  71037. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  71038. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  71039. int nKey;
  71040. char *zKey;
  71041. int t = sqlite3_value_type(argv[2]);
  71042. switch( t ){
  71043. case SQLITE_INTEGER:
  71044. case SQLITE_FLOAT:
  71045. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  71046. rc = SQLITE_ERROR;
  71047. break;
  71048. case SQLITE_TEXT:
  71049. case SQLITE_BLOB:
  71050. nKey = sqlite3_value_bytes(argv[2]);
  71051. zKey = (char *)sqlite3_value_blob(argv[2]);
  71052. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  71053. break;
  71054. case SQLITE_NULL:
  71055. /* No key specified. Use the key from the main database */
  71056. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  71057. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  71058. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  71059. }
  71060. break;
  71061. }
  71062. }
  71063. #endif
  71064. /* If the file was opened successfully, read the schema for the new database.
  71065. ** If this fails, or if opening the file failed, then close the file and
  71066. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  71067. ** we found it.
  71068. */
  71069. if( rc==SQLITE_OK ){
  71070. sqlite3BtreeEnterAll(db);
  71071. rc = sqlite3Init(db, &zErrDyn);
  71072. sqlite3BtreeLeaveAll(db);
  71073. }
  71074. if( rc ){
  71075. int iDb = db->nDb - 1;
  71076. assert( iDb>=2 );
  71077. if( db->aDb[iDb].pBt ){
  71078. sqlite3BtreeClose(db->aDb[iDb].pBt);
  71079. db->aDb[iDb].pBt = 0;
  71080. db->aDb[iDb].pSchema = 0;
  71081. }
  71082. sqlite3ResetInternalSchema(db, -1);
  71083. db->nDb = iDb;
  71084. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  71085. db->mallocFailed = 1;
  71086. sqlite3DbFree(db, zErrDyn);
  71087. zErrDyn = sqlite3MPrintf(db, "out of memory");
  71088. }else if( zErrDyn==0 ){
  71089. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  71090. }
  71091. goto attach_error;
  71092. }
  71093. return;
  71094. attach_error:
  71095. /* Return an error if we get here */
  71096. if( zErrDyn ){
  71097. sqlite3_result_error(context, zErrDyn, -1);
  71098. sqlite3DbFree(db, zErrDyn);
  71099. }
  71100. if( rc ) sqlite3_result_error_code(context, rc);
  71101. }
  71102. /*
  71103. ** An SQL user-function registered to do the work of an DETACH statement. The
  71104. ** three arguments to the function come directly from a detach statement:
  71105. **
  71106. ** DETACH DATABASE x
  71107. **
  71108. ** SELECT sqlite_detach(x)
  71109. */
  71110. static void detachFunc(
  71111. sqlite3_context *context,
  71112. int NotUsed,
  71113. sqlite3_value **argv
  71114. ){
  71115. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  71116. sqlite3 *db = sqlite3_context_db_handle(context);
  71117. int i;
  71118. Db *pDb = 0;
  71119. char zErr[128];
  71120. UNUSED_PARAMETER(NotUsed);
  71121. if( zName==0 ) zName = "";
  71122. for(i=0; i<db->nDb; i++){
  71123. pDb = &db->aDb[i];
  71124. if( pDb->pBt==0 ) continue;
  71125. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  71126. }
  71127. if( i>=db->nDb ){
  71128. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  71129. goto detach_error;
  71130. }
  71131. if( i<2 ){
  71132. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  71133. goto detach_error;
  71134. }
  71135. if( !db->autoCommit ){
  71136. sqlite3_snprintf(sizeof(zErr), zErr,
  71137. "cannot DETACH database within transaction");
  71138. goto detach_error;
  71139. }
  71140. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  71141. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  71142. goto detach_error;
  71143. }
  71144. sqlite3BtreeClose(pDb->pBt);
  71145. pDb->pBt = 0;
  71146. pDb->pSchema = 0;
  71147. sqlite3ResetInternalSchema(db, -1);
  71148. return;
  71149. detach_error:
  71150. sqlite3_result_error(context, zErr, -1);
  71151. }
  71152. /*
  71153. ** This procedure generates VDBE code for a single invocation of either the
  71154. ** sqlite_detach() or sqlite_attach() SQL user functions.
  71155. */
  71156. static void codeAttach(
  71157. Parse *pParse, /* The parser context */
  71158. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  71159. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  71160. Expr *pAuthArg, /* Expression to pass to authorization callback */
  71161. Expr *pFilename, /* Name of database file */
  71162. Expr *pDbname, /* Name of the database to use internally */
  71163. Expr *pKey /* Database key for encryption extension */
  71164. ){
  71165. int rc;
  71166. NameContext sName;
  71167. Vdbe *v;
  71168. sqlite3* db = pParse->db;
  71169. int regArgs;
  71170. memset(&sName, 0, sizeof(NameContext));
  71171. sName.pParse = pParse;
  71172. if(
  71173. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  71174. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  71175. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  71176. ){
  71177. pParse->nErr++;
  71178. goto attach_end;
  71179. }
  71180. #ifndef SQLITE_OMIT_AUTHORIZATION
  71181. if( pAuthArg ){
  71182. char *zAuthArg;
  71183. if( pAuthArg->op==TK_STRING ){
  71184. zAuthArg = pAuthArg->u.zToken;
  71185. }else{
  71186. zAuthArg = 0;
  71187. }
  71188. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  71189. if(rc!=SQLITE_OK ){
  71190. goto attach_end;
  71191. }
  71192. }
  71193. #endif /* SQLITE_OMIT_AUTHORIZATION */
  71194. v = sqlite3GetVdbe(pParse);
  71195. regArgs = sqlite3GetTempRange(pParse, 4);
  71196. sqlite3ExprCode(pParse, pFilename, regArgs);
  71197. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  71198. sqlite3ExprCode(pParse, pKey, regArgs+2);
  71199. assert( v || db->mallocFailed );
  71200. if( v ){
  71201. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  71202. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  71203. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  71204. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  71205. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  71206. ** statement only). For DETACH, set it to false (expire all existing
  71207. ** statements).
  71208. */
  71209. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  71210. }
  71211. attach_end:
  71212. sqlite3ExprDelete(db, pFilename);
  71213. sqlite3ExprDelete(db, pDbname);
  71214. sqlite3ExprDelete(db, pKey);
  71215. }
  71216. /*
  71217. ** Called by the parser to compile a DETACH statement.
  71218. **
  71219. ** DETACH pDbname
  71220. */
  71221. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  71222. static const FuncDef detach_func = {
  71223. 1, /* nArg */
  71224. SQLITE_UTF8, /* iPrefEnc */
  71225. 0, /* flags */
  71226. 0, /* pUserData */
  71227. 0, /* pNext */
  71228. detachFunc, /* xFunc */
  71229. 0, /* xStep */
  71230. 0, /* xFinalize */
  71231. "sqlite_detach", /* zName */
  71232. 0, /* pHash */
  71233. 0 /* pDestructor */
  71234. };
  71235. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  71236. }
  71237. /*
  71238. ** Called by the parser to compile an ATTACH statement.
  71239. **
  71240. ** ATTACH p AS pDbname KEY pKey
  71241. */
  71242. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  71243. static const FuncDef attach_func = {
  71244. 3, /* nArg */
  71245. SQLITE_UTF8, /* iPrefEnc */
  71246. 0, /* flags */
  71247. 0, /* pUserData */
  71248. 0, /* pNext */
  71249. attachFunc, /* xFunc */
  71250. 0, /* xStep */
  71251. 0, /* xFinalize */
  71252. "sqlite_attach", /* zName */
  71253. 0, /* pHash */
  71254. 0 /* pDestructor */
  71255. };
  71256. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  71257. }
  71258. #endif /* SQLITE_OMIT_ATTACH */
  71259. /*
  71260. ** Initialize a DbFixer structure. This routine must be called prior
  71261. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  71262. **
  71263. ** The return value indicates whether or not fixation is required. TRUE
  71264. ** means we do need to fix the database references, FALSE means we do not.
  71265. */
  71266. SQLITE_PRIVATE int sqlite3FixInit(
  71267. DbFixer *pFix, /* The fixer to be initialized */
  71268. Parse *pParse, /* Error messages will be written here */
  71269. int iDb, /* This is the database that must be used */
  71270. const char *zType, /* "view", "trigger", or "index" */
  71271. const Token *pName /* Name of the view, trigger, or index */
  71272. ){
  71273. sqlite3 *db;
  71274. if( NEVER(iDb<0) || iDb==1 ) return 0;
  71275. db = pParse->db;
  71276. assert( db->nDb>iDb );
  71277. pFix->pParse = pParse;
  71278. pFix->zDb = db->aDb[iDb].zName;
  71279. pFix->zType = zType;
  71280. pFix->pName = pName;
  71281. return 1;
  71282. }
  71283. /*
  71284. ** The following set of routines walk through the parse tree and assign
  71285. ** a specific database to all table references where the database name
  71286. ** was left unspecified in the original SQL statement. The pFix structure
  71287. ** must have been initialized by a prior call to sqlite3FixInit().
  71288. **
  71289. ** These routines are used to make sure that an index, trigger, or
  71290. ** view in one database does not refer to objects in a different database.
  71291. ** (Exception: indices, triggers, and views in the TEMP database are
  71292. ** allowed to refer to anything.) If a reference is explicitly made
  71293. ** to an object in a different database, an error message is added to
  71294. ** pParse->zErrMsg and these routines return non-zero. If everything
  71295. ** checks out, these routines return 0.
  71296. */
  71297. SQLITE_PRIVATE int sqlite3FixSrcList(
  71298. DbFixer *pFix, /* Context of the fixation */
  71299. SrcList *pList /* The Source list to check and modify */
  71300. ){
  71301. int i;
  71302. const char *zDb;
  71303. struct SrcList_item *pItem;
  71304. if( NEVER(pList==0) ) return 0;
  71305. zDb = pFix->zDb;
  71306. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  71307. if( pItem->zDatabase==0 ){
  71308. pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
  71309. }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
  71310. sqlite3ErrorMsg(pFix->pParse,
  71311. "%s %T cannot reference objects in database %s",
  71312. pFix->zType, pFix->pName, pItem->zDatabase);
  71313. return 1;
  71314. }
  71315. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  71316. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  71317. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  71318. #endif
  71319. }
  71320. return 0;
  71321. }
  71322. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  71323. SQLITE_PRIVATE int sqlite3FixSelect(
  71324. DbFixer *pFix, /* Context of the fixation */
  71325. Select *pSelect /* The SELECT statement to be fixed to one database */
  71326. ){
  71327. while( pSelect ){
  71328. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  71329. return 1;
  71330. }
  71331. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  71332. return 1;
  71333. }
  71334. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  71335. return 1;
  71336. }
  71337. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  71338. return 1;
  71339. }
  71340. pSelect = pSelect->pPrior;
  71341. }
  71342. return 0;
  71343. }
  71344. SQLITE_PRIVATE int sqlite3FixExpr(
  71345. DbFixer *pFix, /* Context of the fixation */
  71346. Expr *pExpr /* The expression to be fixed to one database */
  71347. ){
  71348. while( pExpr ){
  71349. if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
  71350. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  71351. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  71352. }else{
  71353. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  71354. }
  71355. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  71356. return 1;
  71357. }
  71358. pExpr = pExpr->pLeft;
  71359. }
  71360. return 0;
  71361. }
  71362. SQLITE_PRIVATE int sqlite3FixExprList(
  71363. DbFixer *pFix, /* Context of the fixation */
  71364. ExprList *pList /* The expression to be fixed to one database */
  71365. ){
  71366. int i;
  71367. struct ExprList_item *pItem;
  71368. if( pList==0 ) return 0;
  71369. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  71370. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  71371. return 1;
  71372. }
  71373. }
  71374. return 0;
  71375. }
  71376. #endif
  71377. #ifndef SQLITE_OMIT_TRIGGER
  71378. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  71379. DbFixer *pFix, /* Context of the fixation */
  71380. TriggerStep *pStep /* The trigger step be fixed to one database */
  71381. ){
  71382. while( pStep ){
  71383. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  71384. return 1;
  71385. }
  71386. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  71387. return 1;
  71388. }
  71389. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  71390. return 1;
  71391. }
  71392. pStep = pStep->pNext;
  71393. }
  71394. return 0;
  71395. }
  71396. #endif
  71397. /************** End of attach.c **********************************************/
  71398. /************** Begin file auth.c ********************************************/
  71399. /*
  71400. ** 2003 January 11
  71401. **
  71402. ** The author disclaims copyright to this source code. In place of
  71403. ** a legal notice, here is a blessing:
  71404. **
  71405. ** May you do good and not evil.
  71406. ** May you find forgiveness for yourself and forgive others.
  71407. ** May you share freely, never taking more than you give.
  71408. **
  71409. *************************************************************************
  71410. ** This file contains code used to implement the sqlite3_set_authorizer()
  71411. ** API. This facility is an optional feature of the library. Embedded
  71412. ** systems that do not need this facility may omit it by recompiling
  71413. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  71414. */
  71415. /*
  71416. ** All of the code in this file may be omitted by defining a single
  71417. ** macro.
  71418. */
  71419. #ifndef SQLITE_OMIT_AUTHORIZATION
  71420. /*
  71421. ** Set or clear the access authorization function.
  71422. **
  71423. ** The access authorization function is be called during the compilation
  71424. ** phase to verify that the user has read and/or write access permission on
  71425. ** various fields of the database. The first argument to the auth function
  71426. ** is a copy of the 3rd argument to this routine. The second argument
  71427. ** to the auth function is one of these constants:
  71428. **
  71429. ** SQLITE_CREATE_INDEX
  71430. ** SQLITE_CREATE_TABLE
  71431. ** SQLITE_CREATE_TEMP_INDEX
  71432. ** SQLITE_CREATE_TEMP_TABLE
  71433. ** SQLITE_CREATE_TEMP_TRIGGER
  71434. ** SQLITE_CREATE_TEMP_VIEW
  71435. ** SQLITE_CREATE_TRIGGER
  71436. ** SQLITE_CREATE_VIEW
  71437. ** SQLITE_DELETE
  71438. ** SQLITE_DROP_INDEX
  71439. ** SQLITE_DROP_TABLE
  71440. ** SQLITE_DROP_TEMP_INDEX
  71441. ** SQLITE_DROP_TEMP_TABLE
  71442. ** SQLITE_DROP_TEMP_TRIGGER
  71443. ** SQLITE_DROP_TEMP_VIEW
  71444. ** SQLITE_DROP_TRIGGER
  71445. ** SQLITE_DROP_VIEW
  71446. ** SQLITE_INSERT
  71447. ** SQLITE_PRAGMA
  71448. ** SQLITE_READ
  71449. ** SQLITE_SELECT
  71450. ** SQLITE_TRANSACTION
  71451. ** SQLITE_UPDATE
  71452. **
  71453. ** The third and fourth arguments to the auth function are the name of
  71454. ** the table and the column that are being accessed. The auth function
  71455. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  71456. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  71457. ** means that the SQL statement will never-run - the sqlite3_exec() call
  71458. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  71459. ** should run but attempts to read the specified column will return NULL
  71460. ** and attempts to write the column will be ignored.
  71461. **
  71462. ** Setting the auth function to NULL disables this hook. The default
  71463. ** setting of the auth function is NULL.
  71464. */
  71465. SQLITE_API int sqlite3_set_authorizer(
  71466. sqlite3 *db,
  71467. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  71468. void *pArg
  71469. ){
  71470. sqlite3_mutex_enter(db->mutex);
  71471. db->xAuth = xAuth;
  71472. db->pAuthArg = pArg;
  71473. sqlite3ExpirePreparedStatements(db);
  71474. sqlite3_mutex_leave(db->mutex);
  71475. return SQLITE_OK;
  71476. }
  71477. /*
  71478. ** Write an error message into pParse->zErrMsg that explains that the
  71479. ** user-supplied authorization function returned an illegal value.
  71480. */
  71481. static void sqliteAuthBadReturnCode(Parse *pParse){
  71482. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  71483. pParse->rc = SQLITE_ERROR;
  71484. }
  71485. /*
  71486. ** Invoke the authorization callback for permission to read column zCol from
  71487. ** table zTab in database zDb. This function assumes that an authorization
  71488. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  71489. **
  71490. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  71491. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  71492. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  71493. */
  71494. SQLITE_PRIVATE int sqlite3AuthReadCol(
  71495. Parse *pParse, /* The parser context */
  71496. const char *zTab, /* Table name */
  71497. const char *zCol, /* Column name */
  71498. int iDb /* Index of containing database. */
  71499. ){
  71500. sqlite3 *db = pParse->db; /* Database handle */
  71501. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  71502. int rc; /* Auth callback return code */
  71503. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  71504. if( rc==SQLITE_DENY ){
  71505. if( db->nDb>2 || iDb!=0 ){
  71506. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  71507. }else{
  71508. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  71509. }
  71510. pParse->rc = SQLITE_AUTH;
  71511. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  71512. sqliteAuthBadReturnCode(pParse);
  71513. }
  71514. return rc;
  71515. }
  71516. /*
  71517. ** The pExpr should be a TK_COLUMN expression. The table referred to
  71518. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  71519. ** Check to see if it is OK to read this particular column.
  71520. **
  71521. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  71522. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  71523. ** then generate an error.
  71524. */
  71525. SQLITE_PRIVATE void sqlite3AuthRead(
  71526. Parse *pParse, /* The parser context */
  71527. Expr *pExpr, /* The expression to check authorization on */
  71528. Schema *pSchema, /* The schema of the expression */
  71529. SrcList *pTabList /* All table that pExpr might refer to */
  71530. ){
  71531. sqlite3 *db = pParse->db;
  71532. Table *pTab = 0; /* The table being read */
  71533. const char *zCol; /* Name of the column of the table */
  71534. int iSrc; /* Index in pTabList->a[] of table being read */
  71535. int iDb; /* The index of the database the expression refers to */
  71536. int iCol; /* Index of column in table */
  71537. if( db->xAuth==0 ) return;
  71538. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  71539. if( iDb<0 ){
  71540. /* An attempt to read a column out of a subquery or other
  71541. ** temporary table. */
  71542. return;
  71543. }
  71544. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  71545. if( pExpr->op==TK_TRIGGER ){
  71546. pTab = pParse->pTriggerTab;
  71547. }else{
  71548. assert( pTabList );
  71549. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  71550. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  71551. pTab = pTabList->a[iSrc].pTab;
  71552. break;
  71553. }
  71554. }
  71555. }
  71556. iCol = pExpr->iColumn;
  71557. if( NEVER(pTab==0) ) return;
  71558. if( iCol>=0 ){
  71559. assert( iCol<pTab->nCol );
  71560. zCol = pTab->aCol[iCol].zName;
  71561. }else if( pTab->iPKey>=0 ){
  71562. assert( pTab->iPKey<pTab->nCol );
  71563. zCol = pTab->aCol[pTab->iPKey].zName;
  71564. }else{
  71565. zCol = "ROWID";
  71566. }
  71567. assert( iDb>=0 && iDb<db->nDb );
  71568. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  71569. pExpr->op = TK_NULL;
  71570. }
  71571. }
  71572. /*
  71573. ** Do an authorization check using the code and arguments given. Return
  71574. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  71575. ** is returned, then the error count and error message in pParse are
  71576. ** modified appropriately.
  71577. */
  71578. SQLITE_PRIVATE int sqlite3AuthCheck(
  71579. Parse *pParse,
  71580. int code,
  71581. const char *zArg1,
  71582. const char *zArg2,
  71583. const char *zArg3
  71584. ){
  71585. sqlite3 *db = pParse->db;
  71586. int rc;
  71587. /* Don't do any authorization checks if the database is initialising
  71588. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  71589. */
  71590. if( db->init.busy || IN_DECLARE_VTAB ){
  71591. return SQLITE_OK;
  71592. }
  71593. if( db->xAuth==0 ){
  71594. return SQLITE_OK;
  71595. }
  71596. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  71597. if( rc==SQLITE_DENY ){
  71598. sqlite3ErrorMsg(pParse, "not authorized");
  71599. pParse->rc = SQLITE_AUTH;
  71600. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  71601. rc = SQLITE_DENY;
  71602. sqliteAuthBadReturnCode(pParse);
  71603. }
  71604. return rc;
  71605. }
  71606. /*
  71607. ** Push an authorization context. After this routine is called, the
  71608. ** zArg3 argument to authorization callbacks will be zContext until
  71609. ** popped. Or if pParse==0, this routine is a no-op.
  71610. */
  71611. SQLITE_PRIVATE void sqlite3AuthContextPush(
  71612. Parse *pParse,
  71613. AuthContext *pContext,
  71614. const char *zContext
  71615. ){
  71616. assert( pParse );
  71617. pContext->pParse = pParse;
  71618. pContext->zAuthContext = pParse->zAuthContext;
  71619. pParse->zAuthContext = zContext;
  71620. }
  71621. /*
  71622. ** Pop an authorization context that was previously pushed
  71623. ** by sqlite3AuthContextPush
  71624. */
  71625. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  71626. if( pContext->pParse ){
  71627. pContext->pParse->zAuthContext = pContext->zAuthContext;
  71628. pContext->pParse = 0;
  71629. }
  71630. }
  71631. #endif /* SQLITE_OMIT_AUTHORIZATION */
  71632. /************** End of auth.c ************************************************/
  71633. /************** Begin file build.c *******************************************/
  71634. /*
  71635. ** 2001 September 15
  71636. **
  71637. ** The author disclaims copyright to this source code. In place of
  71638. ** a legal notice, here is a blessing:
  71639. **
  71640. ** May you do good and not evil.
  71641. ** May you find forgiveness for yourself and forgive others.
  71642. ** May you share freely, never taking more than you give.
  71643. **
  71644. *************************************************************************
  71645. ** This file contains C code routines that are called by the SQLite parser
  71646. ** when syntax rules are reduced. The routines in this file handle the
  71647. ** following kinds of SQL syntax:
  71648. **
  71649. ** CREATE TABLE
  71650. ** DROP TABLE
  71651. ** CREATE INDEX
  71652. ** DROP INDEX
  71653. ** creating ID lists
  71654. ** BEGIN TRANSACTION
  71655. ** COMMIT
  71656. ** ROLLBACK
  71657. */
  71658. /*
  71659. ** This routine is called when a new SQL statement is beginning to
  71660. ** be parsed. Initialize the pParse structure as needed.
  71661. */
  71662. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  71663. pParse->explain = (u8)explainFlag;
  71664. pParse->nVar = 0;
  71665. }
  71666. #ifndef SQLITE_OMIT_SHARED_CACHE
  71667. /*
  71668. ** The TableLock structure is only used by the sqlite3TableLock() and
  71669. ** codeTableLocks() functions.
  71670. */
  71671. struct TableLock {
  71672. int iDb; /* The database containing the table to be locked */
  71673. int iTab; /* The root page of the table to be locked */
  71674. u8 isWriteLock; /* True for write lock. False for a read lock */
  71675. const char *zName; /* Name of the table */
  71676. };
  71677. /*
  71678. ** Record the fact that we want to lock a table at run-time.
  71679. **
  71680. ** The table to be locked has root page iTab and is found in database iDb.
  71681. ** A read or a write lock can be taken depending on isWritelock.
  71682. **
  71683. ** This routine just records the fact that the lock is desired. The
  71684. ** code to make the lock occur is generated by a later call to
  71685. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  71686. */
  71687. SQLITE_PRIVATE void sqlite3TableLock(
  71688. Parse *pParse, /* Parsing context */
  71689. int iDb, /* Index of the database containing the table to lock */
  71690. int iTab, /* Root page number of the table to be locked */
  71691. u8 isWriteLock, /* True for a write lock */
  71692. const char *zName /* Name of the table to be locked */
  71693. ){
  71694. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  71695. int i;
  71696. int nBytes;
  71697. TableLock *p;
  71698. assert( iDb>=0 );
  71699. for(i=0; i<pToplevel->nTableLock; i++){
  71700. p = &pToplevel->aTableLock[i];
  71701. if( p->iDb==iDb && p->iTab==iTab ){
  71702. p->isWriteLock = (p->isWriteLock || isWriteLock);
  71703. return;
  71704. }
  71705. }
  71706. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  71707. pToplevel->aTableLock =
  71708. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  71709. if( pToplevel->aTableLock ){
  71710. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  71711. p->iDb = iDb;
  71712. p->iTab = iTab;
  71713. p->isWriteLock = isWriteLock;
  71714. p->zName = zName;
  71715. }else{
  71716. pToplevel->nTableLock = 0;
  71717. pToplevel->db->mallocFailed = 1;
  71718. }
  71719. }
  71720. /*
  71721. ** Code an OP_TableLock instruction for each table locked by the
  71722. ** statement (configured by calls to sqlite3TableLock()).
  71723. */
  71724. static void codeTableLocks(Parse *pParse){
  71725. int i;
  71726. Vdbe *pVdbe;
  71727. pVdbe = sqlite3GetVdbe(pParse);
  71728. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  71729. for(i=0; i<pParse->nTableLock; i++){
  71730. TableLock *p = &pParse->aTableLock[i];
  71731. int p1 = p->iDb;
  71732. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  71733. p->zName, P4_STATIC);
  71734. }
  71735. }
  71736. #else
  71737. #define codeTableLocks(x)
  71738. #endif
  71739. /*
  71740. ** This routine is called after a single SQL statement has been
  71741. ** parsed and a VDBE program to execute that statement has been
  71742. ** prepared. This routine puts the finishing touches on the
  71743. ** VDBE program and resets the pParse structure for the next
  71744. ** parse.
  71745. **
  71746. ** Note that if an error occurred, it might be the case that
  71747. ** no VDBE code was generated.
  71748. */
  71749. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  71750. sqlite3 *db;
  71751. Vdbe *v;
  71752. db = pParse->db;
  71753. if( db->mallocFailed ) return;
  71754. if( pParse->nested ) return;
  71755. if( pParse->nErr ) return;
  71756. /* Begin by generating some termination code at the end of the
  71757. ** vdbe program
  71758. */
  71759. v = sqlite3GetVdbe(pParse);
  71760. assert( !pParse->isMultiWrite
  71761. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  71762. if( v ){
  71763. sqlite3VdbeAddOp0(v, OP_Halt);
  71764. /* The cookie mask contains one bit for each database file open.
  71765. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  71766. ** set for each database that is used. Generate code to start a
  71767. ** transaction on each used database and to verify the schema cookie
  71768. ** on each used database.
  71769. */
  71770. if( pParse->cookieGoto>0 ){
  71771. yDbMask mask;
  71772. int iDb;
  71773. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  71774. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  71775. if( (mask & pParse->cookieMask)==0 ) continue;
  71776. sqlite3VdbeUsesBtree(v, iDb);
  71777. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  71778. if( db->init.busy==0 ){
  71779. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  71780. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  71781. iDb, pParse->cookieValue[iDb],
  71782. db->aDb[iDb].pSchema->iGeneration);
  71783. }
  71784. }
  71785. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71786. {
  71787. int i;
  71788. for(i=0; i<pParse->nVtabLock; i++){
  71789. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  71790. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  71791. }
  71792. pParse->nVtabLock = 0;
  71793. }
  71794. #endif
  71795. /* Once all the cookies have been verified and transactions opened,
  71796. ** obtain the required table-locks. This is a no-op unless the
  71797. ** shared-cache feature is enabled.
  71798. */
  71799. codeTableLocks(pParse);
  71800. /* Initialize any AUTOINCREMENT data structures required.
  71801. */
  71802. sqlite3AutoincrementBegin(pParse);
  71803. /* Finally, jump back to the beginning of the executable code. */
  71804. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  71805. }
  71806. }
  71807. /* Get the VDBE program ready for execution
  71808. */
  71809. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  71810. #ifdef SQLITE_DEBUG
  71811. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  71812. sqlite3VdbeTrace(v, trace);
  71813. #endif
  71814. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  71815. /* A minimum of one cursor is required if autoincrement is used
  71816. * See ticket [a696379c1f08866] */
  71817. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  71818. sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
  71819. pParse->nTab, pParse->nMaxArg, pParse->explain,
  71820. pParse->isMultiWrite && pParse->mayAbort);
  71821. pParse->rc = SQLITE_DONE;
  71822. pParse->colNamesSet = 0;
  71823. }else{
  71824. pParse->rc = SQLITE_ERROR;
  71825. }
  71826. pParse->nTab = 0;
  71827. pParse->nMem = 0;
  71828. pParse->nSet = 0;
  71829. pParse->nVar = 0;
  71830. pParse->cookieMask = 0;
  71831. pParse->cookieGoto = 0;
  71832. }
  71833. /*
  71834. ** Run the parser and code generator recursively in order to generate
  71835. ** code for the SQL statement given onto the end of the pParse context
  71836. ** currently under construction. When the parser is run recursively
  71837. ** this way, the final OP_Halt is not appended and other initialization
  71838. ** and finalization steps are omitted because those are handling by the
  71839. ** outermost parser.
  71840. **
  71841. ** Not everything is nestable. This facility is designed to permit
  71842. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  71843. ** care if you decide to try to use this routine for some other purposes.
  71844. */
  71845. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  71846. va_list ap;
  71847. char *zSql;
  71848. char *zErrMsg = 0;
  71849. sqlite3 *db = pParse->db;
  71850. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  71851. char saveBuf[SAVE_SZ];
  71852. if( pParse->nErr ) return;
  71853. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  71854. va_start(ap, zFormat);
  71855. zSql = sqlite3VMPrintf(db, zFormat, ap);
  71856. va_end(ap);
  71857. if( zSql==0 ){
  71858. return; /* A malloc must have failed */
  71859. }
  71860. pParse->nested++;
  71861. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  71862. memset(&pParse->nVar, 0, SAVE_SZ);
  71863. sqlite3RunParser(pParse, zSql, &zErrMsg);
  71864. sqlite3DbFree(db, zErrMsg);
  71865. sqlite3DbFree(db, zSql);
  71866. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  71867. pParse->nested--;
  71868. }
  71869. /*
  71870. ** Locate the in-memory structure that describes a particular database
  71871. ** table given the name of that table and (optionally) the name of the
  71872. ** database containing the table. Return NULL if not found.
  71873. **
  71874. ** If zDatabase is 0, all databases are searched for the table and the
  71875. ** first matching table is returned. (No checking for duplicate table
  71876. ** names is done.) The search order is TEMP first, then MAIN, then any
  71877. ** auxiliary databases added using the ATTACH command.
  71878. **
  71879. ** See also sqlite3LocateTable().
  71880. */
  71881. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  71882. Table *p = 0;
  71883. int i;
  71884. int nName;
  71885. assert( zName!=0 );
  71886. nName = sqlite3Strlen30(zName);
  71887. /* All mutexes are required for schema access. Make sure we hold them. */
  71888. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  71889. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  71890. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  71891. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  71892. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  71893. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  71894. if( p ) break;
  71895. }
  71896. return p;
  71897. }
  71898. /*
  71899. ** Locate the in-memory structure that describes a particular database
  71900. ** table given the name of that table and (optionally) the name of the
  71901. ** database containing the table. Return NULL if not found. Also leave an
  71902. ** error message in pParse->zErrMsg.
  71903. **
  71904. ** The difference between this routine and sqlite3FindTable() is that this
  71905. ** routine leaves an error message in pParse->zErrMsg where
  71906. ** sqlite3FindTable() does not.
  71907. */
  71908. SQLITE_PRIVATE Table *sqlite3LocateTable(
  71909. Parse *pParse, /* context in which to report errors */
  71910. int isView, /* True if looking for a VIEW rather than a TABLE */
  71911. const char *zName, /* Name of the table we are looking for */
  71912. const char *zDbase /* Name of the database. Might be NULL */
  71913. ){
  71914. Table *p;
  71915. /* Read the database schema. If an error occurs, leave an error message
  71916. ** and code in pParse and return NULL. */
  71917. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  71918. return 0;
  71919. }
  71920. p = sqlite3FindTable(pParse->db, zName, zDbase);
  71921. if( p==0 ){
  71922. const char *zMsg = isView ? "no such view" : "no such table";
  71923. if( zDbase ){
  71924. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  71925. }else{
  71926. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  71927. }
  71928. pParse->checkSchema = 1;
  71929. }
  71930. return p;
  71931. }
  71932. /*
  71933. ** Locate the in-memory structure that describes
  71934. ** a particular index given the name of that index
  71935. ** and the name of the database that contains the index.
  71936. ** Return NULL if not found.
  71937. **
  71938. ** If zDatabase is 0, all databases are searched for the
  71939. ** table and the first matching index is returned. (No checking
  71940. ** for duplicate index names is done.) The search order is
  71941. ** TEMP first, then MAIN, then any auxiliary databases added
  71942. ** using the ATTACH command.
  71943. */
  71944. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  71945. Index *p = 0;
  71946. int i;
  71947. int nName = sqlite3Strlen30(zName);
  71948. /* All mutexes are required for schema access. Make sure we hold them. */
  71949. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  71950. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  71951. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  71952. Schema *pSchema = db->aDb[j].pSchema;
  71953. assert( pSchema );
  71954. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  71955. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  71956. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  71957. if( p ) break;
  71958. }
  71959. return p;
  71960. }
  71961. /*
  71962. ** Reclaim the memory used by an index
  71963. */
  71964. static void freeIndex(sqlite3 *db, Index *p){
  71965. #ifndef SQLITE_OMIT_ANALYZE
  71966. sqlite3DeleteIndexSamples(db, p);
  71967. #endif
  71968. sqlite3DbFree(db, p->zColAff);
  71969. sqlite3DbFree(db, p);
  71970. }
  71971. /*
  71972. ** For the index called zIdxName which is found in the database iDb,
  71973. ** unlike that index from its Table then remove the index from
  71974. ** the index hash table and free all memory structures associated
  71975. ** with the index.
  71976. */
  71977. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  71978. Index *pIndex;
  71979. int len;
  71980. Hash *pHash;
  71981. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  71982. pHash = &db->aDb[iDb].pSchema->idxHash;
  71983. len = sqlite3Strlen30(zIdxName);
  71984. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  71985. if( ALWAYS(pIndex) ){
  71986. if( pIndex->pTable->pIndex==pIndex ){
  71987. pIndex->pTable->pIndex = pIndex->pNext;
  71988. }else{
  71989. Index *p;
  71990. /* Justification of ALWAYS(); The index must be on the list of
  71991. ** indices. */
  71992. p = pIndex->pTable->pIndex;
  71993. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  71994. if( ALWAYS(p && p->pNext==pIndex) ){
  71995. p->pNext = pIndex->pNext;
  71996. }
  71997. }
  71998. freeIndex(db, pIndex);
  71999. }
  72000. db->flags |= SQLITE_InternChanges;
  72001. }
  72002. /*
  72003. ** Erase all schema information from the in-memory hash tables of
  72004. ** a single database. This routine is called to reclaim memory
  72005. ** before the database closes. It is also called during a rollback
  72006. ** if there were schema changes during the transaction or if a
  72007. ** schema-cookie mismatch occurs.
  72008. **
  72009. ** If iDb<0 then reset the internal schema tables for all database
  72010. ** files. If iDb>=0 then reset the internal schema for only the
  72011. ** single file indicated.
  72012. */
  72013. SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
  72014. int i, j;
  72015. assert( iDb<db->nDb );
  72016. if( iDb>=0 ){
  72017. /* Case 1: Reset the single schema identified by iDb */
  72018. Db *pDb = &db->aDb[iDb];
  72019. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  72020. assert( pDb->pSchema!=0 );
  72021. sqlite3SchemaClear(pDb->pSchema);
  72022. /* If any database other than TEMP is reset, then also reset TEMP
  72023. ** since TEMP might be holding triggers that reference tables in the
  72024. ** other database.
  72025. */
  72026. if( iDb!=1 ){
  72027. pDb = &db->aDb[1];
  72028. assert( pDb->pSchema!=0 );
  72029. sqlite3SchemaClear(pDb->pSchema);
  72030. }
  72031. return;
  72032. }
  72033. /* Case 2 (from here to the end): Reset all schemas for all attached
  72034. ** databases. */
  72035. assert( iDb<0 );
  72036. sqlite3BtreeEnterAll(db);
  72037. for(i=0; i<db->nDb; i++){
  72038. Db *pDb = &db->aDb[i];
  72039. if( pDb->pSchema ){
  72040. sqlite3SchemaClear(pDb->pSchema);
  72041. }
  72042. }
  72043. db->flags &= ~SQLITE_InternChanges;
  72044. sqlite3VtabUnlockList(db);
  72045. sqlite3BtreeLeaveAll(db);
  72046. /* If one or more of the auxiliary database files has been closed,
  72047. ** then remove them from the auxiliary database list. We take the
  72048. ** opportunity to do this here since we have just deleted all of the
  72049. ** schema hash tables and therefore do not have to make any changes
  72050. ** to any of those tables.
  72051. */
  72052. for(i=j=2; i<db->nDb; i++){
  72053. struct Db *pDb = &db->aDb[i];
  72054. if( pDb->pBt==0 ){
  72055. sqlite3DbFree(db, pDb->zName);
  72056. pDb->zName = 0;
  72057. continue;
  72058. }
  72059. if( j<i ){
  72060. db->aDb[j] = db->aDb[i];
  72061. }
  72062. j++;
  72063. }
  72064. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  72065. db->nDb = j;
  72066. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  72067. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  72068. sqlite3DbFree(db, db->aDb);
  72069. db->aDb = db->aDbStatic;
  72070. }
  72071. }
  72072. /*
  72073. ** This routine is called when a commit occurs.
  72074. */
  72075. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  72076. db->flags &= ~SQLITE_InternChanges;
  72077. }
  72078. /*
  72079. ** Delete memory allocated for the column names of a table or view (the
  72080. ** Table.aCol[] array).
  72081. */
  72082. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  72083. int i;
  72084. Column *pCol;
  72085. assert( pTable!=0 );
  72086. if( (pCol = pTable->aCol)!=0 ){
  72087. for(i=0; i<pTable->nCol; i++, pCol++){
  72088. sqlite3DbFree(db, pCol->zName);
  72089. sqlite3ExprDelete(db, pCol->pDflt);
  72090. sqlite3DbFree(db, pCol->zDflt);
  72091. sqlite3DbFree(db, pCol->zType);
  72092. sqlite3DbFree(db, pCol->zColl);
  72093. }
  72094. sqlite3DbFree(db, pTable->aCol);
  72095. }
  72096. }
  72097. /*
  72098. ** Remove the memory data structures associated with the given
  72099. ** Table. No changes are made to disk by this routine.
  72100. **
  72101. ** This routine just deletes the data structure. It does not unlink
  72102. ** the table data structure from the hash table. But it does destroy
  72103. ** memory structures of the indices and foreign keys associated with
  72104. ** the table.
  72105. */
  72106. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  72107. Index *pIndex, *pNext;
  72108. assert( !pTable || pTable->nRef>0 );
  72109. /* Do not delete the table until the reference count reaches zero. */
  72110. if( !pTable ) return;
  72111. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  72112. /* Delete all indices associated with this table. */
  72113. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  72114. pNext = pIndex->pNext;
  72115. assert( pIndex->pSchema==pTable->pSchema );
  72116. if( !db || db->pnBytesFreed==0 ){
  72117. char *zName = pIndex->zName;
  72118. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  72119. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  72120. );
  72121. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  72122. assert( pOld==pIndex || pOld==0 );
  72123. }
  72124. freeIndex(db, pIndex);
  72125. }
  72126. /* Delete any foreign keys attached to this table. */
  72127. sqlite3FkDelete(db, pTable);
  72128. /* Delete the Table structure itself.
  72129. */
  72130. sqliteDeleteColumnNames(db, pTable);
  72131. sqlite3DbFree(db, pTable->zName);
  72132. sqlite3DbFree(db, pTable->zColAff);
  72133. sqlite3SelectDelete(db, pTable->pSelect);
  72134. #ifndef SQLITE_OMIT_CHECK
  72135. sqlite3ExprDelete(db, pTable->pCheck);
  72136. #endif
  72137. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72138. sqlite3VtabClear(db, pTable);
  72139. #endif
  72140. sqlite3DbFree(db, pTable);
  72141. }
  72142. /*
  72143. ** Unlink the given table from the hash tables and the delete the
  72144. ** table structure with all its indices and foreign keys.
  72145. */
  72146. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  72147. Table *p;
  72148. Db *pDb;
  72149. assert( db!=0 );
  72150. assert( iDb>=0 && iDb<db->nDb );
  72151. assert( zTabName );
  72152. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  72153. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  72154. pDb = &db->aDb[iDb];
  72155. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  72156. sqlite3Strlen30(zTabName),0);
  72157. sqlite3DeleteTable(db, p);
  72158. db->flags |= SQLITE_InternChanges;
  72159. }
  72160. /*
  72161. ** Given a token, return a string that consists of the text of that
  72162. ** token. Space to hold the returned string
  72163. ** is obtained from sqliteMalloc() and must be freed by the calling
  72164. ** function.
  72165. **
  72166. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  72167. ** surround the body of the token are removed.
  72168. **
  72169. ** Tokens are often just pointers into the original SQL text and so
  72170. ** are not \000 terminated and are not persistent. The returned string
  72171. ** is \000 terminated and is persistent.
  72172. */
  72173. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  72174. char *zName;
  72175. if( pName ){
  72176. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  72177. sqlite3Dequote(zName);
  72178. }else{
  72179. zName = 0;
  72180. }
  72181. return zName;
  72182. }
  72183. /*
  72184. ** Open the sqlite_master table stored in database number iDb for
  72185. ** writing. The table is opened using cursor 0.
  72186. */
  72187. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  72188. Vdbe *v = sqlite3GetVdbe(p);
  72189. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  72190. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  72191. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  72192. if( p->nTab==0 ){
  72193. p->nTab = 1;
  72194. }
  72195. }
  72196. /*
  72197. ** Parameter zName points to a nul-terminated buffer containing the name
  72198. ** of a database ("main", "temp" or the name of an attached db). This
  72199. ** function returns the index of the named database in db->aDb[], or
  72200. ** -1 if the named db cannot be found.
  72201. */
  72202. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  72203. int i = -1; /* Database number */
  72204. if( zName ){
  72205. Db *pDb;
  72206. int n = sqlite3Strlen30(zName);
  72207. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  72208. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  72209. 0==sqlite3StrICmp(pDb->zName, zName) ){
  72210. break;
  72211. }
  72212. }
  72213. }
  72214. return i;
  72215. }
  72216. /*
  72217. ** The token *pName contains the name of a database (either "main" or
  72218. ** "temp" or the name of an attached db). This routine returns the
  72219. ** index of the named database in db->aDb[], or -1 if the named db
  72220. ** does not exist.
  72221. */
  72222. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  72223. int i; /* Database number */
  72224. char *zName; /* Name we are searching for */
  72225. zName = sqlite3NameFromToken(db, pName);
  72226. i = sqlite3FindDbName(db, zName);
  72227. sqlite3DbFree(db, zName);
  72228. return i;
  72229. }
  72230. /* The table or view or trigger name is passed to this routine via tokens
  72231. ** pName1 and pName2. If the table name was fully qualified, for example:
  72232. **
  72233. ** CREATE TABLE xxx.yyy (...);
  72234. **
  72235. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  72236. ** the table name is not fully qualified, i.e.:
  72237. **
  72238. ** CREATE TABLE yyy(...);
  72239. **
  72240. ** Then pName1 is set to "yyy" and pName2 is "".
  72241. **
  72242. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  72243. ** pName2) that stores the unqualified table name. The index of the
  72244. ** database "xxx" is returned.
  72245. */
  72246. SQLITE_PRIVATE int sqlite3TwoPartName(
  72247. Parse *pParse, /* Parsing and code generating context */
  72248. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  72249. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  72250. Token **pUnqual /* Write the unqualified object name here */
  72251. ){
  72252. int iDb; /* Database holding the object */
  72253. sqlite3 *db = pParse->db;
  72254. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  72255. if( db->init.busy ) {
  72256. sqlite3ErrorMsg(pParse, "corrupt database");
  72257. pParse->nErr++;
  72258. return -1;
  72259. }
  72260. *pUnqual = pName2;
  72261. iDb = sqlite3FindDb(db, pName1);
  72262. if( iDb<0 ){
  72263. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  72264. pParse->nErr++;
  72265. return -1;
  72266. }
  72267. }else{
  72268. assert( db->init.iDb==0 || db->init.busy );
  72269. iDb = db->init.iDb;
  72270. *pUnqual = pName1;
  72271. }
  72272. return iDb;
  72273. }
  72274. /*
  72275. ** This routine is used to check if the UTF-8 string zName is a legal
  72276. ** unqualified name for a new schema object (table, index, view or
  72277. ** trigger). All names are legal except those that begin with the string
  72278. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  72279. ** is reserved for internal use.
  72280. */
  72281. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  72282. if( !pParse->db->init.busy && pParse->nested==0
  72283. && (pParse->db->flags & SQLITE_WriteSchema)==0
  72284. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  72285. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  72286. return SQLITE_ERROR;
  72287. }
  72288. return SQLITE_OK;
  72289. }
  72290. /*
  72291. ** Begin constructing a new table representation in memory. This is
  72292. ** the first of several action routines that get called in response
  72293. ** to a CREATE TABLE statement. In particular, this routine is called
  72294. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  72295. ** flag is true if the table should be stored in the auxiliary database
  72296. ** file instead of in the main database file. This is normally the case
  72297. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  72298. ** CREATE and TABLE.
  72299. **
  72300. ** The new table record is initialized and put in pParse->pNewTable.
  72301. ** As more of the CREATE TABLE statement is parsed, additional action
  72302. ** routines will be called to add more information to this record.
  72303. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  72304. ** is called to complete the construction of the new table record.
  72305. */
  72306. SQLITE_PRIVATE void sqlite3StartTable(
  72307. Parse *pParse, /* Parser context */
  72308. Token *pName1, /* First part of the name of the table or view */
  72309. Token *pName2, /* Second part of the name of the table or view */
  72310. int isTemp, /* True if this is a TEMP table */
  72311. int isView, /* True if this is a VIEW */
  72312. int isVirtual, /* True if this is a VIRTUAL table */
  72313. int noErr /* Do nothing if table already exists */
  72314. ){
  72315. Table *pTable;
  72316. char *zName = 0; /* The name of the new table */
  72317. sqlite3 *db = pParse->db;
  72318. Vdbe *v;
  72319. int iDb; /* Database number to create the table in */
  72320. Token *pName; /* Unqualified name of the table to create */
  72321. /* The table or view name to create is passed to this routine via tokens
  72322. ** pName1 and pName2. If the table name was fully qualified, for example:
  72323. **
  72324. ** CREATE TABLE xxx.yyy (...);
  72325. **
  72326. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  72327. ** the table name is not fully qualified, i.e.:
  72328. **
  72329. ** CREATE TABLE yyy(...);
  72330. **
  72331. ** Then pName1 is set to "yyy" and pName2 is "".
  72332. **
  72333. ** The call below sets the pName pointer to point at the token (pName1 or
  72334. ** pName2) that stores the unqualified table name. The variable iDb is
  72335. ** set to the index of the database that the table or view is to be
  72336. ** created in.
  72337. */
  72338. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  72339. if( iDb<0 ) return;
  72340. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  72341. /* If creating a temp table, the name may not be qualified. Unless
  72342. ** the database name is "temp" anyway. */
  72343. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  72344. return;
  72345. }
  72346. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  72347. pParse->sNameToken = *pName;
  72348. zName = sqlite3NameFromToken(db, pName);
  72349. if( zName==0 ) return;
  72350. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  72351. goto begin_table_error;
  72352. }
  72353. if( db->init.iDb==1 ) isTemp = 1;
  72354. #ifndef SQLITE_OMIT_AUTHORIZATION
  72355. assert( (isTemp & 1)==isTemp );
  72356. {
  72357. int code;
  72358. char *zDb = db->aDb[iDb].zName;
  72359. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  72360. goto begin_table_error;
  72361. }
  72362. if( isView ){
  72363. if( !OMIT_TEMPDB && isTemp ){
  72364. code = SQLITE_CREATE_TEMP_VIEW;
  72365. }else{
  72366. code = SQLITE_CREATE_VIEW;
  72367. }
  72368. }else{
  72369. if( !OMIT_TEMPDB && isTemp ){
  72370. code = SQLITE_CREATE_TEMP_TABLE;
  72371. }else{
  72372. code = SQLITE_CREATE_TABLE;
  72373. }
  72374. }
  72375. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  72376. goto begin_table_error;
  72377. }
  72378. }
  72379. #endif
  72380. /* Make sure the new table name does not collide with an existing
  72381. ** index or table name in the same database. Issue an error message if
  72382. ** it does. The exception is if the statement being parsed was passed
  72383. ** to an sqlite3_declare_vtab() call. In that case only the column names
  72384. ** and types will be used, so there is no need to test for namespace
  72385. ** collisions.
  72386. */
  72387. if( !IN_DECLARE_VTAB ){
  72388. char *zDb = db->aDb[iDb].zName;
  72389. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  72390. goto begin_table_error;
  72391. }
  72392. pTable = sqlite3FindTable(db, zName, zDb);
  72393. if( pTable ){
  72394. if( !noErr ){
  72395. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  72396. }else{
  72397. assert( !db->init.busy );
  72398. sqlite3CodeVerifySchema(pParse, iDb);
  72399. }
  72400. goto begin_table_error;
  72401. }
  72402. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  72403. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  72404. goto begin_table_error;
  72405. }
  72406. }
  72407. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  72408. if( pTable==0 ){
  72409. db->mallocFailed = 1;
  72410. pParse->rc = SQLITE_NOMEM;
  72411. pParse->nErr++;
  72412. goto begin_table_error;
  72413. }
  72414. pTable->zName = zName;
  72415. pTable->iPKey = -1;
  72416. pTable->pSchema = db->aDb[iDb].pSchema;
  72417. pTable->nRef = 1;
  72418. pTable->nRowEst = 1000000;
  72419. assert( pParse->pNewTable==0 );
  72420. pParse->pNewTable = pTable;
  72421. /* If this is the magic sqlite_sequence table used by autoincrement,
  72422. ** then record a pointer to this table in the main database structure
  72423. ** so that INSERT can find the table easily.
  72424. */
  72425. #ifndef SQLITE_OMIT_AUTOINCREMENT
  72426. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  72427. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  72428. pTable->pSchema->pSeqTab = pTable;
  72429. }
  72430. #endif
  72431. /* Begin generating the code that will insert the table record into
  72432. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  72433. ** and allocate the record number for the table entry now. Before any
  72434. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  72435. ** indices to be created and the table record must come before the
  72436. ** indices. Hence, the record number for the table must be allocated
  72437. ** now.
  72438. */
  72439. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  72440. int j1;
  72441. int fileFormat;
  72442. int reg1, reg2, reg3;
  72443. sqlite3BeginWriteOperation(pParse, 0, iDb);
  72444. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72445. if( isVirtual ){
  72446. sqlite3VdbeAddOp0(v, OP_VBegin);
  72447. }
  72448. #endif
  72449. /* If the file format and encoding in the database have not been set,
  72450. ** set them now.
  72451. */
  72452. reg1 = pParse->regRowid = ++pParse->nMem;
  72453. reg2 = pParse->regRoot = ++pParse->nMem;
  72454. reg3 = ++pParse->nMem;
  72455. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  72456. sqlite3VdbeUsesBtree(v, iDb);
  72457. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  72458. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  72459. 1 : SQLITE_MAX_FILE_FORMAT;
  72460. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  72461. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  72462. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  72463. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  72464. sqlite3VdbeJumpHere(v, j1);
  72465. /* This just creates a place-holder record in the sqlite_master table.
  72466. ** The record created does not contain anything yet. It will be replaced
  72467. ** by the real entry in code generated at sqlite3EndTable().
  72468. **
  72469. ** The rowid for the new entry is left in register pParse->regRowid.
  72470. ** The root page number of the new table is left in reg pParse->regRoot.
  72471. ** The rowid and root page number values are needed by the code that
  72472. ** sqlite3EndTable will generate.
  72473. */
  72474. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  72475. if( isView || isVirtual ){
  72476. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  72477. }else
  72478. #endif
  72479. {
  72480. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  72481. }
  72482. sqlite3OpenMasterTable(pParse, iDb);
  72483. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  72484. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  72485. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  72486. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  72487. sqlite3VdbeAddOp0(v, OP_Close);
  72488. }
  72489. /* Normal (non-error) return. */
  72490. return;
  72491. /* If an error occurs, we jump here */
  72492. begin_table_error:
  72493. sqlite3DbFree(db, zName);
  72494. return;
  72495. }
  72496. /*
  72497. ** This macro is used to compare two strings in a case-insensitive manner.
  72498. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  72499. ** produces larger code.
  72500. **
  72501. ** WARNING: This macro is not compatible with the strcmp() family. It
  72502. ** returns true if the two strings are equal, otherwise false.
  72503. */
  72504. #define STRICMP(x, y) (\
  72505. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  72506. sqlite3UpperToLower[*(unsigned char *)(y)] \
  72507. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  72508. /*
  72509. ** Add a new column to the table currently being constructed.
  72510. **
  72511. ** The parser calls this routine once for each column declaration
  72512. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  72513. ** first to get things going. Then this routine is called for each
  72514. ** column.
  72515. */
  72516. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  72517. Table *p;
  72518. int i;
  72519. char *z;
  72520. Column *pCol;
  72521. sqlite3 *db = pParse->db;
  72522. if( (p = pParse->pNewTable)==0 ) return;
  72523. #if SQLITE_MAX_COLUMN
  72524. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  72525. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  72526. return;
  72527. }
  72528. #endif
  72529. z = sqlite3NameFromToken(db, pName);
  72530. if( z==0 ) return;
  72531. for(i=0; i<p->nCol; i++){
  72532. if( STRICMP(z, p->aCol[i].zName) ){
  72533. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  72534. sqlite3DbFree(db, z);
  72535. return;
  72536. }
  72537. }
  72538. if( (p->nCol & 0x7)==0 ){
  72539. Column *aNew;
  72540. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  72541. if( aNew==0 ){
  72542. sqlite3DbFree(db, z);
  72543. return;
  72544. }
  72545. p->aCol = aNew;
  72546. }
  72547. pCol = &p->aCol[p->nCol];
  72548. memset(pCol, 0, sizeof(p->aCol[0]));
  72549. pCol->zName = z;
  72550. /* If there is no type specified, columns have the default affinity
  72551. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  72552. ** be called next to set pCol->affinity correctly.
  72553. */
  72554. pCol->affinity = SQLITE_AFF_NONE;
  72555. p->nCol++;
  72556. }
  72557. /*
  72558. ** This routine is called by the parser while in the middle of
  72559. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  72560. ** been seen on a column. This routine sets the notNull flag on
  72561. ** the column currently under construction.
  72562. */
  72563. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  72564. Table *p;
  72565. p = pParse->pNewTable;
  72566. if( p==0 || NEVER(p->nCol<1) ) return;
  72567. p->aCol[p->nCol-1].notNull = (u8)onError;
  72568. }
  72569. /*
  72570. ** Scan the column type name zType (length nType) and return the
  72571. ** associated affinity type.
  72572. **
  72573. ** This routine does a case-independent search of zType for the
  72574. ** substrings in the following table. If one of the substrings is
  72575. ** found, the corresponding affinity is returned. If zType contains
  72576. ** more than one of the substrings, entries toward the top of
  72577. ** the table take priority. For example, if zType is 'BLOBINT',
  72578. ** SQLITE_AFF_INTEGER is returned.
  72579. **
  72580. ** Substring | Affinity
  72581. ** --------------------------------
  72582. ** 'INT' | SQLITE_AFF_INTEGER
  72583. ** 'CHAR' | SQLITE_AFF_TEXT
  72584. ** 'CLOB' | SQLITE_AFF_TEXT
  72585. ** 'TEXT' | SQLITE_AFF_TEXT
  72586. ** 'BLOB' | SQLITE_AFF_NONE
  72587. ** 'REAL' | SQLITE_AFF_REAL
  72588. ** 'FLOA' | SQLITE_AFF_REAL
  72589. ** 'DOUB' | SQLITE_AFF_REAL
  72590. **
  72591. ** If none of the substrings in the above table are found,
  72592. ** SQLITE_AFF_NUMERIC is returned.
  72593. */
  72594. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
  72595. u32 h = 0;
  72596. char aff = SQLITE_AFF_NUMERIC;
  72597. if( zIn ) while( zIn[0] ){
  72598. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  72599. zIn++;
  72600. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  72601. aff = SQLITE_AFF_TEXT;
  72602. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  72603. aff = SQLITE_AFF_TEXT;
  72604. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  72605. aff = SQLITE_AFF_TEXT;
  72606. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  72607. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  72608. aff = SQLITE_AFF_NONE;
  72609. #ifndef SQLITE_OMIT_FLOATING_POINT
  72610. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  72611. && aff==SQLITE_AFF_NUMERIC ){
  72612. aff = SQLITE_AFF_REAL;
  72613. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  72614. && aff==SQLITE_AFF_NUMERIC ){
  72615. aff = SQLITE_AFF_REAL;
  72616. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  72617. && aff==SQLITE_AFF_NUMERIC ){
  72618. aff = SQLITE_AFF_REAL;
  72619. #endif
  72620. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  72621. aff = SQLITE_AFF_INTEGER;
  72622. break;
  72623. }
  72624. }
  72625. return aff;
  72626. }
  72627. /*
  72628. ** This routine is called by the parser while in the middle of
  72629. ** parsing a CREATE TABLE statement. The pFirst token is the first
  72630. ** token in the sequence of tokens that describe the type of the
  72631. ** column currently under construction. pLast is the last token
  72632. ** in the sequence. Use this information to construct a string
  72633. ** that contains the typename of the column and store that string
  72634. ** in zType.
  72635. */
  72636. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  72637. Table *p;
  72638. Column *pCol;
  72639. p = pParse->pNewTable;
  72640. if( p==0 || NEVER(p->nCol<1) ) return;
  72641. pCol = &p->aCol[p->nCol-1];
  72642. assert( pCol->zType==0 );
  72643. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  72644. pCol->affinity = sqlite3AffinityType(pCol->zType);
  72645. }
  72646. /*
  72647. ** The expression is the default value for the most recently added column
  72648. ** of the table currently under construction.
  72649. **
  72650. ** Default value expressions must be constant. Raise an exception if this
  72651. ** is not the case.
  72652. **
  72653. ** This routine is called by the parser while in the middle of
  72654. ** parsing a CREATE TABLE statement.
  72655. */
  72656. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  72657. Table *p;
  72658. Column *pCol;
  72659. sqlite3 *db = pParse->db;
  72660. p = pParse->pNewTable;
  72661. if( p!=0 ){
  72662. pCol = &(p->aCol[p->nCol-1]);
  72663. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  72664. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  72665. pCol->zName);
  72666. }else{
  72667. /* A copy of pExpr is used instead of the original, as pExpr contains
  72668. ** tokens that point to volatile memory. The 'span' of the expression
  72669. ** is required by pragma table_info.
  72670. */
  72671. sqlite3ExprDelete(db, pCol->pDflt);
  72672. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  72673. sqlite3DbFree(db, pCol->zDflt);
  72674. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  72675. (int)(pSpan->zEnd - pSpan->zStart));
  72676. }
  72677. }
  72678. sqlite3ExprDelete(db, pSpan->pExpr);
  72679. }
  72680. /*
  72681. ** Designate the PRIMARY KEY for the table. pList is a list of names
  72682. ** of columns that form the primary key. If pList is NULL, then the
  72683. ** most recently added column of the table is the primary key.
  72684. **
  72685. ** A table can have at most one primary key. If the table already has
  72686. ** a primary key (and this is the second primary key) then create an
  72687. ** error.
  72688. **
  72689. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  72690. ** then we will try to use that column as the rowid. Set the Table.iPKey
  72691. ** field of the table under construction to be the index of the
  72692. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  72693. ** no INTEGER PRIMARY KEY.
  72694. **
  72695. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  72696. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  72697. */
  72698. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  72699. Parse *pParse, /* Parsing context */
  72700. ExprList *pList, /* List of field names to be indexed */
  72701. int onError, /* What to do with a uniqueness conflict */
  72702. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  72703. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  72704. ){
  72705. Table *pTab = pParse->pNewTable;
  72706. char *zType = 0;
  72707. int iCol = -1, i;
  72708. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  72709. if( pTab->tabFlags & TF_HasPrimaryKey ){
  72710. sqlite3ErrorMsg(pParse,
  72711. "table \"%s\" has more than one primary key", pTab->zName);
  72712. goto primary_key_exit;
  72713. }
  72714. pTab->tabFlags |= TF_HasPrimaryKey;
  72715. if( pList==0 ){
  72716. iCol = pTab->nCol - 1;
  72717. pTab->aCol[iCol].isPrimKey = 1;
  72718. }else{
  72719. for(i=0; i<pList->nExpr; i++){
  72720. for(iCol=0; iCol<pTab->nCol; iCol++){
  72721. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  72722. break;
  72723. }
  72724. }
  72725. if( iCol<pTab->nCol ){
  72726. pTab->aCol[iCol].isPrimKey = 1;
  72727. }
  72728. }
  72729. if( pList->nExpr>1 ) iCol = -1;
  72730. }
  72731. if( iCol>=0 && iCol<pTab->nCol ){
  72732. zType = pTab->aCol[iCol].zType;
  72733. }
  72734. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  72735. && sortOrder==SQLITE_SO_ASC ){
  72736. pTab->iPKey = iCol;
  72737. pTab->keyConf = (u8)onError;
  72738. assert( autoInc==0 || autoInc==1 );
  72739. pTab->tabFlags |= autoInc*TF_Autoincrement;
  72740. }else if( autoInc ){
  72741. #ifndef SQLITE_OMIT_AUTOINCREMENT
  72742. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  72743. "INTEGER PRIMARY KEY");
  72744. #endif
  72745. }else{
  72746. Index *p;
  72747. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
  72748. if( p ){
  72749. p->autoIndex = 2;
  72750. }
  72751. pList = 0;
  72752. }
  72753. primary_key_exit:
  72754. sqlite3ExprListDelete(pParse->db, pList);
  72755. return;
  72756. }
  72757. /*
  72758. ** Add a new CHECK constraint to the table currently under construction.
  72759. */
  72760. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  72761. Parse *pParse, /* Parsing context */
  72762. Expr *pCheckExpr /* The check expression */
  72763. ){
  72764. sqlite3 *db = pParse->db;
  72765. #ifndef SQLITE_OMIT_CHECK
  72766. Table *pTab = pParse->pNewTable;
  72767. if( pTab && !IN_DECLARE_VTAB ){
  72768. pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
  72769. }else
  72770. #endif
  72771. {
  72772. sqlite3ExprDelete(db, pCheckExpr);
  72773. }
  72774. }
  72775. /*
  72776. ** Set the collation function of the most recently parsed table column
  72777. ** to the CollSeq given.
  72778. */
  72779. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  72780. Table *p;
  72781. int i;
  72782. char *zColl; /* Dequoted name of collation sequence */
  72783. sqlite3 *db;
  72784. if( (p = pParse->pNewTable)==0 ) return;
  72785. i = p->nCol-1;
  72786. db = pParse->db;
  72787. zColl = sqlite3NameFromToken(db, pToken);
  72788. if( !zColl ) return;
  72789. if( sqlite3LocateCollSeq(pParse, zColl) ){
  72790. Index *pIdx;
  72791. p->aCol[i].zColl = zColl;
  72792. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  72793. ** then an index may have been created on this column before the
  72794. ** collation type was added. Correct this if it is the case.
  72795. */
  72796. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  72797. assert( pIdx->nColumn==1 );
  72798. if( pIdx->aiColumn[0]==i ){
  72799. pIdx->azColl[0] = p->aCol[i].zColl;
  72800. }
  72801. }
  72802. }else{
  72803. sqlite3DbFree(db, zColl);
  72804. }
  72805. }
  72806. /*
  72807. ** This function returns the collation sequence for database native text
  72808. ** encoding identified by the string zName, length nName.
  72809. **
  72810. ** If the requested collation sequence is not available, or not available
  72811. ** in the database native encoding, the collation factory is invoked to
  72812. ** request it. If the collation factory does not supply such a sequence,
  72813. ** and the sequence is available in another text encoding, then that is
  72814. ** returned instead.
  72815. **
  72816. ** If no versions of the requested collations sequence are available, or
  72817. ** another error occurs, NULL is returned and an error message written into
  72818. ** pParse.
  72819. **
  72820. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  72821. ** invokes the collation factory if the named collation cannot be found
  72822. ** and generates an error message.
  72823. **
  72824. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  72825. */
  72826. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  72827. sqlite3 *db = pParse->db;
  72828. u8 enc = ENC(db);
  72829. u8 initbusy = db->init.busy;
  72830. CollSeq *pColl;
  72831. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  72832. if( !initbusy && (!pColl || !pColl->xCmp) ){
  72833. pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
  72834. if( !pColl ){
  72835. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  72836. }
  72837. }
  72838. return pColl;
  72839. }
  72840. /*
  72841. ** Generate code that will increment the schema cookie.
  72842. **
  72843. ** The schema cookie is used to determine when the schema for the
  72844. ** database changes. After each schema change, the cookie value
  72845. ** changes. When a process first reads the schema it records the
  72846. ** cookie. Thereafter, whenever it goes to access the database,
  72847. ** it checks the cookie to make sure the schema has not changed
  72848. ** since it was last read.
  72849. **
  72850. ** This plan is not completely bullet-proof. It is possible for
  72851. ** the schema to change multiple times and for the cookie to be
  72852. ** set back to prior value. But schema changes are infrequent
  72853. ** and the probability of hitting the same cookie value is only
  72854. ** 1 chance in 2^32. So we're safe enough.
  72855. */
  72856. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  72857. int r1 = sqlite3GetTempReg(pParse);
  72858. sqlite3 *db = pParse->db;
  72859. Vdbe *v = pParse->pVdbe;
  72860. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  72861. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  72862. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  72863. sqlite3ReleaseTempReg(pParse, r1);
  72864. }
  72865. /*
  72866. ** Measure the number of characters needed to output the given
  72867. ** identifier. The number returned includes any quotes used
  72868. ** but does not include the null terminator.
  72869. **
  72870. ** The estimate is conservative. It might be larger that what is
  72871. ** really needed.
  72872. */
  72873. static int identLength(const char *z){
  72874. int n;
  72875. for(n=0; *z; n++, z++){
  72876. if( *z=='"' ){ n++; }
  72877. }
  72878. return n + 2;
  72879. }
  72880. /*
  72881. ** The first parameter is a pointer to an output buffer. The second
  72882. ** parameter is a pointer to an integer that contains the offset at
  72883. ** which to write into the output buffer. This function copies the
  72884. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  72885. ** to the specified offset in the buffer and updates *pIdx to refer
  72886. ** to the first byte after the last byte written before returning.
  72887. **
  72888. ** If the string zSignedIdent consists entirely of alpha-numeric
  72889. ** characters, does not begin with a digit and is not an SQL keyword,
  72890. ** then it is copied to the output buffer exactly as it is. Otherwise,
  72891. ** it is quoted using double-quotes.
  72892. */
  72893. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  72894. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  72895. int i, j, needQuote;
  72896. i = *pIdx;
  72897. for(j=0; zIdent[j]; j++){
  72898. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  72899. }
  72900. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  72901. if( !needQuote ){
  72902. needQuote = zIdent[j];
  72903. }
  72904. if( needQuote ) z[i++] = '"';
  72905. for(j=0; zIdent[j]; j++){
  72906. z[i++] = zIdent[j];
  72907. if( zIdent[j]=='"' ) z[i++] = '"';
  72908. }
  72909. if( needQuote ) z[i++] = '"';
  72910. z[i] = 0;
  72911. *pIdx = i;
  72912. }
  72913. /*
  72914. ** Generate a CREATE TABLE statement appropriate for the given
  72915. ** table. Memory to hold the text of the statement is obtained
  72916. ** from sqliteMalloc() and must be freed by the calling function.
  72917. */
  72918. static char *createTableStmt(sqlite3 *db, Table *p){
  72919. int i, k, n;
  72920. char *zStmt;
  72921. char *zSep, *zSep2, *zEnd;
  72922. Column *pCol;
  72923. n = 0;
  72924. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  72925. n += identLength(pCol->zName) + 5;
  72926. }
  72927. n += identLength(p->zName);
  72928. if( n<50 ){
  72929. zSep = "";
  72930. zSep2 = ",";
  72931. zEnd = ")";
  72932. }else{
  72933. zSep = "\n ";
  72934. zSep2 = ",\n ";
  72935. zEnd = "\n)";
  72936. }
  72937. n += 35 + 6*p->nCol;
  72938. zStmt = sqlite3DbMallocRaw(0, n);
  72939. if( zStmt==0 ){
  72940. db->mallocFailed = 1;
  72941. return 0;
  72942. }
  72943. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  72944. k = sqlite3Strlen30(zStmt);
  72945. identPut(zStmt, &k, p->zName);
  72946. zStmt[k++] = '(';
  72947. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  72948. static const char * const azType[] = {
  72949. /* SQLITE_AFF_TEXT */ " TEXT",
  72950. /* SQLITE_AFF_NONE */ "",
  72951. /* SQLITE_AFF_NUMERIC */ " NUM",
  72952. /* SQLITE_AFF_INTEGER */ " INT",
  72953. /* SQLITE_AFF_REAL */ " REAL"
  72954. };
  72955. int len;
  72956. const char *zType;
  72957. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  72958. k += sqlite3Strlen30(&zStmt[k]);
  72959. zSep = zSep2;
  72960. identPut(zStmt, &k, pCol->zName);
  72961. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  72962. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  72963. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  72964. testcase( pCol->affinity==SQLITE_AFF_NONE );
  72965. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  72966. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  72967. testcase( pCol->affinity==SQLITE_AFF_REAL );
  72968. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  72969. len = sqlite3Strlen30(zType);
  72970. assert( pCol->affinity==SQLITE_AFF_NONE
  72971. || pCol->affinity==sqlite3AffinityType(zType) );
  72972. memcpy(&zStmt[k], zType, len);
  72973. k += len;
  72974. assert( k<=n );
  72975. }
  72976. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  72977. return zStmt;
  72978. }
  72979. /*
  72980. ** This routine is called to report the final ")" that terminates
  72981. ** a CREATE TABLE statement.
  72982. **
  72983. ** The table structure that other action routines have been building
  72984. ** is added to the internal hash tables, assuming no errors have
  72985. ** occurred.
  72986. **
  72987. ** An entry for the table is made in the master table on disk, unless
  72988. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  72989. ** it means we are reading the sqlite_master table because we just
  72990. ** connected to the database or because the sqlite_master table has
  72991. ** recently changed, so the entry for this table already exists in
  72992. ** the sqlite_master table. We do not want to create it again.
  72993. **
  72994. ** If the pSelect argument is not NULL, it means that this routine
  72995. ** was called to create a table generated from a
  72996. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  72997. ** the new table will match the result set of the SELECT.
  72998. */
  72999. SQLITE_PRIVATE void sqlite3EndTable(
  73000. Parse *pParse, /* Parse context */
  73001. Token *pCons, /* The ',' token after the last column defn. */
  73002. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  73003. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  73004. ){
  73005. Table *p;
  73006. sqlite3 *db = pParse->db;
  73007. int iDb;
  73008. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  73009. return;
  73010. }
  73011. p = pParse->pNewTable;
  73012. if( p==0 ) return;
  73013. assert( !db->init.busy || !pSelect );
  73014. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  73015. #ifndef SQLITE_OMIT_CHECK
  73016. /* Resolve names in all CHECK constraint expressions.
  73017. */
  73018. if( p->pCheck ){
  73019. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  73020. NameContext sNC; /* Name context for pParse->pNewTable */
  73021. memset(&sNC, 0, sizeof(sNC));
  73022. memset(&sSrc, 0, sizeof(sSrc));
  73023. sSrc.nSrc = 1;
  73024. sSrc.a[0].zName = p->zName;
  73025. sSrc.a[0].pTab = p;
  73026. sSrc.a[0].iCursor = -1;
  73027. sNC.pParse = pParse;
  73028. sNC.pSrcList = &sSrc;
  73029. sNC.isCheck = 1;
  73030. if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
  73031. return;
  73032. }
  73033. }
  73034. #endif /* !defined(SQLITE_OMIT_CHECK) */
  73035. /* If the db->init.busy is 1 it means we are reading the SQL off the
  73036. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  73037. ** So do not write to the disk again. Extract the root page number
  73038. ** for the table from the db->init.newTnum field. (The page number
  73039. ** should have been put there by the sqliteOpenCb routine.)
  73040. */
  73041. if( db->init.busy ){
  73042. p->tnum = db->init.newTnum;
  73043. }
  73044. /* If not initializing, then create a record for the new table
  73045. ** in the SQLITE_MASTER table of the database.
  73046. **
  73047. ** If this is a TEMPORARY table, write the entry into the auxiliary
  73048. ** file instead of into the main database file.
  73049. */
  73050. if( !db->init.busy ){
  73051. int n;
  73052. Vdbe *v;
  73053. char *zType; /* "view" or "table" */
  73054. char *zType2; /* "VIEW" or "TABLE" */
  73055. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  73056. v = sqlite3GetVdbe(pParse);
  73057. if( NEVER(v==0) ) return;
  73058. sqlite3VdbeAddOp1(v, OP_Close, 0);
  73059. /*
  73060. ** Initialize zType for the new view or table.
  73061. */
  73062. if( p->pSelect==0 ){
  73063. /* A regular table */
  73064. zType = "table";
  73065. zType2 = "TABLE";
  73066. #ifndef SQLITE_OMIT_VIEW
  73067. }else{
  73068. /* A view */
  73069. zType = "view";
  73070. zType2 = "VIEW";
  73071. #endif
  73072. }
  73073. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  73074. ** statement to populate the new table. The root-page number for the
  73075. ** new table is in register pParse->regRoot.
  73076. **
  73077. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  73078. ** suitable state to query for the column names and types to be used
  73079. ** by the new table.
  73080. **
  73081. ** A shared-cache write-lock is not required to write to the new table,
  73082. ** as a schema-lock must have already been obtained to create it. Since
  73083. ** a schema-lock excludes all other database users, the write-lock would
  73084. ** be redundant.
  73085. */
  73086. if( pSelect ){
  73087. SelectDest dest;
  73088. Table *pSelTab;
  73089. assert(pParse->nTab==1);
  73090. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  73091. sqlite3VdbeChangeP5(v, 1);
  73092. pParse->nTab = 2;
  73093. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  73094. sqlite3Select(pParse, pSelect, &dest);
  73095. sqlite3VdbeAddOp1(v, OP_Close, 1);
  73096. if( pParse->nErr==0 ){
  73097. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  73098. if( pSelTab==0 ) return;
  73099. assert( p->aCol==0 );
  73100. p->nCol = pSelTab->nCol;
  73101. p->aCol = pSelTab->aCol;
  73102. pSelTab->nCol = 0;
  73103. pSelTab->aCol = 0;
  73104. sqlite3DeleteTable(db, pSelTab);
  73105. }
  73106. }
  73107. /* Compute the complete text of the CREATE statement */
  73108. if( pSelect ){
  73109. zStmt = createTableStmt(db, p);
  73110. }else{
  73111. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  73112. zStmt = sqlite3MPrintf(db,
  73113. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  73114. );
  73115. }
  73116. /* A slot for the record has already been allocated in the
  73117. ** SQLITE_MASTER table. We just need to update that slot with all
  73118. ** the information we've collected.
  73119. */
  73120. sqlite3NestedParse(pParse,
  73121. "UPDATE %Q.%s "
  73122. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  73123. "WHERE rowid=#%d",
  73124. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  73125. zType,
  73126. p->zName,
  73127. p->zName,
  73128. pParse->regRoot,
  73129. zStmt,
  73130. pParse->regRowid
  73131. );
  73132. sqlite3DbFree(db, zStmt);
  73133. sqlite3ChangeCookie(pParse, iDb);
  73134. #ifndef SQLITE_OMIT_AUTOINCREMENT
  73135. /* Check to see if we need to create an sqlite_sequence table for
  73136. ** keeping track of autoincrement keys.
  73137. */
  73138. if( p->tabFlags & TF_Autoincrement ){
  73139. Db *pDb = &db->aDb[iDb];
  73140. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  73141. if( pDb->pSchema->pSeqTab==0 ){
  73142. sqlite3NestedParse(pParse,
  73143. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  73144. pDb->zName
  73145. );
  73146. }
  73147. }
  73148. #endif
  73149. /* Reparse everything to update our internal data structures */
  73150. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
  73151. sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
  73152. }
  73153. /* Add the table to the in-memory representation of the database.
  73154. */
  73155. if( db->init.busy ){
  73156. Table *pOld;
  73157. Schema *pSchema = p->pSchema;
  73158. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  73159. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  73160. sqlite3Strlen30(p->zName),p);
  73161. if( pOld ){
  73162. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  73163. db->mallocFailed = 1;
  73164. return;
  73165. }
  73166. pParse->pNewTable = 0;
  73167. db->nTable++;
  73168. db->flags |= SQLITE_InternChanges;
  73169. #ifndef SQLITE_OMIT_ALTERTABLE
  73170. if( !p->pSelect ){
  73171. const char *zName = (const char *)pParse->sNameToken.z;
  73172. int nName;
  73173. assert( !pSelect && pCons && pEnd );
  73174. if( pCons->z==0 ){
  73175. pCons = pEnd;
  73176. }
  73177. nName = (int)((const char *)pCons->z - zName);
  73178. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  73179. }
  73180. #endif
  73181. }
  73182. }
  73183. #ifndef SQLITE_OMIT_VIEW
  73184. /*
  73185. ** The parser calls this routine in order to create a new VIEW
  73186. */
  73187. SQLITE_PRIVATE void sqlite3CreateView(
  73188. Parse *pParse, /* The parsing context */
  73189. Token *pBegin, /* The CREATE token that begins the statement */
  73190. Token *pName1, /* The token that holds the name of the view */
  73191. Token *pName2, /* The token that holds the name of the view */
  73192. Select *pSelect, /* A SELECT statement that will become the new view */
  73193. int isTemp, /* TRUE for a TEMPORARY view */
  73194. int noErr /* Suppress error messages if VIEW already exists */
  73195. ){
  73196. Table *p;
  73197. int n;
  73198. const char *z;
  73199. Token sEnd;
  73200. DbFixer sFix;
  73201. Token *pName;
  73202. int iDb;
  73203. sqlite3 *db = pParse->db;
  73204. if( pParse->nVar>0 ){
  73205. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  73206. sqlite3SelectDelete(db, pSelect);
  73207. return;
  73208. }
  73209. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  73210. p = pParse->pNewTable;
  73211. if( p==0 || pParse->nErr ){
  73212. sqlite3SelectDelete(db, pSelect);
  73213. return;
  73214. }
  73215. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  73216. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  73217. if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
  73218. && sqlite3FixSelect(&sFix, pSelect)
  73219. ){
  73220. sqlite3SelectDelete(db, pSelect);
  73221. return;
  73222. }
  73223. /* Make a copy of the entire SELECT statement that defines the view.
  73224. ** This will force all the Expr.token.z values to be dynamically
  73225. ** allocated rather than point to the input string - which means that
  73226. ** they will persist after the current sqlite3_exec() call returns.
  73227. */
  73228. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  73229. sqlite3SelectDelete(db, pSelect);
  73230. if( db->mallocFailed ){
  73231. return;
  73232. }
  73233. if( !db->init.busy ){
  73234. sqlite3ViewGetColumnNames(pParse, p);
  73235. }
  73236. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  73237. ** the end.
  73238. */
  73239. sEnd = pParse->sLastToken;
  73240. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  73241. sEnd.z += sEnd.n;
  73242. }
  73243. sEnd.n = 0;
  73244. n = (int)(sEnd.z - pBegin->z);
  73245. z = pBegin->z;
  73246. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  73247. sEnd.z = &z[n-1];
  73248. sEnd.n = 1;
  73249. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  73250. sqlite3EndTable(pParse, 0, &sEnd, 0);
  73251. return;
  73252. }
  73253. #endif /* SQLITE_OMIT_VIEW */
  73254. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  73255. /*
  73256. ** The Table structure pTable is really a VIEW. Fill in the names of
  73257. ** the columns of the view in the pTable structure. Return the number
  73258. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  73259. */
  73260. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  73261. Table *pSelTab; /* A fake table from which we get the result set */
  73262. Select *pSel; /* Copy of the SELECT that implements the view */
  73263. int nErr = 0; /* Number of errors encountered */
  73264. int n; /* Temporarily holds the number of cursors assigned */
  73265. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  73266. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  73267. assert( pTable );
  73268. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73269. if( sqlite3VtabCallConnect(pParse, pTable) ){
  73270. return SQLITE_ERROR;
  73271. }
  73272. if( IsVirtual(pTable) ) return 0;
  73273. #endif
  73274. #ifndef SQLITE_OMIT_VIEW
  73275. /* A positive nCol means the columns names for this view are
  73276. ** already known.
  73277. */
  73278. if( pTable->nCol>0 ) return 0;
  73279. /* A negative nCol is a special marker meaning that we are currently
  73280. ** trying to compute the column names. If we enter this routine with
  73281. ** a negative nCol, it means two or more views form a loop, like this:
  73282. **
  73283. ** CREATE VIEW one AS SELECT * FROM two;
  73284. ** CREATE VIEW two AS SELECT * FROM one;
  73285. **
  73286. ** Actually, the error above is now caught prior to reaching this point.
  73287. ** But the following test is still important as it does come up
  73288. ** in the following:
  73289. **
  73290. ** CREATE TABLE main.ex1(a);
  73291. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  73292. ** SELECT * FROM temp.ex1;
  73293. */
  73294. if( pTable->nCol<0 ){
  73295. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  73296. return 1;
  73297. }
  73298. assert( pTable->nCol>=0 );
  73299. /* If we get this far, it means we need to compute the table names.
  73300. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  73301. ** "*" elements in the results set of the view and will assign cursors
  73302. ** to the elements of the FROM clause. But we do not want these changes
  73303. ** to be permanent. So the computation is done on a copy of the SELECT
  73304. ** statement that defines the view.
  73305. */
  73306. assert( pTable->pSelect );
  73307. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  73308. if( pSel ){
  73309. u8 enableLookaside = db->lookaside.bEnabled;
  73310. n = pParse->nTab;
  73311. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  73312. pTable->nCol = -1;
  73313. db->lookaside.bEnabled = 0;
  73314. #ifndef SQLITE_OMIT_AUTHORIZATION
  73315. xAuth = db->xAuth;
  73316. db->xAuth = 0;
  73317. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  73318. db->xAuth = xAuth;
  73319. #else
  73320. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  73321. #endif
  73322. db->lookaside.bEnabled = enableLookaside;
  73323. pParse->nTab = n;
  73324. if( pSelTab ){
  73325. assert( pTable->aCol==0 );
  73326. pTable->nCol = pSelTab->nCol;
  73327. pTable->aCol = pSelTab->aCol;
  73328. pSelTab->nCol = 0;
  73329. pSelTab->aCol = 0;
  73330. sqlite3DeleteTable(db, pSelTab);
  73331. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  73332. pTable->pSchema->flags |= DB_UnresetViews;
  73333. }else{
  73334. pTable->nCol = 0;
  73335. nErr++;
  73336. }
  73337. sqlite3SelectDelete(db, pSel);
  73338. } else {
  73339. nErr++;
  73340. }
  73341. #endif /* SQLITE_OMIT_VIEW */
  73342. return nErr;
  73343. }
  73344. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  73345. #ifndef SQLITE_OMIT_VIEW
  73346. /*
  73347. ** Clear the column names from every VIEW in database idx.
  73348. */
  73349. static void sqliteViewResetAll(sqlite3 *db, int idx){
  73350. HashElem *i;
  73351. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  73352. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  73353. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  73354. Table *pTab = sqliteHashData(i);
  73355. if( pTab->pSelect ){
  73356. sqliteDeleteColumnNames(db, pTab);
  73357. pTab->aCol = 0;
  73358. pTab->nCol = 0;
  73359. }
  73360. }
  73361. DbClearProperty(db, idx, DB_UnresetViews);
  73362. }
  73363. #else
  73364. # define sqliteViewResetAll(A,B)
  73365. #endif /* SQLITE_OMIT_VIEW */
  73366. /*
  73367. ** This function is called by the VDBE to adjust the internal schema
  73368. ** used by SQLite when the btree layer moves a table root page. The
  73369. ** root-page of a table or index in database iDb has changed from iFrom
  73370. ** to iTo.
  73371. **
  73372. ** Ticket #1728: The symbol table might still contain information
  73373. ** on tables and/or indices that are the process of being deleted.
  73374. ** If you are unlucky, one of those deleted indices or tables might
  73375. ** have the same rootpage number as the real table or index that is
  73376. ** being moved. So we cannot stop searching after the first match
  73377. ** because the first match might be for one of the deleted indices
  73378. ** or tables and not the table/index that is actually being moved.
  73379. ** We must continue looping until all tables and indices with
  73380. ** rootpage==iFrom have been converted to have a rootpage of iTo
  73381. ** in order to be certain that we got the right one.
  73382. */
  73383. #ifndef SQLITE_OMIT_AUTOVACUUM
  73384. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  73385. HashElem *pElem;
  73386. Hash *pHash;
  73387. Db *pDb;
  73388. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  73389. pDb = &db->aDb[iDb];
  73390. pHash = &pDb->pSchema->tblHash;
  73391. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  73392. Table *pTab = sqliteHashData(pElem);
  73393. if( pTab->tnum==iFrom ){
  73394. pTab->tnum = iTo;
  73395. }
  73396. }
  73397. pHash = &pDb->pSchema->idxHash;
  73398. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  73399. Index *pIdx = sqliteHashData(pElem);
  73400. if( pIdx->tnum==iFrom ){
  73401. pIdx->tnum = iTo;
  73402. }
  73403. }
  73404. }
  73405. #endif
  73406. /*
  73407. ** Write code to erase the table with root-page iTable from database iDb.
  73408. ** Also write code to modify the sqlite_master table and internal schema
  73409. ** if a root-page of another table is moved by the btree-layer whilst
  73410. ** erasing iTable (this can happen with an auto-vacuum database).
  73411. */
  73412. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  73413. Vdbe *v = sqlite3GetVdbe(pParse);
  73414. int r1 = sqlite3GetTempReg(pParse);
  73415. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  73416. sqlite3MayAbort(pParse);
  73417. #ifndef SQLITE_OMIT_AUTOVACUUM
  73418. /* OP_Destroy stores an in integer r1. If this integer
  73419. ** is non-zero, then it is the root page number of a table moved to
  73420. ** location iTable. The following code modifies the sqlite_master table to
  73421. ** reflect this.
  73422. **
  73423. ** The "#NNN" in the SQL is a special constant that means whatever value
  73424. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  73425. ** token for additional information.
  73426. */
  73427. sqlite3NestedParse(pParse,
  73428. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  73429. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  73430. #endif
  73431. sqlite3ReleaseTempReg(pParse, r1);
  73432. }
  73433. /*
  73434. ** Write VDBE code to erase table pTab and all associated indices on disk.
  73435. ** Code to update the sqlite_master tables and internal schema definitions
  73436. ** in case a root-page belonging to another table is moved by the btree layer
  73437. ** is also added (this can happen with an auto-vacuum database).
  73438. */
  73439. static void destroyTable(Parse *pParse, Table *pTab){
  73440. #ifdef SQLITE_OMIT_AUTOVACUUM
  73441. Index *pIdx;
  73442. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  73443. destroyRootPage(pParse, pTab->tnum, iDb);
  73444. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73445. destroyRootPage(pParse, pIdx->tnum, iDb);
  73446. }
  73447. #else
  73448. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  73449. ** is not defined), then it is important to call OP_Destroy on the
  73450. ** table and index root-pages in order, starting with the numerically
  73451. ** largest root-page number. This guarantees that none of the root-pages
  73452. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  73453. ** following were coded:
  73454. **
  73455. ** OP_Destroy 4 0
  73456. ** ...
  73457. ** OP_Destroy 5 0
  73458. **
  73459. ** and root page 5 happened to be the largest root-page number in the
  73460. ** database, then root page 5 would be moved to page 4 by the
  73461. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  73462. ** a free-list page.
  73463. */
  73464. int iTab = pTab->tnum;
  73465. int iDestroyed = 0;
  73466. while( 1 ){
  73467. Index *pIdx;
  73468. int iLargest = 0;
  73469. if( iDestroyed==0 || iTab<iDestroyed ){
  73470. iLargest = iTab;
  73471. }
  73472. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73473. int iIdx = pIdx->tnum;
  73474. assert( pIdx->pSchema==pTab->pSchema );
  73475. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  73476. iLargest = iIdx;
  73477. }
  73478. }
  73479. if( iLargest==0 ){
  73480. return;
  73481. }else{
  73482. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  73483. destroyRootPage(pParse, iLargest, iDb);
  73484. iDestroyed = iLargest;
  73485. }
  73486. }
  73487. #endif
  73488. }
  73489. /*
  73490. ** This routine is called to do the work of a DROP TABLE statement.
  73491. ** pName is the name of the table to be dropped.
  73492. */
  73493. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  73494. Table *pTab;
  73495. Vdbe *v;
  73496. sqlite3 *db = pParse->db;
  73497. int iDb;
  73498. if( db->mallocFailed ){
  73499. goto exit_drop_table;
  73500. }
  73501. assert( pParse->nErr==0 );
  73502. assert( pName->nSrc==1 );
  73503. if( noErr ) db->suppressErr++;
  73504. pTab = sqlite3LocateTable(pParse, isView,
  73505. pName->a[0].zName, pName->a[0].zDatabase);
  73506. if( noErr ) db->suppressErr--;
  73507. if( pTab==0 ){
  73508. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  73509. goto exit_drop_table;
  73510. }
  73511. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  73512. assert( iDb>=0 && iDb<db->nDb );
  73513. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  73514. ** it is initialized.
  73515. */
  73516. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  73517. goto exit_drop_table;
  73518. }
  73519. #ifndef SQLITE_OMIT_AUTHORIZATION
  73520. {
  73521. int code;
  73522. const char *zTab = SCHEMA_TABLE(iDb);
  73523. const char *zDb = db->aDb[iDb].zName;
  73524. const char *zArg2 = 0;
  73525. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  73526. goto exit_drop_table;
  73527. }
  73528. if( isView ){
  73529. if( !OMIT_TEMPDB && iDb==1 ){
  73530. code = SQLITE_DROP_TEMP_VIEW;
  73531. }else{
  73532. code = SQLITE_DROP_VIEW;
  73533. }
  73534. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73535. }else if( IsVirtual(pTab) ){
  73536. code = SQLITE_DROP_VTABLE;
  73537. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  73538. #endif
  73539. }else{
  73540. if( !OMIT_TEMPDB && iDb==1 ){
  73541. code = SQLITE_DROP_TEMP_TABLE;
  73542. }else{
  73543. code = SQLITE_DROP_TABLE;
  73544. }
  73545. }
  73546. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  73547. goto exit_drop_table;
  73548. }
  73549. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  73550. goto exit_drop_table;
  73551. }
  73552. }
  73553. #endif
  73554. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  73555. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  73556. goto exit_drop_table;
  73557. }
  73558. #ifndef SQLITE_OMIT_VIEW
  73559. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  73560. ** on a table.
  73561. */
  73562. if( isView && pTab->pSelect==0 ){
  73563. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  73564. goto exit_drop_table;
  73565. }
  73566. if( !isView && pTab->pSelect ){
  73567. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  73568. goto exit_drop_table;
  73569. }
  73570. #endif
  73571. /* Generate code to remove the table from the master table
  73572. ** on disk.
  73573. */
  73574. v = sqlite3GetVdbe(pParse);
  73575. if( v ){
  73576. Trigger *pTrigger;
  73577. Db *pDb = &db->aDb[iDb];
  73578. sqlite3BeginWriteOperation(pParse, 1, iDb);
  73579. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73580. if( IsVirtual(pTab) ){
  73581. sqlite3VdbeAddOp0(v, OP_VBegin);
  73582. }
  73583. #endif
  73584. sqlite3FkDropTable(pParse, pName, pTab);
  73585. /* Drop all triggers associated with the table being dropped. Code
  73586. ** is generated to remove entries from sqlite_master and/or
  73587. ** sqlite_temp_master if required.
  73588. */
  73589. pTrigger = sqlite3TriggerList(pParse, pTab);
  73590. while( pTrigger ){
  73591. assert( pTrigger->pSchema==pTab->pSchema ||
  73592. pTrigger->pSchema==db->aDb[1].pSchema );
  73593. sqlite3DropTriggerPtr(pParse, pTrigger);
  73594. pTrigger = pTrigger->pNext;
  73595. }
  73596. #ifndef SQLITE_OMIT_AUTOINCREMENT
  73597. /* Remove any entries of the sqlite_sequence table associated with
  73598. ** the table being dropped. This is done before the table is dropped
  73599. ** at the btree level, in case the sqlite_sequence table needs to
  73600. ** move as a result of the drop (can happen in auto-vacuum mode).
  73601. */
  73602. if( pTab->tabFlags & TF_Autoincrement ){
  73603. sqlite3NestedParse(pParse,
  73604. "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
  73605. pDb->zName, pTab->zName
  73606. );
  73607. }
  73608. #endif
  73609. /* Drop all SQLITE_MASTER table and index entries that refer to the
  73610. ** table. The program name loops through the master table and deletes
  73611. ** every row that refers to a table of the same name as the one being
  73612. ** dropped. Triggers are handled seperately because a trigger can be
  73613. ** created in the temp database that refers to a table in another
  73614. ** database.
  73615. */
  73616. sqlite3NestedParse(pParse,
  73617. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  73618. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  73619. /* Drop any statistics from the sqlite_stat1 table, if it exists */
  73620. if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
  73621. sqlite3NestedParse(pParse,
  73622. "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
  73623. );
  73624. }
  73625. if( !isView && !IsVirtual(pTab) ){
  73626. destroyTable(pParse, pTab);
  73627. }
  73628. /* Remove the table entry from SQLite's internal schema and modify
  73629. ** the schema cookie.
  73630. */
  73631. if( IsVirtual(pTab) ){
  73632. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  73633. }
  73634. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  73635. sqlite3ChangeCookie(pParse, iDb);
  73636. }
  73637. sqliteViewResetAll(db, iDb);
  73638. exit_drop_table:
  73639. sqlite3SrcListDelete(db, pName);
  73640. }
  73641. /*
  73642. ** This routine is called to create a new foreign key on the table
  73643. ** currently under construction. pFromCol determines which columns
  73644. ** in the current table point to the foreign key. If pFromCol==0 then
  73645. ** connect the key to the last column inserted. pTo is the name of
  73646. ** the table referred to. pToCol is a list of tables in the other
  73647. ** pTo table that the foreign key points to. flags contains all
  73648. ** information about the conflict resolution algorithms specified
  73649. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  73650. **
  73651. ** An FKey structure is created and added to the table currently
  73652. ** under construction in the pParse->pNewTable field.
  73653. **
  73654. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  73655. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  73656. */
  73657. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  73658. Parse *pParse, /* Parsing context */
  73659. ExprList *pFromCol, /* Columns in this table that point to other table */
  73660. Token *pTo, /* Name of the other table */
  73661. ExprList *pToCol, /* Columns in the other table */
  73662. int flags /* Conflict resolution algorithms. */
  73663. ){
  73664. sqlite3 *db = pParse->db;
  73665. #ifndef SQLITE_OMIT_FOREIGN_KEY
  73666. FKey *pFKey = 0;
  73667. FKey *pNextTo;
  73668. Table *p = pParse->pNewTable;
  73669. int nByte;
  73670. int i;
  73671. int nCol;
  73672. char *z;
  73673. assert( pTo!=0 );
  73674. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  73675. if( pFromCol==0 ){
  73676. int iCol = p->nCol-1;
  73677. if( NEVER(iCol<0) ) goto fk_end;
  73678. if( pToCol && pToCol->nExpr!=1 ){
  73679. sqlite3ErrorMsg(pParse, "foreign key on %s"
  73680. " should reference only one column of table %T",
  73681. p->aCol[iCol].zName, pTo);
  73682. goto fk_end;
  73683. }
  73684. nCol = 1;
  73685. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  73686. sqlite3ErrorMsg(pParse,
  73687. "number of columns in foreign key does not match the number of "
  73688. "columns in the referenced table");
  73689. goto fk_end;
  73690. }else{
  73691. nCol = pFromCol->nExpr;
  73692. }
  73693. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  73694. if( pToCol ){
  73695. for(i=0; i<pToCol->nExpr; i++){
  73696. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  73697. }
  73698. }
  73699. pFKey = sqlite3DbMallocZero(db, nByte );
  73700. if( pFKey==0 ){
  73701. goto fk_end;
  73702. }
  73703. pFKey->pFrom = p;
  73704. pFKey->pNextFrom = p->pFKey;
  73705. z = (char*)&pFKey->aCol[nCol];
  73706. pFKey->zTo = z;
  73707. memcpy(z, pTo->z, pTo->n);
  73708. z[pTo->n] = 0;
  73709. sqlite3Dequote(z);
  73710. z += pTo->n+1;
  73711. pFKey->nCol = nCol;
  73712. if( pFromCol==0 ){
  73713. pFKey->aCol[0].iFrom = p->nCol-1;
  73714. }else{
  73715. for(i=0; i<nCol; i++){
  73716. int j;
  73717. for(j=0; j<p->nCol; j++){
  73718. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  73719. pFKey->aCol[i].iFrom = j;
  73720. break;
  73721. }
  73722. }
  73723. if( j>=p->nCol ){
  73724. sqlite3ErrorMsg(pParse,
  73725. "unknown column \"%s\" in foreign key definition",
  73726. pFromCol->a[i].zName);
  73727. goto fk_end;
  73728. }
  73729. }
  73730. }
  73731. if( pToCol ){
  73732. for(i=0; i<nCol; i++){
  73733. int n = sqlite3Strlen30(pToCol->a[i].zName);
  73734. pFKey->aCol[i].zCol = z;
  73735. memcpy(z, pToCol->a[i].zName, n);
  73736. z[n] = 0;
  73737. z += n+1;
  73738. }
  73739. }
  73740. pFKey->isDeferred = 0;
  73741. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  73742. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  73743. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  73744. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  73745. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  73746. );
  73747. if( pNextTo==pFKey ){
  73748. db->mallocFailed = 1;
  73749. goto fk_end;
  73750. }
  73751. if( pNextTo ){
  73752. assert( pNextTo->pPrevTo==0 );
  73753. pFKey->pNextTo = pNextTo;
  73754. pNextTo->pPrevTo = pFKey;
  73755. }
  73756. /* Link the foreign key to the table as the last step.
  73757. */
  73758. p->pFKey = pFKey;
  73759. pFKey = 0;
  73760. fk_end:
  73761. sqlite3DbFree(db, pFKey);
  73762. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  73763. sqlite3ExprListDelete(db, pFromCol);
  73764. sqlite3ExprListDelete(db, pToCol);
  73765. }
  73766. /*
  73767. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  73768. ** clause is seen as part of a foreign key definition. The isDeferred
  73769. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  73770. ** The behavior of the most recently created foreign key is adjusted
  73771. ** accordingly.
  73772. */
  73773. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  73774. #ifndef SQLITE_OMIT_FOREIGN_KEY
  73775. Table *pTab;
  73776. FKey *pFKey;
  73777. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  73778. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  73779. pFKey->isDeferred = (u8)isDeferred;
  73780. #endif
  73781. }
  73782. /*
  73783. ** Generate code that will erase and refill index *pIdx. This is
  73784. ** used to initialize a newly created index or to recompute the
  73785. ** content of an index in response to a REINDEX command.
  73786. **
  73787. ** if memRootPage is not negative, it means that the index is newly
  73788. ** created. The register specified by memRootPage contains the
  73789. ** root page number of the index. If memRootPage is negative, then
  73790. ** the index already exists and must be cleared before being refilled and
  73791. ** the root page number of the index is taken from pIndex->tnum.
  73792. */
  73793. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  73794. Table *pTab = pIndex->pTable; /* The table that is indexed */
  73795. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  73796. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  73797. int addr1; /* Address of top of loop */
  73798. int tnum; /* Root page of index */
  73799. Vdbe *v; /* Generate code into this virtual machine */
  73800. KeyInfo *pKey; /* KeyInfo for index */
  73801. int regIdxKey; /* Registers containing the index key */
  73802. int regRecord; /* Register holding assemblied index record */
  73803. sqlite3 *db = pParse->db; /* The database connection */
  73804. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  73805. #ifndef SQLITE_OMIT_AUTHORIZATION
  73806. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  73807. db->aDb[iDb].zName ) ){
  73808. return;
  73809. }
  73810. #endif
  73811. /* Require a write-lock on the table to perform this operation */
  73812. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  73813. v = sqlite3GetVdbe(pParse);
  73814. if( v==0 ) return;
  73815. if( memRootPage>=0 ){
  73816. tnum = memRootPage;
  73817. }else{
  73818. tnum = pIndex->tnum;
  73819. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  73820. }
  73821. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  73822. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  73823. (char *)pKey, P4_KEYINFO_HANDOFF);
  73824. if( memRootPage>=0 ){
  73825. sqlite3VdbeChangeP5(v, 1);
  73826. }
  73827. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  73828. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  73829. regRecord = sqlite3GetTempReg(pParse);
  73830. regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
  73831. if( pIndex->onError!=OE_None ){
  73832. const int regRowid = regIdxKey + pIndex->nColumn;
  73833. const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
  73834. void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
  73835. /* The registers accessed by the OP_IsUnique opcode were allocated
  73836. ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
  73837. ** call above. Just before that function was freed they were released
  73838. ** (made available to the compiler for reuse) using
  73839. ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
  73840. ** opcode use the values stored within seems dangerous. However, since
  73841. ** we can be sure that no other temp registers have been allocated
  73842. ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
  73843. */
  73844. sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
  73845. sqlite3HaltConstraint(
  73846. pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
  73847. }
  73848. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  73849. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  73850. sqlite3ReleaseTempReg(pParse, regRecord);
  73851. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  73852. sqlite3VdbeJumpHere(v, addr1);
  73853. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  73854. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  73855. }
  73856. /*
  73857. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  73858. ** and pTblList is the name of the table that is to be indexed. Both will
  73859. ** be NULL for a primary key or an index that is created to satisfy a
  73860. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  73861. ** as the table to be indexed. pParse->pNewTable is a table that is
  73862. ** currently being constructed by a CREATE TABLE statement.
  73863. **
  73864. ** pList is a list of columns to be indexed. pList will be NULL if this
  73865. ** is a primary key or unique-constraint on the most recent column added
  73866. ** to the table currently under construction.
  73867. **
  73868. ** If the index is created successfully, return a pointer to the new Index
  73869. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  73870. ** as the tables primary key (Index.autoIndex==2).
  73871. */
  73872. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  73873. Parse *pParse, /* All information about this parse */
  73874. Token *pName1, /* First part of index name. May be NULL */
  73875. Token *pName2, /* Second part of index name. May be NULL */
  73876. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  73877. ExprList *pList, /* A list of columns to be indexed */
  73878. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  73879. Token *pStart, /* The CREATE token that begins this statement */
  73880. Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
  73881. int sortOrder, /* Sort order of primary key when pList==NULL */
  73882. int ifNotExist /* Omit error if index already exists */
  73883. ){
  73884. Index *pRet = 0; /* Pointer to return */
  73885. Table *pTab = 0; /* Table to be indexed */
  73886. Index *pIndex = 0; /* The index to be created */
  73887. char *zName = 0; /* Name of the index */
  73888. int nName; /* Number of characters in zName */
  73889. int i, j;
  73890. Token nullId; /* Fake token for an empty ID list */
  73891. DbFixer sFix; /* For assigning database names to pTable */
  73892. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  73893. sqlite3 *db = pParse->db;
  73894. Db *pDb; /* The specific table containing the indexed database */
  73895. int iDb; /* Index of the database that is being written */
  73896. Token *pName = 0; /* Unqualified name of the index to create */
  73897. struct ExprList_item *pListItem; /* For looping over pList */
  73898. int nCol;
  73899. int nExtra = 0;
  73900. char *zExtra;
  73901. assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
  73902. assert( pParse->nErr==0 ); /* Never called with prior errors */
  73903. if( db->mallocFailed || IN_DECLARE_VTAB ){
  73904. goto exit_create_index;
  73905. }
  73906. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  73907. goto exit_create_index;
  73908. }
  73909. /*
  73910. ** Find the table that is to be indexed. Return early if not found.
  73911. */
  73912. if( pTblName!=0 ){
  73913. /* Use the two-part index name to determine the database
  73914. ** to search for the table. 'Fix' the table name to this db
  73915. ** before looking up the table.
  73916. */
  73917. assert( pName1 && pName2 );
  73918. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  73919. if( iDb<0 ) goto exit_create_index;
  73920. #ifndef SQLITE_OMIT_TEMPDB
  73921. /* If the index name was unqualified, check if the the table
  73922. ** is a temp table. If so, set the database to 1. Do not do this
  73923. ** if initialising a database schema.
  73924. */
  73925. if( !db->init.busy ){
  73926. pTab = sqlite3SrcListLookup(pParse, pTblName);
  73927. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  73928. iDb = 1;
  73929. }
  73930. }
  73931. #endif
  73932. if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
  73933. sqlite3FixSrcList(&sFix, pTblName)
  73934. ){
  73935. /* Because the parser constructs pTblName from a single identifier,
  73936. ** sqlite3FixSrcList can never fail. */
  73937. assert(0);
  73938. }
  73939. pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
  73940. pTblName->a[0].zDatabase);
  73941. if( !pTab || db->mallocFailed ) goto exit_create_index;
  73942. assert( db->aDb[iDb].pSchema==pTab->pSchema );
  73943. }else{
  73944. assert( pName==0 );
  73945. pTab = pParse->pNewTable;
  73946. if( !pTab ) goto exit_create_index;
  73947. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  73948. }
  73949. pDb = &db->aDb[iDb];
  73950. assert( pTab!=0 );
  73951. assert( pParse->nErr==0 );
  73952. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  73953. && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
  73954. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  73955. goto exit_create_index;
  73956. }
  73957. #ifndef SQLITE_OMIT_VIEW
  73958. if( pTab->pSelect ){
  73959. sqlite3ErrorMsg(pParse, "views may not be indexed");
  73960. goto exit_create_index;
  73961. }
  73962. #endif
  73963. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73964. if( IsVirtual(pTab) ){
  73965. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  73966. goto exit_create_index;
  73967. }
  73968. #endif
  73969. /*
  73970. ** Find the name of the index. Make sure there is not already another
  73971. ** index or table with the same name.
  73972. **
  73973. ** Exception: If we are reading the names of permanent indices from the
  73974. ** sqlite_master table (because some other process changed the schema) and
  73975. ** one of the index names collides with the name of a temporary table or
  73976. ** index, then we will continue to process this index.
  73977. **
  73978. ** If pName==0 it means that we are
  73979. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  73980. ** own name.
  73981. */
  73982. if( pName ){
  73983. zName = sqlite3NameFromToken(db, pName);
  73984. if( zName==0 ) goto exit_create_index;
  73985. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  73986. goto exit_create_index;
  73987. }
  73988. if( !db->init.busy ){
  73989. if( sqlite3FindTable(db, zName, 0)!=0 ){
  73990. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  73991. goto exit_create_index;
  73992. }
  73993. }
  73994. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  73995. if( !ifNotExist ){
  73996. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  73997. }else{
  73998. assert( !db->init.busy );
  73999. sqlite3CodeVerifySchema(pParse, iDb);
  74000. }
  74001. goto exit_create_index;
  74002. }
  74003. }else{
  74004. int n;
  74005. Index *pLoop;
  74006. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  74007. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  74008. if( zName==0 ){
  74009. goto exit_create_index;
  74010. }
  74011. }
  74012. /* Check for authorization to create an index.
  74013. */
  74014. #ifndef SQLITE_OMIT_AUTHORIZATION
  74015. {
  74016. const char *zDb = pDb->zName;
  74017. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  74018. goto exit_create_index;
  74019. }
  74020. i = SQLITE_CREATE_INDEX;
  74021. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  74022. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  74023. goto exit_create_index;
  74024. }
  74025. }
  74026. #endif
  74027. /* If pList==0, it means this routine was called to make a primary
  74028. ** key out of the last column added to the table under construction.
  74029. ** So create a fake list to simulate this.
  74030. */
  74031. if( pList==0 ){
  74032. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  74033. nullId.n = sqlite3Strlen30((char*)nullId.z);
  74034. pList = sqlite3ExprListAppend(pParse, 0, 0);
  74035. if( pList==0 ) goto exit_create_index;
  74036. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  74037. pList->a[0].sortOrder = (u8)sortOrder;
  74038. }
  74039. /* Figure out how many bytes of space are required to store explicitly
  74040. ** specified collation sequence names.
  74041. */
  74042. for(i=0; i<pList->nExpr; i++){
  74043. Expr *pExpr = pList->a[i].pExpr;
  74044. if( pExpr ){
  74045. CollSeq *pColl = pExpr->pColl;
  74046. /* Either pColl!=0 or there was an OOM failure. But if an OOM
  74047. ** failure we have quit before reaching this point. */
  74048. if( ALWAYS(pColl) ){
  74049. nExtra += (1 + sqlite3Strlen30(pColl->zName));
  74050. }
  74051. }
  74052. }
  74053. /*
  74054. ** Allocate the index structure.
  74055. */
  74056. nName = sqlite3Strlen30(zName);
  74057. nCol = pList->nExpr;
  74058. pIndex = sqlite3DbMallocZero(db,
  74059. sizeof(Index) + /* Index structure */
  74060. sizeof(int)*nCol + /* Index.aiColumn */
  74061. sizeof(int)*(nCol+1) + /* Index.aiRowEst */
  74062. sizeof(char *)*nCol + /* Index.azColl */
  74063. sizeof(u8)*nCol + /* Index.aSortOrder */
  74064. nName + 1 + /* Index.zName */
  74065. nExtra /* Collation sequence names */
  74066. );
  74067. if( db->mallocFailed ){
  74068. goto exit_create_index;
  74069. }
  74070. pIndex->azColl = (char**)(&pIndex[1]);
  74071. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  74072. pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
  74073. pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
  74074. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  74075. zExtra = (char *)(&pIndex->zName[nName+1]);
  74076. memcpy(pIndex->zName, zName, nName+1);
  74077. pIndex->pTable = pTab;
  74078. pIndex->nColumn = pList->nExpr;
  74079. pIndex->onError = (u8)onError;
  74080. pIndex->autoIndex = (u8)(pName==0);
  74081. pIndex->pSchema = db->aDb[iDb].pSchema;
  74082. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  74083. /* Check to see if we should honor DESC requests on index columns
  74084. */
  74085. if( pDb->pSchema->file_format>=4 ){
  74086. sortOrderMask = -1; /* Honor DESC */
  74087. }else{
  74088. sortOrderMask = 0; /* Ignore DESC */
  74089. }
  74090. /* Scan the names of the columns of the table to be indexed and
  74091. ** load the column indices into the Index structure. Report an error
  74092. ** if any column is not found.
  74093. **
  74094. ** TODO: Add a test to make sure that the same column is not named
  74095. ** more than once within the same index. Only the first instance of
  74096. ** the column will ever be used by the optimizer. Note that using the
  74097. ** same column more than once cannot be an error because that would
  74098. ** break backwards compatibility - it needs to be a warning.
  74099. */
  74100. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  74101. const char *zColName = pListItem->zName;
  74102. Column *pTabCol;
  74103. int requestedSortOrder;
  74104. char *zColl; /* Collation sequence name */
  74105. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  74106. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  74107. }
  74108. if( j>=pTab->nCol ){
  74109. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  74110. pTab->zName, zColName);
  74111. pParse->checkSchema = 1;
  74112. goto exit_create_index;
  74113. }
  74114. pIndex->aiColumn[i] = j;
  74115. /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
  74116. ** the way the "idxlist" non-terminal is constructed by the parser,
  74117. ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
  74118. ** must exist or else there must have been an OOM error. But if there
  74119. ** was an OOM error, we would never reach this point. */
  74120. if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
  74121. int nColl;
  74122. zColl = pListItem->pExpr->pColl->zName;
  74123. nColl = sqlite3Strlen30(zColl) + 1;
  74124. assert( nExtra>=nColl );
  74125. memcpy(zExtra, zColl, nColl);
  74126. zColl = zExtra;
  74127. zExtra += nColl;
  74128. nExtra -= nColl;
  74129. }else{
  74130. zColl = pTab->aCol[j].zColl;
  74131. if( !zColl ){
  74132. zColl = db->pDfltColl->zName;
  74133. }
  74134. }
  74135. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  74136. goto exit_create_index;
  74137. }
  74138. pIndex->azColl[i] = zColl;
  74139. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  74140. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  74141. }
  74142. sqlite3DefaultRowEst(pIndex);
  74143. if( pTab==pParse->pNewTable ){
  74144. /* This routine has been called to create an automatic index as a
  74145. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  74146. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  74147. ** i.e. one of:
  74148. **
  74149. ** CREATE TABLE t(x PRIMARY KEY, y);
  74150. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  74151. **
  74152. ** Either way, check to see if the table already has such an index. If
  74153. ** so, don't bother creating this one. This only applies to
  74154. ** automatically created indices. Users can do as they wish with
  74155. ** explicit indices.
  74156. **
  74157. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  74158. ** (and thus suppressing the second one) even if they have different
  74159. ** sort orders.
  74160. **
  74161. ** If there are different collating sequences or if the columns of
  74162. ** the constraint occur in different orders, then the constraints are
  74163. ** considered distinct and both result in separate indices.
  74164. */
  74165. Index *pIdx;
  74166. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  74167. int k;
  74168. assert( pIdx->onError!=OE_None );
  74169. assert( pIdx->autoIndex );
  74170. assert( pIndex->onError!=OE_None );
  74171. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  74172. for(k=0; k<pIdx->nColumn; k++){
  74173. const char *z1;
  74174. const char *z2;
  74175. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  74176. z1 = pIdx->azColl[k];
  74177. z2 = pIndex->azColl[k];
  74178. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  74179. }
  74180. if( k==pIdx->nColumn ){
  74181. if( pIdx->onError!=pIndex->onError ){
  74182. /* This constraint creates the same index as a previous
  74183. ** constraint specified somewhere in the CREATE TABLE statement.
  74184. ** However the ON CONFLICT clauses are different. If both this
  74185. ** constraint and the previous equivalent constraint have explicit
  74186. ** ON CONFLICT clauses this is an error. Otherwise, use the
  74187. ** explicitly specified behaviour for the index.
  74188. */
  74189. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  74190. sqlite3ErrorMsg(pParse,
  74191. "conflicting ON CONFLICT clauses specified", 0);
  74192. }
  74193. if( pIdx->onError==OE_Default ){
  74194. pIdx->onError = pIndex->onError;
  74195. }
  74196. }
  74197. goto exit_create_index;
  74198. }
  74199. }
  74200. }
  74201. /* Link the new Index structure to its table and to the other
  74202. ** in-memory database structures.
  74203. */
  74204. if( db->init.busy ){
  74205. Index *p;
  74206. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  74207. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  74208. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  74209. pIndex);
  74210. if( p ){
  74211. assert( p==pIndex ); /* Malloc must have failed */
  74212. db->mallocFailed = 1;
  74213. goto exit_create_index;
  74214. }
  74215. db->flags |= SQLITE_InternChanges;
  74216. if( pTblName!=0 ){
  74217. pIndex->tnum = db->init.newTnum;
  74218. }
  74219. }
  74220. /* If the db->init.busy is 0 then create the index on disk. This
  74221. ** involves writing the index into the master table and filling in the
  74222. ** index with the current table contents.
  74223. **
  74224. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  74225. ** command. db->init.busy is 1 when a database is opened and
  74226. ** CREATE INDEX statements are read out of the master table. In
  74227. ** the latter case the index already exists on disk, which is why
  74228. ** we don't want to recreate it.
  74229. **
  74230. ** If pTblName==0 it means this index is generated as a primary key
  74231. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  74232. ** has just been created, it contains no data and the index initialization
  74233. ** step can be skipped.
  74234. */
  74235. else{ /* if( db->init.busy==0 ) */
  74236. Vdbe *v;
  74237. char *zStmt;
  74238. int iMem = ++pParse->nMem;
  74239. v = sqlite3GetVdbe(pParse);
  74240. if( v==0 ) goto exit_create_index;
  74241. /* Create the rootpage for the index
  74242. */
  74243. sqlite3BeginWriteOperation(pParse, 1, iDb);
  74244. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  74245. /* Gather the complete text of the CREATE INDEX statement into
  74246. ** the zStmt variable
  74247. */
  74248. if( pStart ){
  74249. assert( pEnd!=0 );
  74250. /* A named index with an explicit CREATE INDEX statement */
  74251. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  74252. onError==OE_None ? "" : " UNIQUE",
  74253. pEnd->z - pName->z + 1,
  74254. pName->z);
  74255. }else{
  74256. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  74257. /* zStmt = sqlite3MPrintf(""); */
  74258. zStmt = 0;
  74259. }
  74260. /* Add an entry in sqlite_master for this index
  74261. */
  74262. sqlite3NestedParse(pParse,
  74263. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  74264. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  74265. pIndex->zName,
  74266. pTab->zName,
  74267. iMem,
  74268. zStmt
  74269. );
  74270. sqlite3DbFree(db, zStmt);
  74271. /* Fill the index with data and reparse the schema. Code an OP_Expire
  74272. ** to invalidate all pre-compiled statements.
  74273. */
  74274. if( pTblName ){
  74275. sqlite3RefillIndex(pParse, pIndex, iMem);
  74276. sqlite3ChangeCookie(pParse, iDb);
  74277. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
  74278. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName),
  74279. P4_DYNAMIC);
  74280. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  74281. }
  74282. }
  74283. /* When adding an index to the list of indices for a table, make
  74284. ** sure all indices labeled OE_Replace come after all those labeled
  74285. ** OE_Ignore. This is necessary for the correct constraint check
  74286. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  74287. ** UPDATE and INSERT statements.
  74288. */
  74289. if( db->init.busy || pTblName==0 ){
  74290. if( onError!=OE_Replace || pTab->pIndex==0
  74291. || pTab->pIndex->onError==OE_Replace){
  74292. pIndex->pNext = pTab->pIndex;
  74293. pTab->pIndex = pIndex;
  74294. }else{
  74295. Index *pOther = pTab->pIndex;
  74296. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  74297. pOther = pOther->pNext;
  74298. }
  74299. pIndex->pNext = pOther->pNext;
  74300. pOther->pNext = pIndex;
  74301. }
  74302. pRet = pIndex;
  74303. pIndex = 0;
  74304. }
  74305. /* Clean up before exiting */
  74306. exit_create_index:
  74307. if( pIndex ){
  74308. sqlite3DbFree(db, pIndex->zColAff);
  74309. sqlite3DbFree(db, pIndex);
  74310. }
  74311. sqlite3ExprListDelete(db, pList);
  74312. sqlite3SrcListDelete(db, pTblName);
  74313. sqlite3DbFree(db, zName);
  74314. return pRet;
  74315. }
  74316. /*
  74317. ** Fill the Index.aiRowEst[] array with default information - information
  74318. ** to be used when we have not run the ANALYZE command.
  74319. **
  74320. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  74321. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  74322. ** number of rows in the table that match any particular value of the
  74323. ** first column of the index. aiRowEst[2] is an estimate of the number
  74324. ** of rows that match any particular combiniation of the first 2 columns
  74325. ** of the index. And so forth. It must always be the case that
  74326. *
  74327. ** aiRowEst[N]<=aiRowEst[N-1]
  74328. ** aiRowEst[N]>=1
  74329. **
  74330. ** Apart from that, we have little to go on besides intuition as to
  74331. ** how aiRowEst[] should be initialized. The numbers generated here
  74332. ** are based on typical values found in actual indices.
  74333. */
  74334. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  74335. unsigned *a = pIdx->aiRowEst;
  74336. int i;
  74337. unsigned n;
  74338. assert( a!=0 );
  74339. a[0] = pIdx->pTable->nRowEst;
  74340. if( a[0]<10 ) a[0] = 10;
  74341. n = 10;
  74342. for(i=1; i<=pIdx->nColumn; i++){
  74343. a[i] = n;
  74344. if( n>5 ) n--;
  74345. }
  74346. if( pIdx->onError!=OE_None ){
  74347. a[pIdx->nColumn] = 1;
  74348. }
  74349. }
  74350. /*
  74351. ** This routine will drop an existing named index. This routine
  74352. ** implements the DROP INDEX statement.
  74353. */
  74354. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  74355. Index *pIndex;
  74356. Vdbe *v;
  74357. sqlite3 *db = pParse->db;
  74358. int iDb;
  74359. assert( pParse->nErr==0 ); /* Never called with prior errors */
  74360. if( db->mallocFailed ){
  74361. goto exit_drop_index;
  74362. }
  74363. assert( pName->nSrc==1 );
  74364. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  74365. goto exit_drop_index;
  74366. }
  74367. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  74368. if( pIndex==0 ){
  74369. if( !ifExists ){
  74370. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  74371. }else{
  74372. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  74373. }
  74374. pParse->checkSchema = 1;
  74375. goto exit_drop_index;
  74376. }
  74377. if( pIndex->autoIndex ){
  74378. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  74379. "or PRIMARY KEY constraint cannot be dropped", 0);
  74380. goto exit_drop_index;
  74381. }
  74382. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  74383. #ifndef SQLITE_OMIT_AUTHORIZATION
  74384. {
  74385. int code = SQLITE_DROP_INDEX;
  74386. Table *pTab = pIndex->pTable;
  74387. const char *zDb = db->aDb[iDb].zName;
  74388. const char *zTab = SCHEMA_TABLE(iDb);
  74389. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  74390. goto exit_drop_index;
  74391. }
  74392. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  74393. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  74394. goto exit_drop_index;
  74395. }
  74396. }
  74397. #endif
  74398. /* Generate code to remove the index and from the master table */
  74399. v = sqlite3GetVdbe(pParse);
  74400. if( v ){
  74401. sqlite3BeginWriteOperation(pParse, 1, iDb);
  74402. sqlite3NestedParse(pParse,
  74403. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  74404. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  74405. pIndex->zName
  74406. );
  74407. if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
  74408. sqlite3NestedParse(pParse,
  74409. "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
  74410. db->aDb[iDb].zName, pIndex->zName
  74411. );
  74412. }
  74413. sqlite3ChangeCookie(pParse, iDb);
  74414. destroyRootPage(pParse, pIndex->tnum, iDb);
  74415. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  74416. }
  74417. exit_drop_index:
  74418. sqlite3SrcListDelete(db, pName);
  74419. }
  74420. /*
  74421. ** pArray is a pointer to an array of objects. Each object in the
  74422. ** array is szEntry bytes in size. This routine allocates a new
  74423. ** object on the end of the array.
  74424. **
  74425. ** *pnEntry is the number of entries already in use. *pnAlloc is
  74426. ** the previously allocated size of the array. initSize is the
  74427. ** suggested initial array size allocation.
  74428. **
  74429. ** The index of the new entry is returned in *pIdx.
  74430. **
  74431. ** This routine returns a pointer to the array of objects. This
  74432. ** might be the same as the pArray parameter or it might be a different
  74433. ** pointer if the array was resized.
  74434. */
  74435. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  74436. sqlite3 *db, /* Connection to notify of malloc failures */
  74437. void *pArray, /* Array of objects. Might be reallocated */
  74438. int szEntry, /* Size of each object in the array */
  74439. int initSize, /* Suggested initial allocation, in elements */
  74440. int *pnEntry, /* Number of objects currently in use */
  74441. int *pnAlloc, /* Current size of the allocation, in elements */
  74442. int *pIdx /* Write the index of a new slot here */
  74443. ){
  74444. char *z;
  74445. if( *pnEntry >= *pnAlloc ){
  74446. void *pNew;
  74447. int newSize;
  74448. newSize = (*pnAlloc)*2 + initSize;
  74449. pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
  74450. if( pNew==0 ){
  74451. *pIdx = -1;
  74452. return pArray;
  74453. }
  74454. *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
  74455. pArray = pNew;
  74456. }
  74457. z = (char*)pArray;
  74458. memset(&z[*pnEntry * szEntry], 0, szEntry);
  74459. *pIdx = *pnEntry;
  74460. ++*pnEntry;
  74461. return pArray;
  74462. }
  74463. /*
  74464. ** Append a new element to the given IdList. Create a new IdList if
  74465. ** need be.
  74466. **
  74467. ** A new IdList is returned, or NULL if malloc() fails.
  74468. */
  74469. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  74470. int i;
  74471. if( pList==0 ){
  74472. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  74473. if( pList==0 ) return 0;
  74474. pList->nAlloc = 0;
  74475. }
  74476. pList->a = sqlite3ArrayAllocate(
  74477. db,
  74478. pList->a,
  74479. sizeof(pList->a[0]),
  74480. 5,
  74481. &pList->nId,
  74482. &pList->nAlloc,
  74483. &i
  74484. );
  74485. if( i<0 ){
  74486. sqlite3IdListDelete(db, pList);
  74487. return 0;
  74488. }
  74489. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  74490. return pList;
  74491. }
  74492. /*
  74493. ** Delete an IdList.
  74494. */
  74495. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  74496. int i;
  74497. if( pList==0 ) return;
  74498. for(i=0; i<pList->nId; i++){
  74499. sqlite3DbFree(db, pList->a[i].zName);
  74500. }
  74501. sqlite3DbFree(db, pList->a);
  74502. sqlite3DbFree(db, pList);
  74503. }
  74504. /*
  74505. ** Return the index in pList of the identifier named zId. Return -1
  74506. ** if not found.
  74507. */
  74508. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  74509. int i;
  74510. if( pList==0 ) return -1;
  74511. for(i=0; i<pList->nId; i++){
  74512. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  74513. }
  74514. return -1;
  74515. }
  74516. /*
  74517. ** Expand the space allocated for the given SrcList object by
  74518. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  74519. ** New slots are zeroed.
  74520. **
  74521. ** For example, suppose a SrcList initially contains two entries: A,B.
  74522. ** To append 3 new entries onto the end, do this:
  74523. **
  74524. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  74525. **
  74526. ** After the call above it would contain: A, B, nil, nil, nil.
  74527. ** If the iStart argument had been 1 instead of 2, then the result
  74528. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  74529. ** the iStart value would be 0. The result then would
  74530. ** be: nil, nil, nil, A, B.
  74531. **
  74532. ** If a memory allocation fails the SrcList is unchanged. The
  74533. ** db->mallocFailed flag will be set to true.
  74534. */
  74535. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  74536. sqlite3 *db, /* Database connection to notify of OOM errors */
  74537. SrcList *pSrc, /* The SrcList to be enlarged */
  74538. int nExtra, /* Number of new slots to add to pSrc->a[] */
  74539. int iStart /* Index in pSrc->a[] of first new slot */
  74540. ){
  74541. int i;
  74542. /* Sanity checking on calling parameters */
  74543. assert( iStart>=0 );
  74544. assert( nExtra>=1 );
  74545. assert( pSrc!=0 );
  74546. assert( iStart<=pSrc->nSrc );
  74547. /* Allocate additional space if needed */
  74548. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  74549. SrcList *pNew;
  74550. int nAlloc = pSrc->nSrc+nExtra;
  74551. int nGot;
  74552. pNew = sqlite3DbRealloc(db, pSrc,
  74553. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  74554. if( pNew==0 ){
  74555. assert( db->mallocFailed );
  74556. return pSrc;
  74557. }
  74558. pSrc = pNew;
  74559. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  74560. pSrc->nAlloc = (u16)nGot;
  74561. }
  74562. /* Move existing slots that come after the newly inserted slots
  74563. ** out of the way */
  74564. for(i=pSrc->nSrc-1; i>=iStart; i--){
  74565. pSrc->a[i+nExtra] = pSrc->a[i];
  74566. }
  74567. pSrc->nSrc += (i16)nExtra;
  74568. /* Zero the newly allocated slots */
  74569. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  74570. for(i=iStart; i<iStart+nExtra; i++){
  74571. pSrc->a[i].iCursor = -1;
  74572. }
  74573. /* Return a pointer to the enlarged SrcList */
  74574. return pSrc;
  74575. }
  74576. /*
  74577. ** Append a new table name to the given SrcList. Create a new SrcList if
  74578. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  74579. **
  74580. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  74581. ** SrcList might be the same as the SrcList that was input or it might be
  74582. ** a new one. If an OOM error does occurs, then the prior value of pList
  74583. ** that is input to this routine is automatically freed.
  74584. **
  74585. ** If pDatabase is not null, it means that the table has an optional
  74586. ** database name prefix. Like this: "database.table". The pDatabase
  74587. ** points to the table name and the pTable points to the database name.
  74588. ** The SrcList.a[].zName field is filled with the table name which might
  74589. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  74590. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  74591. ** or with NULL if no database is specified.
  74592. **
  74593. ** In other words, if call like this:
  74594. **
  74595. ** sqlite3SrcListAppend(D,A,B,0);
  74596. **
  74597. ** Then B is a table name and the database name is unspecified. If called
  74598. ** like this:
  74599. **
  74600. ** sqlite3SrcListAppend(D,A,B,C);
  74601. **
  74602. ** Then C is the table name and B is the database name. If C is defined
  74603. ** then so is B. In other words, we never have a case where:
  74604. **
  74605. ** sqlite3SrcListAppend(D,A,0,C);
  74606. **
  74607. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  74608. ** before being added to the SrcList.
  74609. */
  74610. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  74611. sqlite3 *db, /* Connection to notify of malloc failures */
  74612. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  74613. Token *pTable, /* Table to append */
  74614. Token *pDatabase /* Database of the table */
  74615. ){
  74616. struct SrcList_item *pItem;
  74617. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  74618. if( pList==0 ){
  74619. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  74620. if( pList==0 ) return 0;
  74621. pList->nAlloc = 1;
  74622. }
  74623. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  74624. if( db->mallocFailed ){
  74625. sqlite3SrcListDelete(db, pList);
  74626. return 0;
  74627. }
  74628. pItem = &pList->a[pList->nSrc-1];
  74629. if( pDatabase && pDatabase->z==0 ){
  74630. pDatabase = 0;
  74631. }
  74632. if( pDatabase ){
  74633. Token *pTemp = pDatabase;
  74634. pDatabase = pTable;
  74635. pTable = pTemp;
  74636. }
  74637. pItem->zName = sqlite3NameFromToken(db, pTable);
  74638. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  74639. return pList;
  74640. }
  74641. /*
  74642. ** Assign VdbeCursor index numbers to all tables in a SrcList
  74643. */
  74644. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  74645. int i;
  74646. struct SrcList_item *pItem;
  74647. assert(pList || pParse->db->mallocFailed );
  74648. if( pList ){
  74649. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  74650. if( pItem->iCursor>=0 ) break;
  74651. pItem->iCursor = pParse->nTab++;
  74652. if( pItem->pSelect ){
  74653. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  74654. }
  74655. }
  74656. }
  74657. }
  74658. /*
  74659. ** Delete an entire SrcList including all its substructure.
  74660. */
  74661. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  74662. int i;
  74663. struct SrcList_item *pItem;
  74664. if( pList==0 ) return;
  74665. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  74666. sqlite3DbFree(db, pItem->zDatabase);
  74667. sqlite3DbFree(db, pItem->zName);
  74668. sqlite3DbFree(db, pItem->zAlias);
  74669. sqlite3DbFree(db, pItem->zIndex);
  74670. sqlite3DeleteTable(db, pItem->pTab);
  74671. sqlite3SelectDelete(db, pItem->pSelect);
  74672. sqlite3ExprDelete(db, pItem->pOn);
  74673. sqlite3IdListDelete(db, pItem->pUsing);
  74674. }
  74675. sqlite3DbFree(db, pList);
  74676. }
  74677. /*
  74678. ** This routine is called by the parser to add a new term to the
  74679. ** end of a growing FROM clause. The "p" parameter is the part of
  74680. ** the FROM clause that has already been constructed. "p" is NULL
  74681. ** if this is the first term of the FROM clause. pTable and pDatabase
  74682. ** are the name of the table and database named in the FROM clause term.
  74683. ** pDatabase is NULL if the database name qualifier is missing - the
  74684. ** usual case. If the term has a alias, then pAlias points to the
  74685. ** alias token. If the term is a subquery, then pSubquery is the
  74686. ** SELECT statement that the subquery encodes. The pTable and
  74687. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  74688. ** parameters are the content of the ON and USING clauses.
  74689. **
  74690. ** Return a new SrcList which encodes is the FROM with the new
  74691. ** term added.
  74692. */
  74693. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  74694. Parse *pParse, /* Parsing context */
  74695. SrcList *p, /* The left part of the FROM clause already seen */
  74696. Token *pTable, /* Name of the table to add to the FROM clause */
  74697. Token *pDatabase, /* Name of the database containing pTable */
  74698. Token *pAlias, /* The right-hand side of the AS subexpression */
  74699. Select *pSubquery, /* A subquery used in place of a table name */
  74700. Expr *pOn, /* The ON clause of a join */
  74701. IdList *pUsing /* The USING clause of a join */
  74702. ){
  74703. struct SrcList_item *pItem;
  74704. sqlite3 *db = pParse->db;
  74705. if( !p && (pOn || pUsing) ){
  74706. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  74707. (pOn ? "ON" : "USING")
  74708. );
  74709. goto append_from_error;
  74710. }
  74711. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  74712. if( p==0 || NEVER(p->nSrc==0) ){
  74713. goto append_from_error;
  74714. }
  74715. pItem = &p->a[p->nSrc-1];
  74716. assert( pAlias!=0 );
  74717. if( pAlias->n ){
  74718. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  74719. }
  74720. pItem->pSelect = pSubquery;
  74721. pItem->pOn = pOn;
  74722. pItem->pUsing = pUsing;
  74723. return p;
  74724. append_from_error:
  74725. assert( p==0 );
  74726. sqlite3ExprDelete(db, pOn);
  74727. sqlite3IdListDelete(db, pUsing);
  74728. sqlite3SelectDelete(db, pSubquery);
  74729. return 0;
  74730. }
  74731. /*
  74732. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  74733. ** element of the source-list passed as the second argument.
  74734. */
  74735. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  74736. assert( pIndexedBy!=0 );
  74737. if( p && ALWAYS(p->nSrc>0) ){
  74738. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  74739. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  74740. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  74741. /* A "NOT INDEXED" clause was supplied. See parse.y
  74742. ** construct "indexed_opt" for details. */
  74743. pItem->notIndexed = 1;
  74744. }else{
  74745. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  74746. }
  74747. }
  74748. }
  74749. /*
  74750. ** When building up a FROM clause in the parser, the join operator
  74751. ** is initially attached to the left operand. But the code generator
  74752. ** expects the join operator to be on the right operand. This routine
  74753. ** Shifts all join operators from left to right for an entire FROM
  74754. ** clause.
  74755. **
  74756. ** Example: Suppose the join is like this:
  74757. **
  74758. ** A natural cross join B
  74759. **
  74760. ** The operator is "natural cross join". The A and B operands are stored
  74761. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  74762. ** operator with A. This routine shifts that operator over to B.
  74763. */
  74764. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  74765. if( p && p->a ){
  74766. int i;
  74767. for(i=p->nSrc-1; i>0; i--){
  74768. p->a[i].jointype = p->a[i-1].jointype;
  74769. }
  74770. p->a[0].jointype = 0;
  74771. }
  74772. }
  74773. /*
  74774. ** Begin a transaction
  74775. */
  74776. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  74777. sqlite3 *db;
  74778. Vdbe *v;
  74779. int i;
  74780. assert( pParse!=0 );
  74781. db = pParse->db;
  74782. assert( db!=0 );
  74783. /* if( db->aDb[0].pBt==0 ) return; */
  74784. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  74785. return;
  74786. }
  74787. v = sqlite3GetVdbe(pParse);
  74788. if( !v ) return;
  74789. if( type!=TK_DEFERRED ){
  74790. for(i=0; i<db->nDb; i++){
  74791. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  74792. sqlite3VdbeUsesBtree(v, i);
  74793. }
  74794. }
  74795. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  74796. }
  74797. /*
  74798. ** Commit a transaction
  74799. */
  74800. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  74801. sqlite3 *db;
  74802. Vdbe *v;
  74803. assert( pParse!=0 );
  74804. db = pParse->db;
  74805. assert( db!=0 );
  74806. /* if( db->aDb[0].pBt==0 ) return; */
  74807. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  74808. return;
  74809. }
  74810. v = sqlite3GetVdbe(pParse);
  74811. if( v ){
  74812. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  74813. }
  74814. }
  74815. /*
  74816. ** Rollback a transaction
  74817. */
  74818. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  74819. sqlite3 *db;
  74820. Vdbe *v;
  74821. assert( pParse!=0 );
  74822. db = pParse->db;
  74823. assert( db!=0 );
  74824. /* if( db->aDb[0].pBt==0 ) return; */
  74825. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  74826. return;
  74827. }
  74828. v = sqlite3GetVdbe(pParse);
  74829. if( v ){
  74830. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  74831. }
  74832. }
  74833. /*
  74834. ** This function is called by the parser when it parses a command to create,
  74835. ** release or rollback an SQL savepoint.
  74836. */
  74837. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  74838. char *zName = sqlite3NameFromToken(pParse->db, pName);
  74839. if( zName ){
  74840. Vdbe *v = sqlite3GetVdbe(pParse);
  74841. #ifndef SQLITE_OMIT_AUTHORIZATION
  74842. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  74843. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  74844. #endif
  74845. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  74846. sqlite3DbFree(pParse->db, zName);
  74847. return;
  74848. }
  74849. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  74850. }
  74851. }
  74852. /*
  74853. ** Make sure the TEMP database is open and available for use. Return
  74854. ** the number of errors. Leave any error messages in the pParse structure.
  74855. */
  74856. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  74857. sqlite3 *db = pParse->db;
  74858. if( db->aDb[1].pBt==0 && !pParse->explain ){
  74859. int rc;
  74860. Btree *pBt;
  74861. static const int flags =
  74862. SQLITE_OPEN_READWRITE |
  74863. SQLITE_OPEN_CREATE |
  74864. SQLITE_OPEN_EXCLUSIVE |
  74865. SQLITE_OPEN_DELETEONCLOSE |
  74866. SQLITE_OPEN_TEMP_DB;
  74867. rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
  74868. if( rc!=SQLITE_OK ){
  74869. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  74870. "file for storing temporary tables");
  74871. pParse->rc = rc;
  74872. return 1;
  74873. }
  74874. db->aDb[1].pBt = pBt;
  74875. assert( db->aDb[1].pSchema );
  74876. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  74877. db->mallocFailed = 1;
  74878. return 1;
  74879. }
  74880. }
  74881. return 0;
  74882. }
  74883. /*
  74884. ** Generate VDBE code that will verify the schema cookie and start
  74885. ** a read-transaction for all named database files.
  74886. **
  74887. ** It is important that all schema cookies be verified and all
  74888. ** read transactions be started before anything else happens in
  74889. ** the VDBE program. But this routine can be called after much other
  74890. ** code has been generated. So here is what we do:
  74891. **
  74892. ** The first time this routine is called, we code an OP_Goto that
  74893. ** will jump to a subroutine at the end of the program. Then we
  74894. ** record every database that needs its schema verified in the
  74895. ** pParse->cookieMask field. Later, after all other code has been
  74896. ** generated, the subroutine that does the cookie verifications and
  74897. ** starts the transactions will be coded and the OP_Goto P2 value
  74898. ** will be made to point to that subroutine. The generation of the
  74899. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  74900. **
  74901. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  74902. ** schema on any databases. This can be used to position the OP_Goto
  74903. ** early in the code, before we know if any database tables will be used.
  74904. */
  74905. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  74906. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  74907. if( pToplevel->cookieGoto==0 ){
  74908. Vdbe *v = sqlite3GetVdbe(pToplevel);
  74909. if( v==0 ) return; /* This only happens if there was a prior error */
  74910. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  74911. }
  74912. if( iDb>=0 ){
  74913. sqlite3 *db = pToplevel->db;
  74914. yDbMask mask;
  74915. assert( iDb<db->nDb );
  74916. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  74917. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  74918. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  74919. mask = ((yDbMask)1)<<iDb;
  74920. if( (pToplevel->cookieMask & mask)==0 ){
  74921. pToplevel->cookieMask |= mask;
  74922. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  74923. if( !OMIT_TEMPDB && iDb==1 ){
  74924. sqlite3OpenTempDatabase(pToplevel);
  74925. }
  74926. }
  74927. }
  74928. }
  74929. /*
  74930. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  74931. ** attached database. Otherwise, invoke it for the database named zDb only.
  74932. */
  74933. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  74934. sqlite3 *db = pParse->db;
  74935. int i;
  74936. for(i=0; i<db->nDb; i++){
  74937. Db *pDb = &db->aDb[i];
  74938. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  74939. sqlite3CodeVerifySchema(pParse, i);
  74940. }
  74941. }
  74942. }
  74943. /*
  74944. ** Generate VDBE code that prepares for doing an operation that
  74945. ** might change the database.
  74946. **
  74947. ** This routine starts a new transaction if we are not already within
  74948. ** a transaction. If we are already within a transaction, then a checkpoint
  74949. ** is set if the setStatement parameter is true. A checkpoint should
  74950. ** be set for operations that might fail (due to a constraint) part of
  74951. ** the way through and which will need to undo some writes without having to
  74952. ** rollback the whole transaction. For operations where all constraints
  74953. ** can be checked before any changes are made to the database, it is never
  74954. ** necessary to undo a write and the checkpoint should not be set.
  74955. */
  74956. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  74957. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  74958. sqlite3CodeVerifySchema(pParse, iDb);
  74959. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  74960. pToplevel->isMultiWrite |= setStatement;
  74961. }
  74962. /*
  74963. ** Indicate that the statement currently under construction might write
  74964. ** more than one entry (example: deleting one row then inserting another,
  74965. ** inserting multiple rows in a table, or inserting a row and index entries.)
  74966. ** If an abort occurs after some of these writes have completed, then it will
  74967. ** be necessary to undo the completed writes.
  74968. */
  74969. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  74970. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  74971. pToplevel->isMultiWrite = 1;
  74972. }
  74973. /*
  74974. ** The code generator calls this routine if is discovers that it is
  74975. ** possible to abort a statement prior to completion. In order to
  74976. ** perform this abort without corrupting the database, we need to make
  74977. ** sure that the statement is protected by a statement transaction.
  74978. **
  74979. ** Technically, we only need to set the mayAbort flag if the
  74980. ** isMultiWrite flag was previously set. There is a time dependency
  74981. ** such that the abort must occur after the multiwrite. This makes
  74982. ** some statements involving the REPLACE conflict resolution algorithm
  74983. ** go a little faster. But taking advantage of this time dependency
  74984. ** makes it more difficult to prove that the code is correct (in
  74985. ** particular, it prevents us from writing an effective
  74986. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  74987. ** to take the safe route and skip the optimization.
  74988. */
  74989. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  74990. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  74991. pToplevel->mayAbort = 1;
  74992. }
  74993. /*
  74994. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  74995. ** error. The onError parameter determines which (if any) of the statement
  74996. ** and/or current transaction is rolled back.
  74997. */
  74998. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
  74999. Vdbe *v = sqlite3GetVdbe(pParse);
  75000. if( onError==OE_Abort ){
  75001. sqlite3MayAbort(pParse);
  75002. }
  75003. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
  75004. }
  75005. /*
  75006. ** Check to see if pIndex uses the collating sequence pColl. Return
  75007. ** true if it does and false if it does not.
  75008. */
  75009. #ifndef SQLITE_OMIT_REINDEX
  75010. static int collationMatch(const char *zColl, Index *pIndex){
  75011. int i;
  75012. assert( zColl!=0 );
  75013. for(i=0; i<pIndex->nColumn; i++){
  75014. const char *z = pIndex->azColl[i];
  75015. assert( z!=0 );
  75016. if( 0==sqlite3StrICmp(z, zColl) ){
  75017. return 1;
  75018. }
  75019. }
  75020. return 0;
  75021. }
  75022. #endif
  75023. /*
  75024. ** Recompute all indices of pTab that use the collating sequence pColl.
  75025. ** If pColl==0 then recompute all indices of pTab.
  75026. */
  75027. #ifndef SQLITE_OMIT_REINDEX
  75028. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  75029. Index *pIndex; /* An index associated with pTab */
  75030. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  75031. if( zColl==0 || collationMatch(zColl, pIndex) ){
  75032. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  75033. sqlite3BeginWriteOperation(pParse, 0, iDb);
  75034. sqlite3RefillIndex(pParse, pIndex, -1);
  75035. }
  75036. }
  75037. }
  75038. #endif
  75039. /*
  75040. ** Recompute all indices of all tables in all databases where the
  75041. ** indices use the collating sequence pColl. If pColl==0 then recompute
  75042. ** all indices everywhere.
  75043. */
  75044. #ifndef SQLITE_OMIT_REINDEX
  75045. static void reindexDatabases(Parse *pParse, char const *zColl){
  75046. Db *pDb; /* A single database */
  75047. int iDb; /* The database index number */
  75048. sqlite3 *db = pParse->db; /* The database connection */
  75049. HashElem *k; /* For looping over tables in pDb */
  75050. Table *pTab; /* A table in the database */
  75051. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  75052. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  75053. assert( pDb!=0 );
  75054. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  75055. pTab = (Table*)sqliteHashData(k);
  75056. reindexTable(pParse, pTab, zColl);
  75057. }
  75058. }
  75059. }
  75060. #endif
  75061. /*
  75062. ** Generate code for the REINDEX command.
  75063. **
  75064. ** REINDEX -- 1
  75065. ** REINDEX <collation> -- 2
  75066. ** REINDEX ?<database>.?<tablename> -- 3
  75067. ** REINDEX ?<database>.?<indexname> -- 4
  75068. **
  75069. ** Form 1 causes all indices in all attached databases to be rebuilt.
  75070. ** Form 2 rebuilds all indices in all databases that use the named
  75071. ** collating function. Forms 3 and 4 rebuild the named index or all
  75072. ** indices associated with the named table.
  75073. */
  75074. #ifndef SQLITE_OMIT_REINDEX
  75075. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  75076. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  75077. char *z; /* Name of a table or index */
  75078. const char *zDb; /* Name of the database */
  75079. Table *pTab; /* A table in the database */
  75080. Index *pIndex; /* An index associated with pTab */
  75081. int iDb; /* The database index number */
  75082. sqlite3 *db = pParse->db; /* The database connection */
  75083. Token *pObjName; /* Name of the table or index to be reindexed */
  75084. /* Read the database schema. If an error occurs, leave an error message
  75085. ** and code in pParse and return NULL. */
  75086. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  75087. return;
  75088. }
  75089. if( pName1==0 ){
  75090. reindexDatabases(pParse, 0);
  75091. return;
  75092. }else if( NEVER(pName2==0) || pName2->z==0 ){
  75093. char *zColl;
  75094. assert( pName1->z );
  75095. zColl = sqlite3NameFromToken(pParse->db, pName1);
  75096. if( !zColl ) return;
  75097. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  75098. if( pColl ){
  75099. reindexDatabases(pParse, zColl);
  75100. sqlite3DbFree(db, zColl);
  75101. return;
  75102. }
  75103. sqlite3DbFree(db, zColl);
  75104. }
  75105. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  75106. if( iDb<0 ) return;
  75107. z = sqlite3NameFromToken(db, pObjName);
  75108. if( z==0 ) return;
  75109. zDb = db->aDb[iDb].zName;
  75110. pTab = sqlite3FindTable(db, z, zDb);
  75111. if( pTab ){
  75112. reindexTable(pParse, pTab, 0);
  75113. sqlite3DbFree(db, z);
  75114. return;
  75115. }
  75116. pIndex = sqlite3FindIndex(db, z, zDb);
  75117. sqlite3DbFree(db, z);
  75118. if( pIndex ){
  75119. sqlite3BeginWriteOperation(pParse, 0, iDb);
  75120. sqlite3RefillIndex(pParse, pIndex, -1);
  75121. return;
  75122. }
  75123. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  75124. }
  75125. #endif
  75126. /*
  75127. ** Return a dynamicly allocated KeyInfo structure that can be used
  75128. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  75129. **
  75130. ** If successful, a pointer to the new structure is returned. In this case
  75131. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  75132. ** pointer. If an error occurs (out of memory or missing collation
  75133. ** sequence), NULL is returned and the state of pParse updated to reflect
  75134. ** the error.
  75135. */
  75136. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  75137. int i;
  75138. int nCol = pIdx->nColumn;
  75139. int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  75140. sqlite3 *db = pParse->db;
  75141. KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
  75142. if( pKey ){
  75143. pKey->db = pParse->db;
  75144. pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
  75145. assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
  75146. for(i=0; i<nCol; i++){
  75147. char *zColl = pIdx->azColl[i];
  75148. assert( zColl );
  75149. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  75150. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  75151. }
  75152. pKey->nField = (u16)nCol;
  75153. }
  75154. if( pParse->nErr ){
  75155. sqlite3DbFree(db, pKey);
  75156. pKey = 0;
  75157. }
  75158. return pKey;
  75159. }
  75160. /************** End of build.c ***********************************************/
  75161. /************** Begin file callback.c ****************************************/
  75162. /*
  75163. ** 2005 May 23
  75164. **
  75165. ** The author disclaims copyright to this source code. In place of
  75166. ** a legal notice, here is a blessing:
  75167. **
  75168. ** May you do good and not evil.
  75169. ** May you find forgiveness for yourself and forgive others.
  75170. ** May you share freely, never taking more than you give.
  75171. **
  75172. *************************************************************************
  75173. **
  75174. ** This file contains functions used to access the internal hash tables
  75175. ** of user defined functions and collation sequences.
  75176. */
  75177. /*
  75178. ** Invoke the 'collation needed' callback to request a collation sequence
  75179. ** in the encoding enc of name zName, length nName.
  75180. */
  75181. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  75182. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  75183. if( db->xCollNeeded ){
  75184. char *zExternal = sqlite3DbStrDup(db, zName);
  75185. if( !zExternal ) return;
  75186. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  75187. sqlite3DbFree(db, zExternal);
  75188. }
  75189. #ifndef SQLITE_OMIT_UTF16
  75190. if( db->xCollNeeded16 ){
  75191. char const *zExternal;
  75192. sqlite3_value *pTmp = sqlite3ValueNew(db);
  75193. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  75194. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  75195. if( zExternal ){
  75196. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  75197. }
  75198. sqlite3ValueFree(pTmp);
  75199. }
  75200. #endif
  75201. }
  75202. /*
  75203. ** This routine is called if the collation factory fails to deliver a
  75204. ** collation function in the best encoding but there may be other versions
  75205. ** of this collation function (for other text encodings) available. Use one
  75206. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  75207. ** possible.
  75208. */
  75209. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  75210. CollSeq *pColl2;
  75211. char *z = pColl->zName;
  75212. int i;
  75213. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  75214. for(i=0; i<3; i++){
  75215. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  75216. if( pColl2->xCmp!=0 ){
  75217. memcpy(pColl, pColl2, sizeof(CollSeq));
  75218. pColl->xDel = 0; /* Do not copy the destructor */
  75219. return SQLITE_OK;
  75220. }
  75221. }
  75222. return SQLITE_ERROR;
  75223. }
  75224. /*
  75225. ** This function is responsible for invoking the collation factory callback
  75226. ** or substituting a collation sequence of a different encoding when the
  75227. ** requested collation sequence is not available in the desired encoding.
  75228. **
  75229. ** If it is not NULL, then pColl must point to the database native encoding
  75230. ** collation sequence with name zName, length nName.
  75231. **
  75232. ** The return value is either the collation sequence to be used in database
  75233. ** db for collation type name zName, length nName, or NULL, if no collation
  75234. ** sequence can be found.
  75235. **
  75236. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  75237. */
  75238. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  75239. sqlite3* db, /* The database connection */
  75240. u8 enc, /* The desired encoding for the collating sequence */
  75241. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  75242. const char *zName /* Collating sequence name */
  75243. ){
  75244. CollSeq *p;
  75245. p = pColl;
  75246. if( !p ){
  75247. p = sqlite3FindCollSeq(db, enc, zName, 0);
  75248. }
  75249. if( !p || !p->xCmp ){
  75250. /* No collation sequence of this type for this encoding is registered.
  75251. ** Call the collation factory to see if it can supply us with one.
  75252. */
  75253. callCollNeeded(db, enc, zName);
  75254. p = sqlite3FindCollSeq(db, enc, zName, 0);
  75255. }
  75256. if( p && !p->xCmp && synthCollSeq(db, p) ){
  75257. p = 0;
  75258. }
  75259. assert( !p || p->xCmp );
  75260. return p;
  75261. }
  75262. /*
  75263. ** This routine is called on a collation sequence before it is used to
  75264. ** check that it is defined. An undefined collation sequence exists when
  75265. ** a database is loaded that contains references to collation sequences
  75266. ** that have not been defined by sqlite3_create_collation() etc.
  75267. **
  75268. ** If required, this routine calls the 'collation needed' callback to
  75269. ** request a definition of the collating sequence. If this doesn't work,
  75270. ** an equivalent collating sequence that uses a text encoding different
  75271. ** from the main database is substituted, if one is available.
  75272. */
  75273. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  75274. if( pColl ){
  75275. const char *zName = pColl->zName;
  75276. sqlite3 *db = pParse->db;
  75277. CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
  75278. if( !p ){
  75279. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  75280. pParse->nErr++;
  75281. return SQLITE_ERROR;
  75282. }
  75283. assert( p==pColl );
  75284. }
  75285. return SQLITE_OK;
  75286. }
  75287. /*
  75288. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  75289. ** specified by zName and nName is not found and parameter 'create' is
  75290. ** true, then create a new entry. Otherwise return NULL.
  75291. **
  75292. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  75293. ** array of three CollSeq structures. The first is the collation sequence
  75294. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  75295. **
  75296. ** Stored immediately after the three collation sequences is a copy of
  75297. ** the collation sequence name. A pointer to this string is stored in
  75298. ** each collation sequence structure.
  75299. */
  75300. static CollSeq *findCollSeqEntry(
  75301. sqlite3 *db, /* Database connection */
  75302. const char *zName, /* Name of the collating sequence */
  75303. int create /* Create a new entry if true */
  75304. ){
  75305. CollSeq *pColl;
  75306. int nName = sqlite3Strlen30(zName);
  75307. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  75308. if( 0==pColl && create ){
  75309. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  75310. if( pColl ){
  75311. CollSeq *pDel = 0;
  75312. pColl[0].zName = (char*)&pColl[3];
  75313. pColl[0].enc = SQLITE_UTF8;
  75314. pColl[1].zName = (char*)&pColl[3];
  75315. pColl[1].enc = SQLITE_UTF16LE;
  75316. pColl[2].zName = (char*)&pColl[3];
  75317. pColl[2].enc = SQLITE_UTF16BE;
  75318. memcpy(pColl[0].zName, zName, nName);
  75319. pColl[0].zName[nName] = 0;
  75320. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  75321. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  75322. ** return the pColl pointer to be deleted (because it wasn't added
  75323. ** to the hash table).
  75324. */
  75325. assert( pDel==0 || pDel==pColl );
  75326. if( pDel!=0 ){
  75327. db->mallocFailed = 1;
  75328. sqlite3DbFree(db, pDel);
  75329. pColl = 0;
  75330. }
  75331. }
  75332. }
  75333. return pColl;
  75334. }
  75335. /*
  75336. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  75337. ** Return the CollSeq* pointer for the collation sequence named zName
  75338. ** for the encoding 'enc' from the database 'db'.
  75339. **
  75340. ** If the entry specified is not found and 'create' is true, then create a
  75341. ** new entry. Otherwise return NULL.
  75342. **
  75343. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  75344. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  75345. ** if necessary and generates an error message if the collating sequence
  75346. ** cannot be found.
  75347. **
  75348. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  75349. */
  75350. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  75351. sqlite3 *db,
  75352. u8 enc,
  75353. const char *zName,
  75354. int create
  75355. ){
  75356. CollSeq *pColl;
  75357. if( zName ){
  75358. pColl = findCollSeqEntry(db, zName, create);
  75359. }else{
  75360. pColl = db->pDfltColl;
  75361. }
  75362. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  75363. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  75364. if( pColl ) pColl += enc-1;
  75365. return pColl;
  75366. }
  75367. /* During the search for the best function definition, this procedure
  75368. ** is called to test how well the function passed as the first argument
  75369. ** matches the request for a function with nArg arguments in a system
  75370. ** that uses encoding enc. The value returned indicates how well the
  75371. ** request is matched. A higher value indicates a better match.
  75372. **
  75373. ** The returned value is always between 0 and 6, as follows:
  75374. **
  75375. ** 0: Not a match, or if nArg<0 and the function is has no implementation.
  75376. ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
  75377. ** encoding is requested, or vice versa.
  75378. ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
  75379. ** requested, or vice versa.
  75380. ** 3: A variable arguments function using the same text encoding.
  75381. ** 4: A function with the exact number of arguments requested that
  75382. ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
  75383. ** 5: A function with the exact number of arguments requested that
  75384. ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
  75385. ** 6: An exact match.
  75386. **
  75387. */
  75388. static int matchQuality(FuncDef *p, int nArg, u8 enc){
  75389. int match = 0;
  75390. if( p->nArg==-1 || p->nArg==nArg
  75391. || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
  75392. ){
  75393. match = 1;
  75394. if( p->nArg==nArg || nArg==-1 ){
  75395. match = 4;
  75396. }
  75397. if( enc==p->iPrefEnc ){
  75398. match += 2;
  75399. }
  75400. else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
  75401. (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
  75402. match += 1;
  75403. }
  75404. }
  75405. return match;
  75406. }
  75407. /*
  75408. ** Search a FuncDefHash for a function with the given name. Return
  75409. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  75410. */
  75411. static FuncDef *functionSearch(
  75412. FuncDefHash *pHash, /* Hash table to search */
  75413. int h, /* Hash of the name */
  75414. const char *zFunc, /* Name of function */
  75415. int nFunc /* Number of bytes in zFunc */
  75416. ){
  75417. FuncDef *p;
  75418. for(p=pHash->a[h]; p; p=p->pHash){
  75419. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  75420. return p;
  75421. }
  75422. }
  75423. return 0;
  75424. }
  75425. /*
  75426. ** Insert a new FuncDef into a FuncDefHash hash table.
  75427. */
  75428. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  75429. FuncDefHash *pHash, /* The hash table into which to insert */
  75430. FuncDef *pDef /* The function definition to insert */
  75431. ){
  75432. FuncDef *pOther;
  75433. int nName = sqlite3Strlen30(pDef->zName);
  75434. u8 c1 = (u8)pDef->zName[0];
  75435. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  75436. pOther = functionSearch(pHash, h, pDef->zName, nName);
  75437. if( pOther ){
  75438. assert( pOther!=pDef && pOther->pNext!=pDef );
  75439. pDef->pNext = pOther->pNext;
  75440. pOther->pNext = pDef;
  75441. }else{
  75442. pDef->pNext = 0;
  75443. pDef->pHash = pHash->a[h];
  75444. pHash->a[h] = pDef;
  75445. }
  75446. }
  75447. /*
  75448. ** Locate a user function given a name, a number of arguments and a flag
  75449. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  75450. ** pointer to the FuncDef structure that defines that function, or return
  75451. ** NULL if the function does not exist.
  75452. **
  75453. ** If the createFlag argument is true, then a new (blank) FuncDef
  75454. ** structure is created and liked into the "db" structure if a
  75455. ** no matching function previously existed. When createFlag is true
  75456. ** and the nArg parameter is -1, then only a function that accepts
  75457. ** any number of arguments will be returned.
  75458. **
  75459. ** If createFlag is false and nArg is -1, then the first valid
  75460. ** function found is returned. A function is valid if either xFunc
  75461. ** or xStep is non-zero.
  75462. **
  75463. ** If createFlag is false, then a function with the required name and
  75464. ** number of arguments may be returned even if the eTextRep flag does not
  75465. ** match that requested.
  75466. */
  75467. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  75468. sqlite3 *db, /* An open database */
  75469. const char *zName, /* Name of the function. Not null-terminated */
  75470. int nName, /* Number of characters in the name */
  75471. int nArg, /* Number of arguments. -1 means any number */
  75472. u8 enc, /* Preferred text encoding */
  75473. int createFlag /* Create new entry if true and does not otherwise exist */
  75474. ){
  75475. FuncDef *p; /* Iterator variable */
  75476. FuncDef *pBest = 0; /* Best match found so far */
  75477. int bestScore = 0; /* Score of best match */
  75478. int h; /* Hash value */
  75479. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  75480. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  75481. /* First search for a match amongst the application-defined functions.
  75482. */
  75483. p = functionSearch(&db->aFunc, h, zName, nName);
  75484. while( p ){
  75485. int score = matchQuality(p, nArg, enc);
  75486. if( score>bestScore ){
  75487. pBest = p;
  75488. bestScore = score;
  75489. }
  75490. p = p->pNext;
  75491. }
  75492. /* If no match is found, search the built-in functions.
  75493. **
  75494. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  75495. ** functions even if a prior app-defined function was found. And give
  75496. ** priority to built-in functions.
  75497. **
  75498. ** Except, if createFlag is true, that means that we are trying to
  75499. ** install a new function. Whatever FuncDef structure is returned it will
  75500. ** have fields overwritten with new information appropriate for the
  75501. ** new function. But the FuncDefs for built-in functions are read-only.
  75502. ** So we must not search for built-ins when creating a new function.
  75503. */
  75504. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  75505. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  75506. bestScore = 0;
  75507. p = functionSearch(pHash, h, zName, nName);
  75508. while( p ){
  75509. int score = matchQuality(p, nArg, enc);
  75510. if( score>bestScore ){
  75511. pBest = p;
  75512. bestScore = score;
  75513. }
  75514. p = p->pNext;
  75515. }
  75516. }
  75517. /* If the createFlag parameter is true and the search did not reveal an
  75518. ** exact match for the name, number of arguments and encoding, then add a
  75519. ** new entry to the hash table and return it.
  75520. */
  75521. if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
  75522. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  75523. pBest->zName = (char *)&pBest[1];
  75524. pBest->nArg = (u16)nArg;
  75525. pBest->iPrefEnc = enc;
  75526. memcpy(pBest->zName, zName, nName);
  75527. pBest->zName[nName] = 0;
  75528. sqlite3FuncDefInsert(&db->aFunc, pBest);
  75529. }
  75530. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  75531. return pBest;
  75532. }
  75533. return 0;
  75534. }
  75535. /*
  75536. ** Free all resources held by the schema structure. The void* argument points
  75537. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  75538. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  75539. ** of the schema hash tables).
  75540. **
  75541. ** The Schema.cache_size variable is not cleared.
  75542. */
  75543. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  75544. Hash temp1;
  75545. Hash temp2;
  75546. HashElem *pElem;
  75547. Schema *pSchema = (Schema *)p;
  75548. temp1 = pSchema->tblHash;
  75549. temp2 = pSchema->trigHash;
  75550. sqlite3HashInit(&pSchema->trigHash);
  75551. sqlite3HashClear(&pSchema->idxHash);
  75552. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  75553. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  75554. }
  75555. sqlite3HashClear(&temp2);
  75556. sqlite3HashInit(&pSchema->tblHash);
  75557. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  75558. Table *pTab = sqliteHashData(pElem);
  75559. sqlite3DeleteTable(0, pTab);
  75560. }
  75561. sqlite3HashClear(&temp1);
  75562. sqlite3HashClear(&pSchema->fkeyHash);
  75563. pSchema->pSeqTab = 0;
  75564. if( pSchema->flags & DB_SchemaLoaded ){
  75565. pSchema->iGeneration++;
  75566. pSchema->flags &= ~DB_SchemaLoaded;
  75567. }
  75568. }
  75569. /*
  75570. ** Find and return the schema associated with a BTree. Create
  75571. ** a new one if necessary.
  75572. */
  75573. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  75574. Schema * p;
  75575. if( pBt ){
  75576. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  75577. }else{
  75578. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  75579. }
  75580. if( !p ){
  75581. db->mallocFailed = 1;
  75582. }else if ( 0==p->file_format ){
  75583. sqlite3HashInit(&p->tblHash);
  75584. sqlite3HashInit(&p->idxHash);
  75585. sqlite3HashInit(&p->trigHash);
  75586. sqlite3HashInit(&p->fkeyHash);
  75587. p->enc = SQLITE_UTF8;
  75588. }
  75589. return p;
  75590. }
  75591. /************** End of callback.c ********************************************/
  75592. /************** Begin file delete.c ******************************************/
  75593. /*
  75594. ** 2001 September 15
  75595. **
  75596. ** The author disclaims copyright to this source code. In place of
  75597. ** a legal notice, here is a blessing:
  75598. **
  75599. ** May you do good and not evil.
  75600. ** May you find forgiveness for yourself and forgive others.
  75601. ** May you share freely, never taking more than you give.
  75602. **
  75603. *************************************************************************
  75604. ** This file contains C code routines that are called by the parser
  75605. ** in order to generate code for DELETE FROM statements.
  75606. */
  75607. /*
  75608. ** While a SrcList can in general represent multiple tables and subqueries
  75609. ** (as in the FROM clause of a SELECT statement) in this case it contains
  75610. ** the name of a single table, as one might find in an INSERT, DELETE,
  75611. ** or UPDATE statement. Look up that table in the symbol table and
  75612. ** return a pointer. Set an error message and return NULL if the table
  75613. ** name is not found or if any other error occurs.
  75614. **
  75615. ** The following fields are initialized appropriate in pSrc:
  75616. **
  75617. ** pSrc->a[0].pTab Pointer to the Table object
  75618. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  75619. **
  75620. */
  75621. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  75622. struct SrcList_item *pItem = pSrc->a;
  75623. Table *pTab;
  75624. assert( pItem && pSrc->nSrc==1 );
  75625. pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
  75626. sqlite3DeleteTable(pParse->db, pItem->pTab);
  75627. pItem->pTab = pTab;
  75628. if( pTab ){
  75629. pTab->nRef++;
  75630. }
  75631. if( sqlite3IndexedByLookup(pParse, pItem) ){
  75632. pTab = 0;
  75633. }
  75634. return pTab;
  75635. }
  75636. /*
  75637. ** Check to make sure the given table is writable. If it is not
  75638. ** writable, generate an error message and return 1. If it is
  75639. ** writable return 0;
  75640. */
  75641. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  75642. /* A table is not writable under the following circumstances:
  75643. **
  75644. ** 1) It is a virtual table and no implementation of the xUpdate method
  75645. ** has been provided, or
  75646. ** 2) It is a system table (i.e. sqlite_master), this call is not
  75647. ** part of a nested parse and writable_schema pragma has not
  75648. ** been specified.
  75649. **
  75650. ** In either case leave an error message in pParse and return non-zero.
  75651. */
  75652. if( ( IsVirtual(pTab)
  75653. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  75654. || ( (pTab->tabFlags & TF_Readonly)!=0
  75655. && (pParse->db->flags & SQLITE_WriteSchema)==0
  75656. && pParse->nested==0 )
  75657. ){
  75658. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  75659. return 1;
  75660. }
  75661. #ifndef SQLITE_OMIT_VIEW
  75662. if( !viewOk && pTab->pSelect ){
  75663. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  75664. return 1;
  75665. }
  75666. #endif
  75667. return 0;
  75668. }
  75669. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  75670. /*
  75671. ** Evaluate a view and store its result in an ephemeral table. The
  75672. ** pWhere argument is an optional WHERE clause that restricts the
  75673. ** set of rows in the view that are to be added to the ephemeral table.
  75674. */
  75675. SQLITE_PRIVATE void sqlite3MaterializeView(
  75676. Parse *pParse, /* Parsing context */
  75677. Table *pView, /* View definition */
  75678. Expr *pWhere, /* Optional WHERE clause to be added */
  75679. int iCur /* Cursor number for ephemerial table */
  75680. ){
  75681. SelectDest dest;
  75682. Select *pDup;
  75683. sqlite3 *db = pParse->db;
  75684. pDup = sqlite3SelectDup(db, pView->pSelect, 0);
  75685. if( pWhere ){
  75686. SrcList *pFrom;
  75687. pWhere = sqlite3ExprDup(db, pWhere, 0);
  75688. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  75689. if( pFrom ){
  75690. assert( pFrom->nSrc==1 );
  75691. pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
  75692. pFrom->a[0].pSelect = pDup;
  75693. assert( pFrom->a[0].pOn==0 );
  75694. assert( pFrom->a[0].pUsing==0 );
  75695. }else{
  75696. sqlite3SelectDelete(db, pDup);
  75697. }
  75698. pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  75699. }
  75700. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  75701. sqlite3Select(pParse, pDup, &dest);
  75702. sqlite3SelectDelete(db, pDup);
  75703. }
  75704. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  75705. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  75706. /*
  75707. ** Generate an expression tree to implement the WHERE, ORDER BY,
  75708. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  75709. **
  75710. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  75711. ** \__________________________/
  75712. ** pLimitWhere (pInClause)
  75713. */
  75714. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  75715. Parse *pParse, /* The parser context */
  75716. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  75717. Expr *pWhere, /* The WHERE clause. May be null */
  75718. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  75719. Expr *pLimit, /* The LIMIT clause. May be null */
  75720. Expr *pOffset, /* The OFFSET clause. May be null */
  75721. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  75722. ){
  75723. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  75724. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  75725. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  75726. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  75727. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  75728. Select *pSelect = NULL; /* Complete SELECT tree */
  75729. /* Check that there isn't an ORDER BY without a LIMIT clause.
  75730. */
  75731. if( pOrderBy && (pLimit == 0) ) {
  75732. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  75733. pParse->parseError = 1;
  75734. goto limit_where_cleanup_2;
  75735. }
  75736. /* We only need to generate a select expression if there
  75737. ** is a limit/offset term to enforce.
  75738. */
  75739. if( pLimit == 0 ) {
  75740. /* if pLimit is null, pOffset will always be null as well. */
  75741. assert( pOffset == 0 );
  75742. return pWhere;
  75743. }
  75744. /* Generate a select expression tree to enforce the limit/offset
  75745. ** term for the DELETE or UPDATE statement. For example:
  75746. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  75747. ** becomes:
  75748. ** DELETE FROM table_a WHERE rowid IN (
  75749. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  75750. ** );
  75751. */
  75752. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  75753. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  75754. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  75755. if( pEList == 0 ) goto limit_where_cleanup_2;
  75756. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  75757. ** and the SELECT subtree. */
  75758. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  75759. if( pSelectSrc == 0 ) {
  75760. sqlite3ExprListDelete(pParse->db, pEList);
  75761. goto limit_where_cleanup_2;
  75762. }
  75763. /* generate the SELECT expression tree. */
  75764. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  75765. pOrderBy,0,pLimit,pOffset);
  75766. if( pSelect == 0 ) return 0;
  75767. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  75768. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  75769. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  75770. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  75771. if( pInClause == 0 ) goto limit_where_cleanup_1;
  75772. pInClause->x.pSelect = pSelect;
  75773. pInClause->flags |= EP_xIsSelect;
  75774. sqlite3ExprSetHeight(pParse, pInClause);
  75775. return pInClause;
  75776. /* something went wrong. clean up anything allocated. */
  75777. limit_where_cleanup_1:
  75778. sqlite3SelectDelete(pParse->db, pSelect);
  75779. return 0;
  75780. limit_where_cleanup_2:
  75781. sqlite3ExprDelete(pParse->db, pWhere);
  75782. sqlite3ExprListDelete(pParse->db, pOrderBy);
  75783. sqlite3ExprDelete(pParse->db, pLimit);
  75784. sqlite3ExprDelete(pParse->db, pOffset);
  75785. return 0;
  75786. }
  75787. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  75788. /*
  75789. ** Generate code for a DELETE FROM statement.
  75790. **
  75791. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  75792. ** \________/ \________________/
  75793. ** pTabList pWhere
  75794. */
  75795. SQLITE_PRIVATE void sqlite3DeleteFrom(
  75796. Parse *pParse, /* The parser context */
  75797. SrcList *pTabList, /* The table from which we should delete things */
  75798. Expr *pWhere /* The WHERE clause. May be null */
  75799. ){
  75800. Vdbe *v; /* The virtual database engine */
  75801. Table *pTab; /* The table from which records will be deleted */
  75802. const char *zDb; /* Name of database holding pTab */
  75803. int end, addr = 0; /* A couple addresses of generated code */
  75804. int i; /* Loop counter */
  75805. WhereInfo *pWInfo; /* Information about the WHERE clause */
  75806. Index *pIdx; /* For looping over indices of the table */
  75807. int iCur; /* VDBE Cursor number for pTab */
  75808. sqlite3 *db; /* Main database structure */
  75809. AuthContext sContext; /* Authorization context */
  75810. NameContext sNC; /* Name context to resolve expressions in */
  75811. int iDb; /* Database number */
  75812. int memCnt = -1; /* Memory cell used for change counting */
  75813. int rcauth; /* Value returned by authorization callback */
  75814. #ifndef SQLITE_OMIT_TRIGGER
  75815. int isView; /* True if attempting to delete from a view */
  75816. Trigger *pTrigger; /* List of table triggers, if required */
  75817. #endif
  75818. memset(&sContext, 0, sizeof(sContext));
  75819. db = pParse->db;
  75820. if( pParse->nErr || db->mallocFailed ){
  75821. goto delete_from_cleanup;
  75822. }
  75823. assert( pTabList->nSrc==1 );
  75824. /* Locate the table which we want to delete. This table has to be
  75825. ** put in an SrcList structure because some of the subroutines we
  75826. ** will be calling are designed to work with multiple tables and expect
  75827. ** an SrcList* parameter instead of just a Table* parameter.
  75828. */
  75829. pTab = sqlite3SrcListLookup(pParse, pTabList);
  75830. if( pTab==0 ) goto delete_from_cleanup;
  75831. /* Figure out if we have any triggers and if the table being
  75832. ** deleted from is a view
  75833. */
  75834. #ifndef SQLITE_OMIT_TRIGGER
  75835. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  75836. isView = pTab->pSelect!=0;
  75837. #else
  75838. # define pTrigger 0
  75839. # define isView 0
  75840. #endif
  75841. #ifdef SQLITE_OMIT_VIEW
  75842. # undef isView
  75843. # define isView 0
  75844. #endif
  75845. /* If pTab is really a view, make sure it has been initialized.
  75846. */
  75847. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  75848. goto delete_from_cleanup;
  75849. }
  75850. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  75851. goto delete_from_cleanup;
  75852. }
  75853. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75854. assert( iDb<db->nDb );
  75855. zDb = db->aDb[iDb].zName;
  75856. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  75857. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  75858. if( rcauth==SQLITE_DENY ){
  75859. goto delete_from_cleanup;
  75860. }
  75861. assert(!isView || pTrigger);
  75862. /* Assign cursor number to the table and all its indices.
  75863. */
  75864. assert( pTabList->nSrc==1 );
  75865. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  75866. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  75867. pParse->nTab++;
  75868. }
  75869. /* Start the view context
  75870. */
  75871. if( isView ){
  75872. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  75873. }
  75874. /* Begin generating code.
  75875. */
  75876. v = sqlite3GetVdbe(pParse);
  75877. if( v==0 ){
  75878. goto delete_from_cleanup;
  75879. }
  75880. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  75881. sqlite3BeginWriteOperation(pParse, 1, iDb);
  75882. /* If we are trying to delete from a view, realize that view into
  75883. ** a ephemeral table.
  75884. */
  75885. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  75886. if( isView ){
  75887. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  75888. }
  75889. #endif
  75890. /* Resolve the column names in the WHERE clause.
  75891. */
  75892. memset(&sNC, 0, sizeof(sNC));
  75893. sNC.pParse = pParse;
  75894. sNC.pSrcList = pTabList;
  75895. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  75896. goto delete_from_cleanup;
  75897. }
  75898. /* Initialize the counter of the number of rows deleted, if
  75899. ** we are counting rows.
  75900. */
  75901. if( db->flags & SQLITE_CountRows ){
  75902. memCnt = ++pParse->nMem;
  75903. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  75904. }
  75905. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  75906. /* Special case: A DELETE without a WHERE clause deletes everything.
  75907. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  75908. ** this optimization caused the row change count (the value returned by
  75909. ** API function sqlite3_count_changes) to be set incorrectly. */
  75910. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  75911. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  75912. ){
  75913. assert( !isView );
  75914. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  75915. pTab->zName, P4_STATIC);
  75916. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  75917. assert( pIdx->pSchema==pTab->pSchema );
  75918. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  75919. }
  75920. }else
  75921. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  75922. /* The usual case: There is a WHERE clause so we have to scan through
  75923. ** the table and pick which records to delete.
  75924. */
  75925. {
  75926. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  75927. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  75928. int regRowid; /* Actual register containing rowids */
  75929. /* Collect rowids of every row to be deleted.
  75930. */
  75931. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  75932. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
  75933. if( pWInfo==0 ) goto delete_from_cleanup;
  75934. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
  75935. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  75936. if( db->flags & SQLITE_CountRows ){
  75937. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  75938. }
  75939. sqlite3WhereEnd(pWInfo);
  75940. /* Delete every item whose key was written to the list during the
  75941. ** database scan. We have to delete items after the scan is complete
  75942. ** because deleting an item can change the scan order. */
  75943. end = sqlite3VdbeMakeLabel(v);
  75944. /* Unless this is a view, open cursors for the table we are
  75945. ** deleting from and all its indices. If this is a view, then the
  75946. ** only effect this statement has is to fire the INSTEAD OF
  75947. ** triggers. */
  75948. if( !isView ){
  75949. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  75950. }
  75951. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  75952. /* Delete the row */
  75953. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75954. if( IsVirtual(pTab) ){
  75955. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  75956. sqlite3VtabMakeWritable(pParse, pTab);
  75957. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  75958. sqlite3MayAbort(pParse);
  75959. }else
  75960. #endif
  75961. {
  75962. int count = (pParse->nested==0); /* True to count changes */
  75963. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  75964. }
  75965. /* End of the delete loop */
  75966. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  75967. sqlite3VdbeResolveLabel(v, end);
  75968. /* Close the cursors open on the table and its indexes. */
  75969. if( !isView && !IsVirtual(pTab) ){
  75970. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  75971. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  75972. }
  75973. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  75974. }
  75975. }
  75976. /* Update the sqlite_sequence table by storing the content of the
  75977. ** maximum rowid counter values recorded while inserting into
  75978. ** autoincrement tables.
  75979. */
  75980. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  75981. sqlite3AutoincrementEnd(pParse);
  75982. }
  75983. /* Return the number of rows that were deleted. If this routine is
  75984. ** generating code because of a call to sqlite3NestedParse(), do not
  75985. ** invoke the callback function.
  75986. */
  75987. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  75988. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  75989. sqlite3VdbeSetNumCols(v, 1);
  75990. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  75991. }
  75992. delete_from_cleanup:
  75993. sqlite3AuthContextPop(&sContext);
  75994. sqlite3SrcListDelete(db, pTabList);
  75995. sqlite3ExprDelete(db, pWhere);
  75996. return;
  75997. }
  75998. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  75999. ** thely may interfere with compilation of other functions in this file
  76000. ** (or in another file, if this file becomes part of the amalgamation). */
  76001. #ifdef isView
  76002. #undef isView
  76003. #endif
  76004. #ifdef pTrigger
  76005. #undef pTrigger
  76006. #endif
  76007. /*
  76008. ** This routine generates VDBE code that causes a single row of a
  76009. ** single table to be deleted.
  76010. **
  76011. ** The VDBE must be in a particular state when this routine is called.
  76012. ** These are the requirements:
  76013. **
  76014. ** 1. A read/write cursor pointing to pTab, the table containing the row
  76015. ** to be deleted, must be opened as cursor number $iCur.
  76016. **
  76017. ** 2. Read/write cursors for all indices of pTab must be open as
  76018. ** cursor number base+i for the i-th index.
  76019. **
  76020. ** 3. The record number of the row to be deleted must be stored in
  76021. ** memory cell iRowid.
  76022. **
  76023. ** This routine generates code to remove both the table record and all
  76024. ** index entries that point to that record.
  76025. */
  76026. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  76027. Parse *pParse, /* Parsing context */
  76028. Table *pTab, /* Table containing the row to be deleted */
  76029. int iCur, /* Cursor number for the table */
  76030. int iRowid, /* Memory cell that contains the rowid to delete */
  76031. int count, /* If non-zero, increment the row change counter */
  76032. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  76033. int onconf /* Default ON CONFLICT policy for triggers */
  76034. ){
  76035. Vdbe *v = pParse->pVdbe; /* Vdbe */
  76036. int iOld = 0; /* First register in OLD.* array */
  76037. int iLabel; /* Label resolved to end of generated code */
  76038. /* Vdbe is guaranteed to have been allocated by this stage. */
  76039. assert( v );
  76040. /* Seek cursor iCur to the row to delete. If this row no longer exists
  76041. ** (this can happen if a trigger program has already deleted it), do
  76042. ** not attempt to delete it or fire any DELETE triggers. */
  76043. iLabel = sqlite3VdbeMakeLabel(v);
  76044. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  76045. /* If there are any triggers to fire, allocate a range of registers to
  76046. ** use for the old.* references in the triggers. */
  76047. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  76048. u32 mask; /* Mask of OLD.* columns in use */
  76049. int iCol; /* Iterator used while populating OLD.* */
  76050. /* TODO: Could use temporary registers here. Also could attempt to
  76051. ** avoid copying the contents of the rowid register. */
  76052. mask = sqlite3TriggerColmask(
  76053. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  76054. );
  76055. mask |= sqlite3FkOldmask(pParse, pTab);
  76056. iOld = pParse->nMem+1;
  76057. pParse->nMem += (1 + pTab->nCol);
  76058. /* Populate the OLD.* pseudo-table register array. These values will be
  76059. ** used by any BEFORE and AFTER triggers that exist. */
  76060. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  76061. for(iCol=0; iCol<pTab->nCol; iCol++){
  76062. if( mask==0xffffffff || mask&(1<<iCol) ){
  76063. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  76064. }
  76065. }
  76066. /* Invoke BEFORE DELETE trigger programs. */
  76067. sqlite3CodeRowTrigger(pParse, pTrigger,
  76068. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  76069. );
  76070. /* Seek the cursor to the row to be deleted again. It may be that
  76071. ** the BEFORE triggers coded above have already removed the row
  76072. ** being deleted. Do not attempt to delete the row a second time, and
  76073. ** do not fire AFTER triggers. */
  76074. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  76075. /* Do FK processing. This call checks that any FK constraints that
  76076. ** refer to this table (i.e. constraints attached to other tables)
  76077. ** are not violated by deleting this row. */
  76078. sqlite3FkCheck(pParse, pTab, iOld, 0);
  76079. }
  76080. /* Delete the index and table entries. Skip this step if pTab is really
  76081. ** a view (in which case the only effect of the DELETE statement is to
  76082. ** fire the INSTEAD OF triggers). */
  76083. if( pTab->pSelect==0 ){
  76084. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  76085. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  76086. if( count ){
  76087. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  76088. }
  76089. }
  76090. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  76091. ** handle rows (possibly in other tables) that refer via a foreign key
  76092. ** to the row just deleted. */
  76093. sqlite3FkActions(pParse, pTab, 0, iOld);
  76094. /* Invoke AFTER DELETE trigger programs. */
  76095. sqlite3CodeRowTrigger(pParse, pTrigger,
  76096. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  76097. );
  76098. /* Jump here if the row had already been deleted before any BEFORE
  76099. ** trigger programs were invoked. Or if a trigger program throws a
  76100. ** RAISE(IGNORE) exception. */
  76101. sqlite3VdbeResolveLabel(v, iLabel);
  76102. }
  76103. /*
  76104. ** This routine generates VDBE code that causes the deletion of all
  76105. ** index entries associated with a single row of a single table.
  76106. **
  76107. ** The VDBE must be in a particular state when this routine is called.
  76108. ** These are the requirements:
  76109. **
  76110. ** 1. A read/write cursor pointing to pTab, the table containing the row
  76111. ** to be deleted, must be opened as cursor number "iCur".
  76112. **
  76113. ** 2. Read/write cursors for all indices of pTab must be open as
  76114. ** cursor number iCur+i for the i-th index.
  76115. **
  76116. ** 3. The "iCur" cursor must be pointing to the row that is to be
  76117. ** deleted.
  76118. */
  76119. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  76120. Parse *pParse, /* Parsing and code generating context */
  76121. Table *pTab, /* Table containing the row to be deleted */
  76122. int iCur, /* Cursor number for the table */
  76123. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  76124. ){
  76125. int i;
  76126. Index *pIdx;
  76127. int r1;
  76128. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  76129. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  76130. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
  76131. sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
  76132. }
  76133. }
  76134. /*
  76135. ** Generate code that will assemble an index key and put it in register
  76136. ** regOut. The key with be for index pIdx which is an index on pTab.
  76137. ** iCur is the index of a cursor open on the pTab table and pointing to
  76138. ** the entry that needs indexing.
  76139. **
  76140. ** Return a register number which is the first in a block of
  76141. ** registers that holds the elements of the index key. The
  76142. ** block of registers has already been deallocated by the time
  76143. ** this routine returns.
  76144. */
  76145. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  76146. Parse *pParse, /* Parsing context */
  76147. Index *pIdx, /* The index for which to generate a key */
  76148. int iCur, /* Cursor number for the pIdx->pTable table */
  76149. int regOut, /* Write the new index key to this register */
  76150. int doMakeRec /* Run the OP_MakeRecord instruction if true */
  76151. ){
  76152. Vdbe *v = pParse->pVdbe;
  76153. int j;
  76154. Table *pTab = pIdx->pTable;
  76155. int regBase;
  76156. int nCol;
  76157. nCol = pIdx->nColumn;
  76158. regBase = sqlite3GetTempRange(pParse, nCol+1);
  76159. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  76160. for(j=0; j<nCol; j++){
  76161. int idx = pIdx->aiColumn[j];
  76162. if( idx==pTab->iPKey ){
  76163. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  76164. }else{
  76165. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  76166. sqlite3ColumnDefault(v, pTab, idx, -1);
  76167. }
  76168. }
  76169. if( doMakeRec ){
  76170. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  76171. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  76172. }
  76173. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  76174. return regBase;
  76175. }
  76176. /************** End of delete.c **********************************************/
  76177. /************** Begin file func.c ********************************************/
  76178. /*
  76179. ** 2002 February 23
  76180. **
  76181. ** The author disclaims copyright to this source code. In place of
  76182. ** a legal notice, here is a blessing:
  76183. **
  76184. ** May you do good and not evil.
  76185. ** May you find forgiveness for yourself and forgive others.
  76186. ** May you share freely, never taking more than you give.
  76187. **
  76188. *************************************************************************
  76189. ** This file contains the C functions that implement various SQL
  76190. ** functions of SQLite.
  76191. **
  76192. ** There is only one exported symbol in this file - the function
  76193. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  76194. ** All other code has file scope.
  76195. */
  76196. /*
  76197. ** Return the collating function associated with a function.
  76198. */
  76199. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  76200. return context->pColl;
  76201. }
  76202. /*
  76203. ** Implementation of the non-aggregate min() and max() functions
  76204. */
  76205. static void minmaxFunc(
  76206. sqlite3_context *context,
  76207. int argc,
  76208. sqlite3_value **argv
  76209. ){
  76210. int i;
  76211. int mask; /* 0 for min() or 0xffffffff for max() */
  76212. int iBest;
  76213. CollSeq *pColl;
  76214. assert( argc>1 );
  76215. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  76216. pColl = sqlite3GetFuncCollSeq(context);
  76217. assert( pColl );
  76218. assert( mask==-1 || mask==0 );
  76219. iBest = 0;
  76220. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  76221. for(i=1; i<argc; i++){
  76222. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  76223. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  76224. testcase( mask==0 );
  76225. iBest = i;
  76226. }
  76227. }
  76228. sqlite3_result_value(context, argv[iBest]);
  76229. }
  76230. /*
  76231. ** Return the type of the argument.
  76232. */
  76233. static void typeofFunc(
  76234. sqlite3_context *context,
  76235. int NotUsed,
  76236. sqlite3_value **argv
  76237. ){
  76238. const char *z = 0;
  76239. UNUSED_PARAMETER(NotUsed);
  76240. switch( sqlite3_value_type(argv[0]) ){
  76241. case SQLITE_INTEGER: z = "integer"; break;
  76242. case SQLITE_TEXT: z = "text"; break;
  76243. case SQLITE_FLOAT: z = "real"; break;
  76244. case SQLITE_BLOB: z = "blob"; break;
  76245. default: z = "null"; break;
  76246. }
  76247. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  76248. }
  76249. /*
  76250. ** Implementation of the length() function
  76251. */
  76252. static void lengthFunc(
  76253. sqlite3_context *context,
  76254. int argc,
  76255. sqlite3_value **argv
  76256. ){
  76257. int len;
  76258. assert( argc==1 );
  76259. UNUSED_PARAMETER(argc);
  76260. switch( sqlite3_value_type(argv[0]) ){
  76261. case SQLITE_BLOB:
  76262. case SQLITE_INTEGER:
  76263. case SQLITE_FLOAT: {
  76264. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  76265. break;
  76266. }
  76267. case SQLITE_TEXT: {
  76268. const unsigned char *z = sqlite3_value_text(argv[0]);
  76269. if( z==0 ) return;
  76270. len = 0;
  76271. while( *z ){
  76272. len++;
  76273. SQLITE_SKIP_UTF8(z);
  76274. }
  76275. sqlite3_result_int(context, len);
  76276. break;
  76277. }
  76278. default: {
  76279. sqlite3_result_null(context);
  76280. break;
  76281. }
  76282. }
  76283. }
  76284. /*
  76285. ** Implementation of the abs() function.
  76286. **
  76287. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  76288. ** the numeric argument X.
  76289. */
  76290. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  76291. assert( argc==1 );
  76292. UNUSED_PARAMETER(argc);
  76293. switch( sqlite3_value_type(argv[0]) ){
  76294. case SQLITE_INTEGER: {
  76295. i64 iVal = sqlite3_value_int64(argv[0]);
  76296. if( iVal<0 ){
  76297. if( (iVal<<1)==0 ){
  76298. /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
  76299. ** abs(X) throws an integer overflow error since there is no
  76300. ** equivalent positive 64-bit two complement value. */
  76301. sqlite3_result_error(context, "integer overflow", -1);
  76302. return;
  76303. }
  76304. iVal = -iVal;
  76305. }
  76306. sqlite3_result_int64(context, iVal);
  76307. break;
  76308. }
  76309. case SQLITE_NULL: {
  76310. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  76311. sqlite3_result_null(context);
  76312. break;
  76313. }
  76314. default: {
  76315. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  76316. ** something that can be converted into a number, we have:
  76317. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  76318. ** cannot be converted to a numeric value.
  76319. */
  76320. double rVal = sqlite3_value_double(argv[0]);
  76321. if( rVal<0 ) rVal = -rVal;
  76322. sqlite3_result_double(context, rVal);
  76323. break;
  76324. }
  76325. }
  76326. }
  76327. /*
  76328. ** Implementation of the substr() function.
  76329. **
  76330. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  76331. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  76332. ** of x. If x is text, then we actually count UTF-8 characters.
  76333. ** If x is a blob, then we count bytes.
  76334. **
  76335. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  76336. **
  76337. ** If p2 is negative, return the p2 characters preceeding p1.
  76338. */
  76339. static void substrFunc(
  76340. sqlite3_context *context,
  76341. int argc,
  76342. sqlite3_value **argv
  76343. ){
  76344. const unsigned char *z;
  76345. const unsigned char *z2;
  76346. int len;
  76347. int p0type;
  76348. i64 p1, p2;
  76349. int negP2 = 0;
  76350. assert( argc==3 || argc==2 );
  76351. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  76352. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  76353. ){
  76354. return;
  76355. }
  76356. p0type = sqlite3_value_type(argv[0]);
  76357. p1 = sqlite3_value_int(argv[1]);
  76358. if( p0type==SQLITE_BLOB ){
  76359. len = sqlite3_value_bytes(argv[0]);
  76360. z = sqlite3_value_blob(argv[0]);
  76361. if( z==0 ) return;
  76362. assert( len==sqlite3_value_bytes(argv[0]) );
  76363. }else{
  76364. z = sqlite3_value_text(argv[0]);
  76365. if( z==0 ) return;
  76366. len = 0;
  76367. if( p1<0 ){
  76368. for(z2=z; *z2; len++){
  76369. SQLITE_SKIP_UTF8(z2);
  76370. }
  76371. }
  76372. }
  76373. if( argc==3 ){
  76374. p2 = sqlite3_value_int(argv[2]);
  76375. if( p2<0 ){
  76376. p2 = -p2;
  76377. negP2 = 1;
  76378. }
  76379. }else{
  76380. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  76381. }
  76382. if( p1<0 ){
  76383. p1 += len;
  76384. if( p1<0 ){
  76385. p2 += p1;
  76386. if( p2<0 ) p2 = 0;
  76387. p1 = 0;
  76388. }
  76389. }else if( p1>0 ){
  76390. p1--;
  76391. }else if( p2>0 ){
  76392. p2--;
  76393. }
  76394. if( negP2 ){
  76395. p1 -= p2;
  76396. if( p1<0 ){
  76397. p2 += p1;
  76398. p1 = 0;
  76399. }
  76400. }
  76401. assert( p1>=0 && p2>=0 );
  76402. if( p0type!=SQLITE_BLOB ){
  76403. while( *z && p1 ){
  76404. SQLITE_SKIP_UTF8(z);
  76405. p1--;
  76406. }
  76407. for(z2=z; *z2 && p2; p2--){
  76408. SQLITE_SKIP_UTF8(z2);
  76409. }
  76410. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  76411. }else{
  76412. if( p1+p2>len ){
  76413. p2 = len-p1;
  76414. if( p2<0 ) p2 = 0;
  76415. }
  76416. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  76417. }
  76418. }
  76419. /*
  76420. ** Implementation of the round() function
  76421. */
  76422. #ifndef SQLITE_OMIT_FLOATING_POINT
  76423. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  76424. int n = 0;
  76425. double r;
  76426. char *zBuf;
  76427. assert( argc==1 || argc==2 );
  76428. if( argc==2 ){
  76429. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  76430. n = sqlite3_value_int(argv[1]);
  76431. if( n>30 ) n = 30;
  76432. if( n<0 ) n = 0;
  76433. }
  76434. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  76435. r = sqlite3_value_double(argv[0]);
  76436. /* If Y==0 and X will fit in a 64-bit int,
  76437. ** handle the rounding directly,
  76438. ** otherwise use printf.
  76439. */
  76440. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  76441. r = (double)((sqlite_int64)(r+0.5));
  76442. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  76443. r = -(double)((sqlite_int64)((-r)+0.5));
  76444. }else{
  76445. zBuf = sqlite3_mprintf("%.*f",n,r);
  76446. if( zBuf==0 ){
  76447. sqlite3_result_error_nomem(context);
  76448. return;
  76449. }
  76450. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  76451. sqlite3_free(zBuf);
  76452. }
  76453. sqlite3_result_double(context, r);
  76454. }
  76455. #endif
  76456. /*
  76457. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  76458. ** allocation fails, call sqlite3_result_error_nomem() to notify
  76459. ** the database handle that malloc() has failed and return NULL.
  76460. ** If nByte is larger than the maximum string or blob length, then
  76461. ** raise an SQLITE_TOOBIG exception and return NULL.
  76462. */
  76463. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  76464. char *z;
  76465. sqlite3 *db = sqlite3_context_db_handle(context);
  76466. assert( nByte>0 );
  76467. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  76468. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  76469. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  76470. sqlite3_result_error_toobig(context);
  76471. z = 0;
  76472. }else{
  76473. z = sqlite3Malloc((int)nByte);
  76474. if( !z ){
  76475. sqlite3_result_error_nomem(context);
  76476. }
  76477. }
  76478. return z;
  76479. }
  76480. /*
  76481. ** Implementation of the upper() and lower() SQL functions.
  76482. */
  76483. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  76484. char *z1;
  76485. const char *z2;
  76486. int i, n;
  76487. UNUSED_PARAMETER(argc);
  76488. z2 = (char*)sqlite3_value_text(argv[0]);
  76489. n = sqlite3_value_bytes(argv[0]);
  76490. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  76491. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  76492. if( z2 ){
  76493. z1 = contextMalloc(context, ((i64)n)+1);
  76494. if( z1 ){
  76495. memcpy(z1, z2, n+1);
  76496. for(i=0; z1[i]; i++){
  76497. z1[i] = (char)sqlite3Toupper(z1[i]);
  76498. }
  76499. sqlite3_result_text(context, z1, -1, sqlite3_free);
  76500. }
  76501. }
  76502. }
  76503. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  76504. u8 *z1;
  76505. const char *z2;
  76506. int i, n;
  76507. UNUSED_PARAMETER(argc);
  76508. z2 = (char*)sqlite3_value_text(argv[0]);
  76509. n = sqlite3_value_bytes(argv[0]);
  76510. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  76511. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  76512. if( z2 ){
  76513. z1 = contextMalloc(context, ((i64)n)+1);
  76514. if( z1 ){
  76515. memcpy(z1, z2, n+1);
  76516. for(i=0; z1[i]; i++){
  76517. z1[i] = sqlite3Tolower(z1[i]);
  76518. }
  76519. sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
  76520. }
  76521. }
  76522. }
  76523. #if 0 /* This function is never used. */
  76524. /*
  76525. ** The COALESCE() and IFNULL() functions used to be implemented as shown
  76526. ** here. But now they are implemented as VDBE code so that unused arguments
  76527. ** do not have to be computed. This legacy implementation is retained as
  76528. ** comment.
  76529. */
  76530. /*
  76531. ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
  76532. ** All three do the same thing. They return the first non-NULL
  76533. ** argument.
  76534. */
  76535. static void ifnullFunc(
  76536. sqlite3_context *context,
  76537. int argc,
  76538. sqlite3_value **argv
  76539. ){
  76540. int i;
  76541. for(i=0; i<argc; i++){
  76542. if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
  76543. sqlite3_result_value(context, argv[i]);
  76544. break;
  76545. }
  76546. }
  76547. }
  76548. #endif /* NOT USED */
  76549. #define ifnullFunc versionFunc /* Substitute function - never called */
  76550. /*
  76551. ** Implementation of random(). Return a random integer.
  76552. */
  76553. static void randomFunc(
  76554. sqlite3_context *context,
  76555. int NotUsed,
  76556. sqlite3_value **NotUsed2
  76557. ){
  76558. sqlite_int64 r;
  76559. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  76560. sqlite3_randomness(sizeof(r), &r);
  76561. if( r<0 ){
  76562. /* We need to prevent a random number of 0x8000000000000000
  76563. ** (or -9223372036854775808) since when you do abs() of that
  76564. ** number of you get the same value back again. To do this
  76565. ** in a way that is testable, mask the sign bit off of negative
  76566. ** values, resulting in a positive value. Then take the
  76567. ** 2s complement of that positive value. The end result can
  76568. ** therefore be no less than -9223372036854775807.
  76569. */
  76570. r = -(r ^ (((sqlite3_int64)1)<<63));
  76571. }
  76572. sqlite3_result_int64(context, r);
  76573. }
  76574. /*
  76575. ** Implementation of randomblob(N). Return a random blob
  76576. ** that is N bytes long.
  76577. */
  76578. static void randomBlob(
  76579. sqlite3_context *context,
  76580. int argc,
  76581. sqlite3_value **argv
  76582. ){
  76583. int n;
  76584. unsigned char *p;
  76585. assert( argc==1 );
  76586. UNUSED_PARAMETER(argc);
  76587. n = sqlite3_value_int(argv[0]);
  76588. if( n<1 ){
  76589. n = 1;
  76590. }
  76591. p = contextMalloc(context, n);
  76592. if( p ){
  76593. sqlite3_randomness(n, p);
  76594. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  76595. }
  76596. }
  76597. /*
  76598. ** Implementation of the last_insert_rowid() SQL function. The return
  76599. ** value is the same as the sqlite3_last_insert_rowid() API function.
  76600. */
  76601. static void last_insert_rowid(
  76602. sqlite3_context *context,
  76603. int NotUsed,
  76604. sqlite3_value **NotUsed2
  76605. ){
  76606. sqlite3 *db = sqlite3_context_db_handle(context);
  76607. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  76608. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  76609. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  76610. ** function. */
  76611. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  76612. }
  76613. /*
  76614. ** Implementation of the changes() SQL function.
  76615. **
  76616. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  76617. ** around the sqlite3_changes() C/C++ function and hence follows the same
  76618. ** rules for counting changes.
  76619. */
  76620. static void changes(
  76621. sqlite3_context *context,
  76622. int NotUsed,
  76623. sqlite3_value **NotUsed2
  76624. ){
  76625. sqlite3 *db = sqlite3_context_db_handle(context);
  76626. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  76627. sqlite3_result_int(context, sqlite3_changes(db));
  76628. }
  76629. /*
  76630. ** Implementation of the total_changes() SQL function. The return value is
  76631. ** the same as the sqlite3_total_changes() API function.
  76632. */
  76633. static void total_changes(
  76634. sqlite3_context *context,
  76635. int NotUsed,
  76636. sqlite3_value **NotUsed2
  76637. ){
  76638. sqlite3 *db = sqlite3_context_db_handle(context);
  76639. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  76640. /* IMP: R-52756-41993 This function is a wrapper around the
  76641. ** sqlite3_total_changes() C/C++ interface. */
  76642. sqlite3_result_int(context, sqlite3_total_changes(db));
  76643. }
  76644. /*
  76645. ** A structure defining how to do GLOB-style comparisons.
  76646. */
  76647. struct compareInfo {
  76648. u8 matchAll;
  76649. u8 matchOne;
  76650. u8 matchSet;
  76651. u8 noCase;
  76652. };
  76653. /*
  76654. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  76655. ** character is exactly one byte in size. Also, all characters are
  76656. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  76657. ** whereas only characters less than 0x80 do in ASCII.
  76658. */
  76659. #if defined(SQLITE_EBCDIC)
  76660. # define sqlite3Utf8Read(A,C) (*(A++))
  76661. # define GlogUpperToLower(A) A = sqlite3UpperToLower[A]
  76662. #else
  76663. # define GlogUpperToLower(A) if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
  76664. #endif
  76665. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  76666. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  76667. ** case. Thus 'a' LIKE 'A' would be true. */
  76668. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  76669. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  76670. ** is case sensitive causing 'a' LIKE 'A' to be false */
  76671. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  76672. /*
  76673. ** Compare two UTF-8 strings for equality where the first string can
  76674. ** potentially be a "glob" expression. Return true (1) if they
  76675. ** are the same and false (0) if they are different.
  76676. **
  76677. ** Globbing rules:
  76678. **
  76679. ** '*' Matches any sequence of zero or more characters.
  76680. **
  76681. ** '?' Matches exactly one character.
  76682. **
  76683. ** [...] Matches one character from the enclosed list of
  76684. ** characters.
  76685. **
  76686. ** [^...] Matches one character not in the enclosed list.
  76687. **
  76688. ** With the [...] and [^...] matching, a ']' character can be included
  76689. ** in the list by making it the first character after '[' or '^'. A
  76690. ** range of characters can be specified using '-'. Example:
  76691. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  76692. ** it the last character in the list.
  76693. **
  76694. ** This routine is usually quick, but can be N**2 in the worst case.
  76695. **
  76696. ** Hints: to match '*' or '?', put them in "[]". Like this:
  76697. **
  76698. ** abc[*]xyz Matches "abc*xyz" only
  76699. */
  76700. static int patternCompare(
  76701. const u8 *zPattern, /* The glob pattern */
  76702. const u8 *zString, /* The string to compare against the glob */
  76703. const struct compareInfo *pInfo, /* Information about how to do the compare */
  76704. const int esc /* The escape character */
  76705. ){
  76706. int c, c2;
  76707. int invert;
  76708. int seen;
  76709. u8 matchOne = pInfo->matchOne;
  76710. u8 matchAll = pInfo->matchAll;
  76711. u8 matchSet = pInfo->matchSet;
  76712. u8 noCase = pInfo->noCase;
  76713. int prevEscape = 0; /* True if the previous character was 'escape' */
  76714. while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
  76715. if( !prevEscape && c==matchAll ){
  76716. while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
  76717. || c == matchOne ){
  76718. if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
  76719. return 0;
  76720. }
  76721. }
  76722. if( c==0 ){
  76723. return 1;
  76724. }else if( c==esc ){
  76725. c = sqlite3Utf8Read(zPattern, &zPattern);
  76726. if( c==0 ){
  76727. return 0;
  76728. }
  76729. }else if( c==matchSet ){
  76730. assert( esc==0 ); /* This is GLOB, not LIKE */
  76731. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  76732. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  76733. SQLITE_SKIP_UTF8(zString);
  76734. }
  76735. return *zString!=0;
  76736. }
  76737. while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
  76738. if( noCase ){
  76739. GlogUpperToLower(c2);
  76740. GlogUpperToLower(c);
  76741. while( c2 != 0 && c2 != c ){
  76742. c2 = sqlite3Utf8Read(zString, &zString);
  76743. GlogUpperToLower(c2);
  76744. }
  76745. }else{
  76746. while( c2 != 0 && c2 != c ){
  76747. c2 = sqlite3Utf8Read(zString, &zString);
  76748. }
  76749. }
  76750. if( c2==0 ) return 0;
  76751. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  76752. }
  76753. return 0;
  76754. }else if( !prevEscape && c==matchOne ){
  76755. if( sqlite3Utf8Read(zString, &zString)==0 ){
  76756. return 0;
  76757. }
  76758. }else if( c==matchSet ){
  76759. int prior_c = 0;
  76760. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  76761. seen = 0;
  76762. invert = 0;
  76763. c = sqlite3Utf8Read(zString, &zString);
  76764. if( c==0 ) return 0;
  76765. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  76766. if( c2=='^' ){
  76767. invert = 1;
  76768. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  76769. }
  76770. if( c2==']' ){
  76771. if( c==']' ) seen = 1;
  76772. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  76773. }
  76774. while( c2 && c2!=']' ){
  76775. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  76776. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  76777. if( c>=prior_c && c<=c2 ) seen = 1;
  76778. prior_c = 0;
  76779. }else{
  76780. if( c==c2 ){
  76781. seen = 1;
  76782. }
  76783. prior_c = c2;
  76784. }
  76785. c2 = sqlite3Utf8Read(zPattern, &zPattern);
  76786. }
  76787. if( c2==0 || (seen ^ invert)==0 ){
  76788. return 0;
  76789. }
  76790. }else if( esc==c && !prevEscape ){
  76791. prevEscape = 1;
  76792. }else{
  76793. c2 = sqlite3Utf8Read(zString, &zString);
  76794. if( noCase ){
  76795. GlogUpperToLower(c);
  76796. GlogUpperToLower(c2);
  76797. }
  76798. if( c!=c2 ){
  76799. return 0;
  76800. }
  76801. prevEscape = 0;
  76802. }
  76803. }
  76804. return *zString==0;
  76805. }
  76806. /*
  76807. ** Count the number of times that the LIKE operator (or GLOB which is
  76808. ** just a variation of LIKE) gets called. This is used for testing
  76809. ** only.
  76810. */
  76811. #ifdef SQLITE_TEST
  76812. SQLITE_API int sqlite3_like_count = 0;
  76813. #endif
  76814. /*
  76815. ** Implementation of the like() SQL function. This function implements
  76816. ** the build-in LIKE operator. The first argument to the function is the
  76817. ** pattern and the second argument is the string. So, the SQL statements:
  76818. **
  76819. ** A LIKE B
  76820. **
  76821. ** is implemented as like(B,A).
  76822. **
  76823. ** This same function (with a different compareInfo structure) computes
  76824. ** the GLOB operator.
  76825. */
  76826. static void likeFunc(
  76827. sqlite3_context *context,
  76828. int argc,
  76829. sqlite3_value **argv
  76830. ){
  76831. const unsigned char *zA, *zB;
  76832. int escape = 0;
  76833. int nPat;
  76834. sqlite3 *db = sqlite3_context_db_handle(context);
  76835. zB = sqlite3_value_text(argv[0]);
  76836. zA = sqlite3_value_text(argv[1]);
  76837. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  76838. ** of deep recursion and N*N behavior in patternCompare().
  76839. */
  76840. nPat = sqlite3_value_bytes(argv[0]);
  76841. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  76842. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  76843. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  76844. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  76845. return;
  76846. }
  76847. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  76848. if( argc==3 ){
  76849. /* The escape character string must consist of a single UTF-8 character.
  76850. ** Otherwise, return an error.
  76851. */
  76852. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  76853. if( zEsc==0 ) return;
  76854. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  76855. sqlite3_result_error(context,
  76856. "ESCAPE expression must be a single character", -1);
  76857. return;
  76858. }
  76859. escape = sqlite3Utf8Read(zEsc, &zEsc);
  76860. }
  76861. if( zA && zB ){
  76862. struct compareInfo *pInfo = sqlite3_user_data(context);
  76863. #ifdef SQLITE_TEST
  76864. sqlite3_like_count++;
  76865. #endif
  76866. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  76867. }
  76868. }
  76869. /*
  76870. ** Implementation of the NULLIF(x,y) function. The result is the first
  76871. ** argument if the arguments are different. The result is NULL if the
  76872. ** arguments are equal to each other.
  76873. */
  76874. static void nullifFunc(
  76875. sqlite3_context *context,
  76876. int NotUsed,
  76877. sqlite3_value **argv
  76878. ){
  76879. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  76880. UNUSED_PARAMETER(NotUsed);
  76881. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  76882. sqlite3_result_value(context, argv[0]);
  76883. }
  76884. }
  76885. /*
  76886. ** Implementation of the sqlite_version() function. The result is the version
  76887. ** of the SQLite library that is running.
  76888. */
  76889. static void versionFunc(
  76890. sqlite3_context *context,
  76891. int NotUsed,
  76892. sqlite3_value **NotUsed2
  76893. ){
  76894. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  76895. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  76896. ** sqlite3_libversion() C-interface. */
  76897. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  76898. }
  76899. /*
  76900. ** Implementation of the sqlite_source_id() function. The result is a string
  76901. ** that identifies the particular version of the source code used to build
  76902. ** SQLite.
  76903. */
  76904. static void sourceidFunc(
  76905. sqlite3_context *context,
  76906. int NotUsed,
  76907. sqlite3_value **NotUsed2
  76908. ){
  76909. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  76910. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  76911. ** sqlite3_sourceid() C interface. */
  76912. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  76913. }
  76914. /*
  76915. ** Implementation of the sqlite_compileoption_used() function.
  76916. ** The result is an integer that identifies if the compiler option
  76917. ** was used to build SQLite.
  76918. */
  76919. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  76920. static void compileoptionusedFunc(
  76921. sqlite3_context *context,
  76922. int argc,
  76923. sqlite3_value **argv
  76924. ){
  76925. const char *zOptName;
  76926. assert( argc==1 );
  76927. UNUSED_PARAMETER(argc);
  76928. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  76929. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  76930. ** function.
  76931. */
  76932. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  76933. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  76934. }
  76935. }
  76936. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  76937. /*
  76938. ** Implementation of the sqlite_compileoption_get() function.
  76939. ** The result is a string that identifies the compiler options
  76940. ** used to build SQLite.
  76941. */
  76942. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  76943. static void compileoptiongetFunc(
  76944. sqlite3_context *context,
  76945. int argc,
  76946. sqlite3_value **argv
  76947. ){
  76948. int n;
  76949. assert( argc==1 );
  76950. UNUSED_PARAMETER(argc);
  76951. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  76952. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  76953. */
  76954. n = sqlite3_value_int(argv[0]);
  76955. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  76956. }
  76957. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  76958. /* Array for converting from half-bytes (nybbles) into ASCII hex
  76959. ** digits. */
  76960. static const char hexdigits[] = {
  76961. '0', '1', '2', '3', '4', '5', '6', '7',
  76962. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  76963. };
  76964. /*
  76965. ** EXPERIMENTAL - This is not an official function. The interface may
  76966. ** change. This function may disappear. Do not write code that depends
  76967. ** on this function.
  76968. **
  76969. ** Implementation of the QUOTE() function. This function takes a single
  76970. ** argument. If the argument is numeric, the return value is the same as
  76971. ** the argument. If the argument is NULL, the return value is the string
  76972. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  76973. ** single-quote escapes.
  76974. */
  76975. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  76976. assert( argc==1 );
  76977. UNUSED_PARAMETER(argc);
  76978. switch( sqlite3_value_type(argv[0]) ){
  76979. case SQLITE_INTEGER:
  76980. case SQLITE_FLOAT: {
  76981. sqlite3_result_value(context, argv[0]);
  76982. break;
  76983. }
  76984. case SQLITE_BLOB: {
  76985. char *zText = 0;
  76986. char const *zBlob = sqlite3_value_blob(argv[0]);
  76987. int nBlob = sqlite3_value_bytes(argv[0]);
  76988. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  76989. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  76990. if( zText ){
  76991. int i;
  76992. for(i=0; i<nBlob; i++){
  76993. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  76994. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  76995. }
  76996. zText[(nBlob*2)+2] = '\'';
  76997. zText[(nBlob*2)+3] = '\0';
  76998. zText[0] = 'X';
  76999. zText[1] = '\'';
  77000. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  77001. sqlite3_free(zText);
  77002. }
  77003. break;
  77004. }
  77005. case SQLITE_TEXT: {
  77006. int i,j;
  77007. u64 n;
  77008. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  77009. char *z;
  77010. if( zArg==0 ) return;
  77011. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  77012. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  77013. if( z ){
  77014. z[0] = '\'';
  77015. for(i=0, j=1; zArg[i]; i++){
  77016. z[j++] = zArg[i];
  77017. if( zArg[i]=='\'' ){
  77018. z[j++] = '\'';
  77019. }
  77020. }
  77021. z[j++] = '\'';
  77022. z[j] = 0;
  77023. sqlite3_result_text(context, z, j, sqlite3_free);
  77024. }
  77025. break;
  77026. }
  77027. default: {
  77028. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  77029. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  77030. break;
  77031. }
  77032. }
  77033. }
  77034. /*
  77035. ** The hex() function. Interpret the argument as a blob. Return
  77036. ** a hexadecimal rendering as text.
  77037. */
  77038. static void hexFunc(
  77039. sqlite3_context *context,
  77040. int argc,
  77041. sqlite3_value **argv
  77042. ){
  77043. int i, n;
  77044. const unsigned char *pBlob;
  77045. char *zHex, *z;
  77046. assert( argc==1 );
  77047. UNUSED_PARAMETER(argc);
  77048. pBlob = sqlite3_value_blob(argv[0]);
  77049. n = sqlite3_value_bytes(argv[0]);
  77050. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  77051. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  77052. if( zHex ){
  77053. for(i=0; i<n; i++, pBlob++){
  77054. unsigned char c = *pBlob;
  77055. *(z++) = hexdigits[(c>>4)&0xf];
  77056. *(z++) = hexdigits[c&0xf];
  77057. }
  77058. *z = 0;
  77059. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  77060. }
  77061. }
  77062. /*
  77063. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  77064. */
  77065. static void zeroblobFunc(
  77066. sqlite3_context *context,
  77067. int argc,
  77068. sqlite3_value **argv
  77069. ){
  77070. i64 n;
  77071. sqlite3 *db = sqlite3_context_db_handle(context);
  77072. assert( argc==1 );
  77073. UNUSED_PARAMETER(argc);
  77074. n = sqlite3_value_int64(argv[0]);
  77075. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  77076. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  77077. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77078. sqlite3_result_error_toobig(context);
  77079. }else{
  77080. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  77081. }
  77082. }
  77083. /*
  77084. ** The replace() function. Three arguments are all strings: call
  77085. ** them A, B, and C. The result is also a string which is derived
  77086. ** from A by replacing every occurance of B with C. The match
  77087. ** must be exact. Collating sequences are not used.
  77088. */
  77089. static void replaceFunc(
  77090. sqlite3_context *context,
  77091. int argc,
  77092. sqlite3_value **argv
  77093. ){
  77094. const unsigned char *zStr; /* The input string A */
  77095. const unsigned char *zPattern; /* The pattern string B */
  77096. const unsigned char *zRep; /* The replacement string C */
  77097. unsigned char *zOut; /* The output */
  77098. int nStr; /* Size of zStr */
  77099. int nPattern; /* Size of zPattern */
  77100. int nRep; /* Size of zRep */
  77101. i64 nOut; /* Maximum size of zOut */
  77102. int loopLimit; /* Last zStr[] that might match zPattern[] */
  77103. int i, j; /* Loop counters */
  77104. assert( argc==3 );
  77105. UNUSED_PARAMETER(argc);
  77106. zStr = sqlite3_value_text(argv[0]);
  77107. if( zStr==0 ) return;
  77108. nStr = sqlite3_value_bytes(argv[0]);
  77109. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  77110. zPattern = sqlite3_value_text(argv[1]);
  77111. if( zPattern==0 ){
  77112. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  77113. || sqlite3_context_db_handle(context)->mallocFailed );
  77114. return;
  77115. }
  77116. if( zPattern[0]==0 ){
  77117. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  77118. sqlite3_result_value(context, argv[0]);
  77119. return;
  77120. }
  77121. nPattern = sqlite3_value_bytes(argv[1]);
  77122. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  77123. zRep = sqlite3_value_text(argv[2]);
  77124. if( zRep==0 ) return;
  77125. nRep = sqlite3_value_bytes(argv[2]);
  77126. assert( zRep==sqlite3_value_text(argv[2]) );
  77127. nOut = nStr + 1;
  77128. assert( nOut<SQLITE_MAX_LENGTH );
  77129. zOut = contextMalloc(context, (i64)nOut);
  77130. if( zOut==0 ){
  77131. return;
  77132. }
  77133. loopLimit = nStr - nPattern;
  77134. for(i=j=0; i<=loopLimit; i++){
  77135. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  77136. zOut[j++] = zStr[i];
  77137. }else{
  77138. u8 *zOld;
  77139. sqlite3 *db = sqlite3_context_db_handle(context);
  77140. nOut += nRep - nPattern;
  77141. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  77142. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  77143. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77144. sqlite3_result_error_toobig(context);
  77145. sqlite3_free(zOut);
  77146. return;
  77147. }
  77148. zOld = zOut;
  77149. zOut = sqlite3_realloc(zOut, (int)nOut);
  77150. if( zOut==0 ){
  77151. sqlite3_result_error_nomem(context);
  77152. sqlite3_free(zOld);
  77153. return;
  77154. }
  77155. memcpy(&zOut[j], zRep, nRep);
  77156. j += nRep;
  77157. i += nPattern-1;
  77158. }
  77159. }
  77160. assert( j+nStr-i+1==nOut );
  77161. memcpy(&zOut[j], &zStr[i], nStr-i);
  77162. j += nStr - i;
  77163. assert( j<=nOut );
  77164. zOut[j] = 0;
  77165. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  77166. }
  77167. /*
  77168. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  77169. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  77170. */
  77171. static void trimFunc(
  77172. sqlite3_context *context,
  77173. int argc,
  77174. sqlite3_value **argv
  77175. ){
  77176. const unsigned char *zIn; /* Input string */
  77177. const unsigned char *zCharSet; /* Set of characters to trim */
  77178. int nIn; /* Number of bytes in input */
  77179. int flags; /* 1: trimleft 2: trimright 3: trim */
  77180. int i; /* Loop counter */
  77181. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  77182. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  77183. int nChar; /* Number of characters in zCharSet */
  77184. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  77185. return;
  77186. }
  77187. zIn = sqlite3_value_text(argv[0]);
  77188. if( zIn==0 ) return;
  77189. nIn = sqlite3_value_bytes(argv[0]);
  77190. assert( zIn==sqlite3_value_text(argv[0]) );
  77191. if( argc==1 ){
  77192. static const unsigned char lenOne[] = { 1 };
  77193. static unsigned char * const azOne[] = { (u8*)" " };
  77194. nChar = 1;
  77195. aLen = (u8*)lenOne;
  77196. azChar = (unsigned char **)azOne;
  77197. zCharSet = 0;
  77198. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  77199. return;
  77200. }else{
  77201. const unsigned char *z;
  77202. for(z=zCharSet, nChar=0; *z; nChar++){
  77203. SQLITE_SKIP_UTF8(z);
  77204. }
  77205. if( nChar>0 ){
  77206. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  77207. if( azChar==0 ){
  77208. return;
  77209. }
  77210. aLen = (unsigned char*)&azChar[nChar];
  77211. for(z=zCharSet, nChar=0; *z; nChar++){
  77212. azChar[nChar] = (unsigned char *)z;
  77213. SQLITE_SKIP_UTF8(z);
  77214. aLen[nChar] = (u8)(z - azChar[nChar]);
  77215. }
  77216. }
  77217. }
  77218. if( nChar>0 ){
  77219. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  77220. if( flags & 1 ){
  77221. while( nIn>0 ){
  77222. int len = 0;
  77223. for(i=0; i<nChar; i++){
  77224. len = aLen[i];
  77225. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  77226. }
  77227. if( i>=nChar ) break;
  77228. zIn += len;
  77229. nIn -= len;
  77230. }
  77231. }
  77232. if( flags & 2 ){
  77233. while( nIn>0 ){
  77234. int len = 0;
  77235. for(i=0; i<nChar; i++){
  77236. len = aLen[i];
  77237. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  77238. }
  77239. if( i>=nChar ) break;
  77240. nIn -= len;
  77241. }
  77242. }
  77243. if( zCharSet ){
  77244. sqlite3_free(azChar);
  77245. }
  77246. }
  77247. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  77248. }
  77249. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  77250. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  77251. ** when SQLite is built.
  77252. */
  77253. #ifdef SQLITE_SOUNDEX
  77254. /*
  77255. ** Compute the soundex encoding of a word.
  77256. **
  77257. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  77258. ** soundex encoding of the string X.
  77259. */
  77260. static void soundexFunc(
  77261. sqlite3_context *context,
  77262. int argc,
  77263. sqlite3_value **argv
  77264. ){
  77265. char zResult[8];
  77266. const u8 *zIn;
  77267. int i, j;
  77268. static const unsigned char iCode[] = {
  77269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  77270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  77271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  77272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  77273. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  77274. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  77275. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  77276. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  77277. };
  77278. assert( argc==1 );
  77279. zIn = (u8*)sqlite3_value_text(argv[0]);
  77280. if( zIn==0 ) zIn = (u8*)"";
  77281. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  77282. if( zIn[i] ){
  77283. u8 prevcode = iCode[zIn[i]&0x7f];
  77284. zResult[0] = sqlite3Toupper(zIn[i]);
  77285. for(j=1; j<4 && zIn[i]; i++){
  77286. int code = iCode[zIn[i]&0x7f];
  77287. if( code>0 ){
  77288. if( code!=prevcode ){
  77289. prevcode = code;
  77290. zResult[j++] = code + '0';
  77291. }
  77292. }else{
  77293. prevcode = 0;
  77294. }
  77295. }
  77296. while( j<4 ){
  77297. zResult[j++] = '0';
  77298. }
  77299. zResult[j] = 0;
  77300. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  77301. }else{
  77302. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  77303. ** is NULL or contains no ASCII alphabetic characters. */
  77304. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  77305. }
  77306. }
  77307. #endif /* SQLITE_SOUNDEX */
  77308. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  77309. /*
  77310. ** A function that loads a shared-library extension then returns NULL.
  77311. */
  77312. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  77313. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  77314. const char *zProc;
  77315. sqlite3 *db = sqlite3_context_db_handle(context);
  77316. char *zErrMsg = 0;
  77317. if( argc==2 ){
  77318. zProc = (const char *)sqlite3_value_text(argv[1]);
  77319. }else{
  77320. zProc = 0;
  77321. }
  77322. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  77323. sqlite3_result_error(context, zErrMsg, -1);
  77324. sqlite3_free(zErrMsg);
  77325. }
  77326. }
  77327. #endif
  77328. /*
  77329. ** An instance of the following structure holds the context of a
  77330. ** sum() or avg() aggregate computation.
  77331. */
  77332. typedef struct SumCtx SumCtx;
  77333. struct SumCtx {
  77334. double rSum; /* Floating point sum */
  77335. i64 iSum; /* Integer sum */
  77336. i64 cnt; /* Number of elements summed */
  77337. u8 overflow; /* True if integer overflow seen */
  77338. u8 approx; /* True if non-integer value was input to the sum */
  77339. };
  77340. /*
  77341. ** Routines used to compute the sum, average, and total.
  77342. **
  77343. ** The SUM() function follows the (broken) SQL standard which means
  77344. ** that it returns NULL if it sums over no inputs. TOTAL returns
  77345. ** 0.0 in that case. In addition, TOTAL always returns a float where
  77346. ** SUM might return an integer if it never encounters a floating point
  77347. ** value. TOTAL never fails, but SUM might through an exception if
  77348. ** it overflows an integer.
  77349. */
  77350. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  77351. SumCtx *p;
  77352. int type;
  77353. assert( argc==1 );
  77354. UNUSED_PARAMETER(argc);
  77355. p = sqlite3_aggregate_context(context, sizeof(*p));
  77356. type = sqlite3_value_numeric_type(argv[0]);
  77357. if( p && type!=SQLITE_NULL ){
  77358. p->cnt++;
  77359. if( type==SQLITE_INTEGER ){
  77360. i64 v = sqlite3_value_int64(argv[0]);
  77361. p->rSum += v;
  77362. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  77363. p->overflow = 1;
  77364. }
  77365. }else{
  77366. p->rSum += sqlite3_value_double(argv[0]);
  77367. p->approx = 1;
  77368. }
  77369. }
  77370. }
  77371. static void sumFinalize(sqlite3_context *context){
  77372. SumCtx *p;
  77373. p = sqlite3_aggregate_context(context, 0);
  77374. if( p && p->cnt>0 ){
  77375. if( p->overflow ){
  77376. sqlite3_result_error(context,"integer overflow",-1);
  77377. }else if( p->approx ){
  77378. sqlite3_result_double(context, p->rSum);
  77379. }else{
  77380. sqlite3_result_int64(context, p->iSum);
  77381. }
  77382. }
  77383. }
  77384. static void avgFinalize(sqlite3_context *context){
  77385. SumCtx *p;
  77386. p = sqlite3_aggregate_context(context, 0);
  77387. if( p && p->cnt>0 ){
  77388. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  77389. }
  77390. }
  77391. static void totalFinalize(sqlite3_context *context){
  77392. SumCtx *p;
  77393. p = sqlite3_aggregate_context(context, 0);
  77394. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  77395. sqlite3_result_double(context, p ? p->rSum : (double)0);
  77396. }
  77397. /*
  77398. ** The following structure keeps track of state information for the
  77399. ** count() aggregate function.
  77400. */
  77401. typedef struct CountCtx CountCtx;
  77402. struct CountCtx {
  77403. i64 n;
  77404. };
  77405. /*
  77406. ** Routines to implement the count() aggregate function.
  77407. */
  77408. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  77409. CountCtx *p;
  77410. p = sqlite3_aggregate_context(context, sizeof(*p));
  77411. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  77412. p->n++;
  77413. }
  77414. #ifndef SQLITE_OMIT_DEPRECATED
  77415. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  77416. ** sure it still operates correctly, verify that its count agrees with our
  77417. ** internal count when using count(*) and when the total count can be
  77418. ** expressed as a 32-bit integer. */
  77419. assert( argc==1 || p==0 || p->n>0x7fffffff
  77420. || p->n==sqlite3_aggregate_count(context) );
  77421. #endif
  77422. }
  77423. static void countFinalize(sqlite3_context *context){
  77424. CountCtx *p;
  77425. p = sqlite3_aggregate_context(context, 0);
  77426. sqlite3_result_int64(context, p ? p->n : 0);
  77427. }
  77428. /*
  77429. ** Routines to implement min() and max() aggregate functions.
  77430. */
  77431. static void minmaxStep(
  77432. sqlite3_context *context,
  77433. int NotUsed,
  77434. sqlite3_value **argv
  77435. ){
  77436. Mem *pArg = (Mem *)argv[0];
  77437. Mem *pBest;
  77438. UNUSED_PARAMETER(NotUsed);
  77439. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  77440. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  77441. if( !pBest ) return;
  77442. if( pBest->flags ){
  77443. int max;
  77444. int cmp;
  77445. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  77446. /* This step function is used for both the min() and max() aggregates,
  77447. ** the only difference between the two being that the sense of the
  77448. ** comparison is inverted. For the max() aggregate, the
  77449. ** sqlite3_user_data() function returns (void *)-1. For min() it
  77450. ** returns (void *)db, where db is the sqlite3* database pointer.
  77451. ** Therefore the next statement sets variable 'max' to 1 for the max()
  77452. ** aggregate, or 0 for min().
  77453. */
  77454. max = sqlite3_user_data(context)!=0;
  77455. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  77456. if( (max && cmp<0) || (!max && cmp>0) ){
  77457. sqlite3VdbeMemCopy(pBest, pArg);
  77458. }
  77459. }else{
  77460. sqlite3VdbeMemCopy(pBest, pArg);
  77461. }
  77462. }
  77463. static void minMaxFinalize(sqlite3_context *context){
  77464. sqlite3_value *pRes;
  77465. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  77466. if( pRes ){
  77467. if( ALWAYS(pRes->flags) ){
  77468. sqlite3_result_value(context, pRes);
  77469. }
  77470. sqlite3VdbeMemRelease(pRes);
  77471. }
  77472. }
  77473. /*
  77474. ** group_concat(EXPR, ?SEPARATOR?)
  77475. */
  77476. static void groupConcatStep(
  77477. sqlite3_context *context,
  77478. int argc,
  77479. sqlite3_value **argv
  77480. ){
  77481. const char *zVal;
  77482. StrAccum *pAccum;
  77483. const char *zSep;
  77484. int nVal, nSep;
  77485. assert( argc==1 || argc==2 );
  77486. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  77487. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  77488. if( pAccum ){
  77489. sqlite3 *db = sqlite3_context_db_handle(context);
  77490. int firstTerm = pAccum->useMalloc==0;
  77491. pAccum->useMalloc = 2;
  77492. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  77493. if( !firstTerm ){
  77494. if( argc==2 ){
  77495. zSep = (char*)sqlite3_value_text(argv[1]);
  77496. nSep = sqlite3_value_bytes(argv[1]);
  77497. }else{
  77498. zSep = ",";
  77499. nSep = 1;
  77500. }
  77501. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  77502. }
  77503. zVal = (char*)sqlite3_value_text(argv[0]);
  77504. nVal = sqlite3_value_bytes(argv[0]);
  77505. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  77506. }
  77507. }
  77508. static void groupConcatFinalize(sqlite3_context *context){
  77509. StrAccum *pAccum;
  77510. pAccum = sqlite3_aggregate_context(context, 0);
  77511. if( pAccum ){
  77512. if( pAccum->tooBig ){
  77513. sqlite3_result_error_toobig(context);
  77514. }else if( pAccum->mallocFailed ){
  77515. sqlite3_result_error_nomem(context);
  77516. }else{
  77517. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  77518. sqlite3_free);
  77519. }
  77520. }
  77521. }
  77522. /*
  77523. ** This routine does per-connection function registration. Most
  77524. ** of the built-in functions above are part of the global function set.
  77525. ** This routine only deals with those that are not global.
  77526. */
  77527. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  77528. int rc = sqlite3_overload_function(db, "MATCH", 2);
  77529. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  77530. if( rc==SQLITE_NOMEM ){
  77531. db->mallocFailed = 1;
  77532. }
  77533. }
  77534. /*
  77535. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  77536. */
  77537. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  77538. FuncDef *pDef;
  77539. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  77540. 2, SQLITE_UTF8, 0);
  77541. if( ALWAYS(pDef) ){
  77542. pDef->flags = flagVal;
  77543. }
  77544. }
  77545. /*
  77546. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  77547. ** parameter determines whether or not the LIKE operator is case
  77548. ** sensitive. GLOB is always case sensitive.
  77549. */
  77550. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  77551. struct compareInfo *pInfo;
  77552. if( caseSensitive ){
  77553. pInfo = (struct compareInfo*)&likeInfoAlt;
  77554. }else{
  77555. pInfo = (struct compareInfo*)&likeInfoNorm;
  77556. }
  77557. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  77558. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  77559. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  77560. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  77561. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  77562. setLikeOptFlag(db, "like",
  77563. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  77564. }
  77565. /*
  77566. ** pExpr points to an expression which implements a function. If
  77567. ** it is appropriate to apply the LIKE optimization to that function
  77568. ** then set aWc[0] through aWc[2] to the wildcard characters and
  77569. ** return TRUE. If the function is not a LIKE-style function then
  77570. ** return FALSE.
  77571. */
  77572. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  77573. FuncDef *pDef;
  77574. if( pExpr->op!=TK_FUNCTION
  77575. || !pExpr->x.pList
  77576. || pExpr->x.pList->nExpr!=2
  77577. ){
  77578. return 0;
  77579. }
  77580. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77581. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  77582. sqlite3Strlen30(pExpr->u.zToken),
  77583. 2, SQLITE_UTF8, 0);
  77584. if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
  77585. return 0;
  77586. }
  77587. /* The memcpy() statement assumes that the wildcard characters are
  77588. ** the first three statements in the compareInfo structure. The
  77589. ** asserts() that follow verify that assumption
  77590. */
  77591. memcpy(aWc, pDef->pUserData, 3);
  77592. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  77593. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  77594. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  77595. *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
  77596. return 1;
  77597. }
  77598. /*
  77599. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  77600. ** to the global function hash table. This occurs at start-time (as
  77601. ** a consequence of calling sqlite3_initialize()).
  77602. **
  77603. ** After this routine runs
  77604. */
  77605. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  77606. /*
  77607. ** The following array holds FuncDef structures for all of the functions
  77608. ** defined in this file.
  77609. **
  77610. ** The array cannot be constant since changes are made to the
  77611. ** FuncDef.pHash elements at start-time. The elements of this array
  77612. ** are read-only after initialization is complete.
  77613. */
  77614. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  77615. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  77616. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  77617. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  77618. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  77619. FUNCTION(trim, 1, 3, 0, trimFunc ),
  77620. FUNCTION(trim, 2, 3, 0, trimFunc ),
  77621. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  77622. FUNCTION(min, 0, 0, 1, 0 ),
  77623. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  77624. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  77625. FUNCTION(max, 0, 1, 1, 0 ),
  77626. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  77627. FUNCTION(typeof, 1, 0, 0, typeofFunc ),
  77628. FUNCTION(length, 1, 0, 0, lengthFunc ),
  77629. FUNCTION(substr, 2, 0, 0, substrFunc ),
  77630. FUNCTION(substr, 3, 0, 0, substrFunc ),
  77631. FUNCTION(abs, 1, 0, 0, absFunc ),
  77632. #ifndef SQLITE_OMIT_FLOATING_POINT
  77633. FUNCTION(round, 1, 0, 0, roundFunc ),
  77634. FUNCTION(round, 2, 0, 0, roundFunc ),
  77635. #endif
  77636. FUNCTION(upper, 1, 0, 0, upperFunc ),
  77637. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  77638. FUNCTION(coalesce, 1, 0, 0, 0 ),
  77639. FUNCTION(coalesce, 0, 0, 0, 0 ),
  77640. /* FUNCTION(coalesce, -1, 0, 0, ifnullFunc ), */
  77641. {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
  77642. FUNCTION(hex, 1, 0, 0, hexFunc ),
  77643. /* FUNCTION(ifnull, 2, 0, 0, ifnullFunc ), */
  77644. {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
  77645. FUNCTION(random, 0, 0, 0, randomFunc ),
  77646. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  77647. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  77648. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  77649. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  77650. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  77651. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  77652. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  77653. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  77654. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  77655. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  77656. FUNCTION(changes, 0, 0, 0, changes ),
  77657. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  77658. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  77659. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  77660. #ifdef SQLITE_SOUNDEX
  77661. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  77662. #endif
  77663. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  77664. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  77665. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  77666. #endif
  77667. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  77668. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  77669. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  77670. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  77671. {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
  77672. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  77673. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  77674. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  77675. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  77676. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  77677. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  77678. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  77679. #else
  77680. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  77681. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  77682. #endif
  77683. };
  77684. int i;
  77685. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  77686. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  77687. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  77688. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  77689. }
  77690. sqlite3RegisterDateTimeFunctions();
  77691. #ifndef SQLITE_OMIT_ALTERTABLE
  77692. sqlite3AlterFunctions();
  77693. #endif
  77694. }
  77695. /************** End of func.c ************************************************/
  77696. /************** Begin file fkey.c ********************************************/
  77697. /*
  77698. **
  77699. ** The author disclaims copyright to this source code. In place of
  77700. ** a legal notice, here is a blessing:
  77701. **
  77702. ** May you do good and not evil.
  77703. ** May you find forgiveness for yourself and forgive others.
  77704. ** May you share freely, never taking more than you give.
  77705. **
  77706. *************************************************************************
  77707. ** This file contains code used by the compiler to add foreign key
  77708. ** support to compiled SQL statements.
  77709. */
  77710. #ifndef SQLITE_OMIT_FOREIGN_KEY
  77711. #ifndef SQLITE_OMIT_TRIGGER
  77712. /*
  77713. ** Deferred and Immediate FKs
  77714. ** --------------------------
  77715. **
  77716. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  77717. ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
  77718. ** is returned and the current statement transaction rolled back. If a
  77719. ** deferred foreign key constraint is violated, no action is taken
  77720. ** immediately. However if the application attempts to commit the
  77721. ** transaction before fixing the constraint violation, the attempt fails.
  77722. **
  77723. ** Deferred constraints are implemented using a simple counter associated
  77724. ** with the database handle. The counter is set to zero each time a
  77725. ** database transaction is opened. Each time a statement is executed
  77726. ** that causes a foreign key violation, the counter is incremented. Each
  77727. ** time a statement is executed that removes an existing violation from
  77728. ** the database, the counter is decremented. When the transaction is
  77729. ** committed, the commit fails if the current value of the counter is
  77730. ** greater than zero. This scheme has two big drawbacks:
  77731. **
  77732. ** * When a commit fails due to a deferred foreign key constraint,
  77733. ** there is no way to tell which foreign constraint is not satisfied,
  77734. ** or which row it is not satisfied for.
  77735. **
  77736. ** * If the database contains foreign key violations when the
  77737. ** transaction is opened, this may cause the mechanism to malfunction.
  77738. **
  77739. ** Despite these problems, this approach is adopted as it seems simpler
  77740. ** than the alternatives.
  77741. **
  77742. ** INSERT operations:
  77743. **
  77744. ** I.1) For each FK for which the table is the child table, search
  77745. ** the parent table for a match. If none is found increment the
  77746. ** constraint counter.
  77747. **
  77748. ** I.2) For each FK for which the table is the parent table,
  77749. ** search the child table for rows that correspond to the new
  77750. ** row in the parent table. Decrement the counter for each row
  77751. ** found (as the constraint is now satisfied).
  77752. **
  77753. ** DELETE operations:
  77754. **
  77755. ** D.1) For each FK for which the table is the child table,
  77756. ** search the parent table for a row that corresponds to the
  77757. ** deleted row in the child table. If such a row is not found,
  77758. ** decrement the counter.
  77759. **
  77760. ** D.2) For each FK for which the table is the parent table, search
  77761. ** the child table for rows that correspond to the deleted row
  77762. ** in the parent table. For each found increment the counter.
  77763. **
  77764. ** UPDATE operations:
  77765. **
  77766. ** An UPDATE command requires that all 4 steps above are taken, but only
  77767. ** for FK constraints for which the affected columns are actually
  77768. ** modified (values must be compared at runtime).
  77769. **
  77770. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  77771. ** This simplifies the implementation a bit.
  77772. **
  77773. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  77774. ** resolution is considered to delete rows before the new row is inserted.
  77775. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  77776. ** is thrown, even if the FK constraint would be satisfied after the new
  77777. ** row is inserted.
  77778. **
  77779. ** Immediate constraints are usually handled similarly. The only difference
  77780. ** is that the counter used is stored as part of each individual statement
  77781. ** object (struct Vdbe). If, after the statement has run, its immediate
  77782. ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
  77783. ** and the statement transaction is rolled back. An exception is an INSERT
  77784. ** statement that inserts a single row only (no triggers). In this case,
  77785. ** instead of using a counter, an exception is thrown immediately if the
  77786. ** INSERT violates a foreign key constraint. This is necessary as such
  77787. ** an INSERT does not open a statement transaction.
  77788. **
  77789. ** TODO: How should dropping a table be handled? How should renaming a
  77790. ** table be handled?
  77791. **
  77792. **
  77793. ** Query API Notes
  77794. ** ---------------
  77795. **
  77796. ** Before coding an UPDATE or DELETE row operation, the code-generator
  77797. ** for those two operations needs to know whether or not the operation
  77798. ** requires any FK processing and, if so, which columns of the original
  77799. ** row are required by the FK processing VDBE code (i.e. if FKs were
  77800. ** implemented using triggers, which of the old.* columns would be
  77801. ** accessed). No information is required by the code-generator before
  77802. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  77803. ** generation code to query for this information are:
  77804. **
  77805. ** sqlite3FkRequired() - Test to see if FK processing is required.
  77806. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  77807. **
  77808. **
  77809. ** Externally accessible module functions
  77810. ** --------------------------------------
  77811. **
  77812. ** sqlite3FkCheck() - Check for foreign key violations.
  77813. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  77814. ** sqlite3FkDelete() - Delete an FKey structure.
  77815. */
  77816. /*
  77817. ** VDBE Calling Convention
  77818. ** -----------------------
  77819. **
  77820. ** Example:
  77821. **
  77822. ** For the following INSERT statement:
  77823. **
  77824. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  77825. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  77826. **
  77827. ** Register (x): 2 (type integer)
  77828. ** Register (x+1): 1 (type integer)
  77829. ** Register (x+2): NULL (type NULL)
  77830. ** Register (x+3): 3.1 (type real)
  77831. */
  77832. /*
  77833. ** A foreign key constraint requires that the key columns in the parent
  77834. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  77835. ** Given that pParent is the parent table for foreign key constraint pFKey,
  77836. ** search the schema a unique index on the parent key columns.
  77837. **
  77838. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  77839. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  77840. ** is set to point to the unique index.
  77841. **
  77842. ** If the parent key consists of a single column (the foreign key constraint
  77843. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  77844. ** Otherwise, it is set to point to an allocated array of size N, where
  77845. ** N is the number of columns in the parent key. The first element of the
  77846. ** array is the index of the child table column that is mapped by the FK
  77847. ** constraint to the parent table column stored in the left-most column
  77848. ** of index *ppIdx. The second element of the array is the index of the
  77849. ** child table column that corresponds to the second left-most column of
  77850. ** *ppIdx, and so on.
  77851. **
  77852. ** If the required index cannot be found, either because:
  77853. **
  77854. ** 1) The named parent key columns do not exist, or
  77855. **
  77856. ** 2) The named parent key columns do exist, but are not subject to a
  77857. ** UNIQUE or PRIMARY KEY constraint, or
  77858. **
  77859. ** 3) No parent key columns were provided explicitly as part of the
  77860. ** foreign key definition, and the parent table does not have a
  77861. ** PRIMARY KEY, or
  77862. **
  77863. ** 4) No parent key columns were provided explicitly as part of the
  77864. ** foreign key definition, and the PRIMARY KEY of the parent table
  77865. ** consists of a a different number of columns to the child key in
  77866. ** the child table.
  77867. **
  77868. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  77869. ** into pParse. If an OOM error occurs, non-zero is returned and the
  77870. ** pParse->db->mallocFailed flag is set.
  77871. */
  77872. static int locateFkeyIndex(
  77873. Parse *pParse, /* Parse context to store any error in */
  77874. Table *pParent, /* Parent table of FK constraint pFKey */
  77875. FKey *pFKey, /* Foreign key to find index for */
  77876. Index **ppIdx, /* OUT: Unique index on parent table */
  77877. int **paiCol /* OUT: Map of index columns in pFKey */
  77878. ){
  77879. Index *pIdx = 0; /* Value to return via *ppIdx */
  77880. int *aiCol = 0; /* Value to return via *paiCol */
  77881. int nCol = pFKey->nCol; /* Number of columns in parent key */
  77882. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  77883. /* The caller is responsible for zeroing output parameters. */
  77884. assert( ppIdx && *ppIdx==0 );
  77885. assert( !paiCol || *paiCol==0 );
  77886. assert( pParse );
  77887. /* If this is a non-composite (single column) foreign key, check if it
  77888. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  77889. ** and *paiCol set to zero and return early.
  77890. **
  77891. ** Otherwise, for a composite foreign key (more than one column), allocate
  77892. ** space for the aiCol array (returned via output parameter *paiCol).
  77893. ** Non-composite foreign keys do not require the aiCol array.
  77894. */
  77895. if( nCol==1 ){
  77896. /* The FK maps to the IPK if any of the following are true:
  77897. **
  77898. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  77899. ** mapped to the primary key of table pParent, or
  77900. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  77901. ** PRIMARY KEY.
  77902. */
  77903. if( pParent->iPKey>=0 ){
  77904. if( !zKey ) return 0;
  77905. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  77906. }
  77907. }else if( paiCol ){
  77908. assert( nCol>1 );
  77909. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  77910. if( !aiCol ) return 1;
  77911. *paiCol = aiCol;
  77912. }
  77913. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  77914. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  77915. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  77916. ** of columns. If each indexed column corresponds to a foreign key
  77917. ** column of pFKey, then this index is a winner. */
  77918. if( zKey==0 ){
  77919. /* If zKey is NULL, then this foreign key is implicitly mapped to
  77920. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  77921. ** identified by the test (Index.autoIndex==2). */
  77922. if( pIdx->autoIndex==2 ){
  77923. if( aiCol ){
  77924. int i;
  77925. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  77926. }
  77927. break;
  77928. }
  77929. }else{
  77930. /* If zKey is non-NULL, then this foreign key was declared to
  77931. ** map to an explicit list of columns in table pParent. Check if this
  77932. ** index matches those columns. Also, check that the index uses
  77933. ** the default collation sequences for each column. */
  77934. int i, j;
  77935. for(i=0; i<nCol; i++){
  77936. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  77937. char *zDfltColl; /* Def. collation for column */
  77938. char *zIdxCol; /* Name of indexed column */
  77939. /* If the index uses a collation sequence that is different from
  77940. ** the default collation sequence for the column, this index is
  77941. ** unusable. Bail out early in this case. */
  77942. zDfltColl = pParent->aCol[iCol].zColl;
  77943. if( !zDfltColl ){
  77944. zDfltColl = "BINARY";
  77945. }
  77946. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  77947. zIdxCol = pParent->aCol[iCol].zName;
  77948. for(j=0; j<nCol; j++){
  77949. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  77950. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  77951. break;
  77952. }
  77953. }
  77954. if( j==nCol ) break;
  77955. }
  77956. if( i==nCol ) break; /* pIdx is usable */
  77957. }
  77958. }
  77959. }
  77960. if( !pIdx ){
  77961. if( !pParse->disableTriggers ){
  77962. sqlite3ErrorMsg(pParse, "foreign key mismatch");
  77963. }
  77964. sqlite3DbFree(pParse->db, aiCol);
  77965. return 1;
  77966. }
  77967. *ppIdx = pIdx;
  77968. return 0;
  77969. }
  77970. /*
  77971. ** This function is called when a row is inserted into or deleted from the
  77972. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  77973. ** on the child table of pFKey, this function is invoked twice for each row
  77974. ** affected - once to "delete" the old row, and then again to "insert" the
  77975. ** new row.
  77976. **
  77977. ** Each time it is called, this function generates VDBE code to locate the
  77978. ** row in the parent table that corresponds to the row being inserted into
  77979. ** or deleted from the child table. If the parent row can be found, no
  77980. ** special action is taken. Otherwise, if the parent row can *not* be
  77981. ** found in the parent table:
  77982. **
  77983. ** Operation | FK type | Action taken
  77984. ** --------------------------------------------------------------------------
  77985. ** INSERT immediate Increment the "immediate constraint counter".
  77986. **
  77987. ** DELETE immediate Decrement the "immediate constraint counter".
  77988. **
  77989. ** INSERT deferred Increment the "deferred constraint counter".
  77990. **
  77991. ** DELETE deferred Decrement the "deferred constraint counter".
  77992. **
  77993. ** These operations are identified in the comment at the top of this file
  77994. ** (fkey.c) as "I.1" and "D.1".
  77995. */
  77996. static void fkLookupParent(
  77997. Parse *pParse, /* Parse context */
  77998. int iDb, /* Index of database housing pTab */
  77999. Table *pTab, /* Parent table of FK pFKey */
  78000. Index *pIdx, /* Unique index on parent key columns in pTab */
  78001. FKey *pFKey, /* Foreign key constraint */
  78002. int *aiCol, /* Map from parent key columns to child table columns */
  78003. int regData, /* Address of array containing child table row */
  78004. int nIncr, /* Increment constraint counter by this */
  78005. int isIgnore /* If true, pretend pTab contains all NULL values */
  78006. ){
  78007. int i; /* Iterator variable */
  78008. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  78009. int iCur = pParse->nTab - 1; /* Cursor number to use */
  78010. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  78011. /* If nIncr is less than zero, then check at runtime if there are any
  78012. ** outstanding constraints to resolve. If there are not, there is no need
  78013. ** to check if deleting this row resolves any outstanding violations.
  78014. **
  78015. ** Check if any of the key columns in the child table row are NULL. If
  78016. ** any are, then the constraint is considered satisfied. No need to
  78017. ** search for a matching row in the parent table. */
  78018. if( nIncr<0 ){
  78019. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  78020. }
  78021. for(i=0; i<pFKey->nCol; i++){
  78022. int iReg = aiCol[i] + regData + 1;
  78023. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  78024. }
  78025. if( isIgnore==0 ){
  78026. if( pIdx==0 ){
  78027. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  78028. ** column of the parent table (table pTab). */
  78029. int iMustBeInt; /* Address of MustBeInt instruction */
  78030. int regTemp = sqlite3GetTempReg(pParse);
  78031. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  78032. ** apply the affinity of the parent key). If this fails, then there
  78033. ** is no matching parent key. Before using MustBeInt, make a copy of
  78034. ** the value. Otherwise, the value inserted into the child key column
  78035. ** will have INTEGER affinity applied to it, which may not be correct. */
  78036. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  78037. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  78038. /* If the parent table is the same as the child table, and we are about
  78039. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  78040. ** then check if the row being inserted matches itself. If so, do not
  78041. ** increment the constraint-counter. */
  78042. if( pTab==pFKey->pFrom && nIncr==1 ){
  78043. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  78044. }
  78045. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  78046. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  78047. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  78048. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  78049. sqlite3VdbeJumpHere(v, iMustBeInt);
  78050. sqlite3ReleaseTempReg(pParse, regTemp);
  78051. }else{
  78052. int nCol = pFKey->nCol;
  78053. int regTemp = sqlite3GetTempRange(pParse, nCol);
  78054. int regRec = sqlite3GetTempReg(pParse);
  78055. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  78056. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  78057. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  78058. for(i=0; i<nCol; i++){
  78059. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  78060. }
  78061. /* If the parent table is the same as the child table, and we are about
  78062. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  78063. ** then check if the row being inserted matches itself. If so, do not
  78064. ** increment the constraint-counter. */
  78065. if( pTab==pFKey->pFrom && nIncr==1 ){
  78066. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  78067. for(i=0; i<nCol; i++){
  78068. int iChild = aiCol[i]+1+regData;
  78069. int iParent = pIdx->aiColumn[i]+1+regData;
  78070. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  78071. }
  78072. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  78073. }
  78074. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  78075. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  78076. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  78077. sqlite3ReleaseTempReg(pParse, regRec);
  78078. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  78079. }
  78080. }
  78081. if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
  78082. /* Special case: If this is an INSERT statement that will insert exactly
  78083. ** one row into the table, raise a constraint immediately instead of
  78084. ** incrementing a counter. This is necessary as the VM code is being
  78085. ** generated for will not open a statement transaction. */
  78086. assert( nIncr==1 );
  78087. sqlite3HaltConstraint(
  78088. pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
  78089. );
  78090. }else{
  78091. if( nIncr>0 && pFKey->isDeferred==0 ){
  78092. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  78093. }
  78094. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  78095. }
  78096. sqlite3VdbeResolveLabel(v, iOk);
  78097. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  78098. }
  78099. /*
  78100. ** This function is called to generate code executed when a row is deleted
  78101. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  78102. ** deferred, when a row is inserted into the same table. When generating
  78103. ** code for an SQL UPDATE operation, this function may be called twice -
  78104. ** once to "delete" the old row and once to "insert" the new row.
  78105. **
  78106. ** The code generated by this function scans through the rows in the child
  78107. ** table that correspond to the parent table row being deleted or inserted.
  78108. ** For each child row found, one of the following actions is taken:
  78109. **
  78110. ** Operation | FK type | Action taken
  78111. ** --------------------------------------------------------------------------
  78112. ** DELETE immediate Increment the "immediate constraint counter".
  78113. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  78114. ** throw a "foreign key constraint failed" exception.
  78115. **
  78116. ** INSERT immediate Decrement the "immediate constraint counter".
  78117. **
  78118. ** DELETE deferred Increment the "deferred constraint counter".
  78119. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  78120. ** throw a "foreign key constraint failed" exception.
  78121. **
  78122. ** INSERT deferred Decrement the "deferred constraint counter".
  78123. **
  78124. ** These operations are identified in the comment at the top of this file
  78125. ** (fkey.c) as "I.2" and "D.2".
  78126. */
  78127. static void fkScanChildren(
  78128. Parse *pParse, /* Parse context */
  78129. SrcList *pSrc, /* SrcList containing the table to scan */
  78130. Table *pTab,
  78131. Index *pIdx, /* Foreign key index */
  78132. FKey *pFKey, /* Foreign key relationship */
  78133. int *aiCol, /* Map from pIdx cols to child table cols */
  78134. int regData, /* Referenced table data starts here */
  78135. int nIncr /* Amount to increment deferred counter by */
  78136. ){
  78137. sqlite3 *db = pParse->db; /* Database handle */
  78138. int i; /* Iterator variable */
  78139. Expr *pWhere = 0; /* WHERE clause to scan with */
  78140. NameContext sNameContext; /* Context used to resolve WHERE clause */
  78141. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  78142. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  78143. Vdbe *v = sqlite3GetVdbe(pParse);
  78144. assert( !pIdx || pIdx->pTable==pTab );
  78145. if( nIncr<0 ){
  78146. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  78147. }
  78148. /* Create an Expr object representing an SQL expression like:
  78149. **
  78150. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  78151. **
  78152. ** The collation sequence used for the comparison should be that of
  78153. ** the parent key columns. The affinity of the parent key column should
  78154. ** be applied to each child key value before the comparison takes place.
  78155. */
  78156. for(i=0; i<pFKey->nCol; i++){
  78157. Expr *pLeft; /* Value from parent table row */
  78158. Expr *pRight; /* Column ref to child table */
  78159. Expr *pEq; /* Expression (pLeft = pRight) */
  78160. int iCol; /* Index of column in child table */
  78161. const char *zCol; /* Name of column in child table */
  78162. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  78163. if( pLeft ){
  78164. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  78165. ** expression to the parent key column defaults. */
  78166. if( pIdx ){
  78167. Column *pCol;
  78168. iCol = pIdx->aiColumn[i];
  78169. pCol = &pTab->aCol[iCol];
  78170. if( pTab->iPKey==iCol ) iCol = -1;
  78171. pLeft->iTable = regData+iCol+1;
  78172. pLeft->affinity = pCol->affinity;
  78173. pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
  78174. }else{
  78175. pLeft->iTable = regData;
  78176. pLeft->affinity = SQLITE_AFF_INTEGER;
  78177. }
  78178. }
  78179. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  78180. assert( iCol>=0 );
  78181. zCol = pFKey->pFrom->aCol[iCol].zName;
  78182. pRight = sqlite3Expr(db, TK_ID, zCol);
  78183. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  78184. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  78185. }
  78186. /* If the child table is the same as the parent table, and this scan
  78187. ** is taking place as part of a DELETE operation (operation D.2), omit the
  78188. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  78189. ** clause, where $rowid is the rowid of the row being deleted. */
  78190. if( pTab==pFKey->pFrom && nIncr>0 ){
  78191. Expr *pEq; /* Expression (pLeft = pRight) */
  78192. Expr *pLeft; /* Value from parent table row */
  78193. Expr *pRight; /* Column ref to child table */
  78194. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  78195. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  78196. if( pLeft && pRight ){
  78197. pLeft->iTable = regData;
  78198. pLeft->affinity = SQLITE_AFF_INTEGER;
  78199. pRight->iTable = pSrc->a[0].iCursor;
  78200. pRight->iColumn = -1;
  78201. }
  78202. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  78203. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  78204. }
  78205. /* Resolve the references in the WHERE clause. */
  78206. memset(&sNameContext, 0, sizeof(NameContext));
  78207. sNameContext.pSrcList = pSrc;
  78208. sNameContext.pParse = pParse;
  78209. sqlite3ResolveExprNames(&sNameContext, pWhere);
  78210. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  78211. ** clause. If the constraint is not deferred, throw an exception for
  78212. ** each row found. Otherwise, for deferred constraints, increment the
  78213. ** deferred constraint counter by nIncr for each row selected. */
  78214. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
  78215. if( nIncr>0 && pFKey->isDeferred==0 ){
  78216. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  78217. }
  78218. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  78219. if( pWInfo ){
  78220. sqlite3WhereEnd(pWInfo);
  78221. }
  78222. /* Clean up the WHERE clause constructed above. */
  78223. sqlite3ExprDelete(db, pWhere);
  78224. if( iFkIfZero ){
  78225. sqlite3VdbeJumpHere(v, iFkIfZero);
  78226. }
  78227. }
  78228. /*
  78229. ** This function returns a pointer to the head of a linked list of FK
  78230. ** constraints for which table pTab is the parent table. For example,
  78231. ** given the following schema:
  78232. **
  78233. ** CREATE TABLE t1(a PRIMARY KEY);
  78234. ** CREATE TABLE t2(b REFERENCES t1(a);
  78235. **
  78236. ** Calling this function with table "t1" as an argument returns a pointer
  78237. ** to the FKey structure representing the foreign key constraint on table
  78238. ** "t2". Calling this function with "t2" as the argument would return a
  78239. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  78240. ** table).
  78241. */
  78242. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  78243. int nName = sqlite3Strlen30(pTab->zName);
  78244. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  78245. }
  78246. /*
  78247. ** The second argument is a Trigger structure allocated by the
  78248. ** fkActionTrigger() routine. This function deletes the Trigger structure
  78249. ** and all of its sub-components.
  78250. **
  78251. ** The Trigger structure or any of its sub-components may be allocated from
  78252. ** the lookaside buffer belonging to database handle dbMem.
  78253. */
  78254. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  78255. if( p ){
  78256. TriggerStep *pStep = p->step_list;
  78257. sqlite3ExprDelete(dbMem, pStep->pWhere);
  78258. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  78259. sqlite3SelectDelete(dbMem, pStep->pSelect);
  78260. sqlite3ExprDelete(dbMem, p->pWhen);
  78261. sqlite3DbFree(dbMem, p);
  78262. }
  78263. }
  78264. /*
  78265. ** This function is called to generate code that runs when table pTab is
  78266. ** being dropped from the database. The SrcList passed as the second argument
  78267. ** to this function contains a single entry guaranteed to resolve to
  78268. ** table pTab.
  78269. **
  78270. ** Normally, no code is required. However, if either
  78271. **
  78272. ** (a) The table is the parent table of a FK constraint, or
  78273. ** (b) The table is the child table of a deferred FK constraint and it is
  78274. ** determined at runtime that there are outstanding deferred FK
  78275. ** constraint violations in the database,
  78276. **
  78277. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  78278. ** the table from the database. Triggers are disabled while running this
  78279. ** DELETE, but foreign key actions are not.
  78280. */
  78281. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  78282. sqlite3 *db = pParse->db;
  78283. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  78284. int iSkip = 0;
  78285. Vdbe *v = sqlite3GetVdbe(pParse);
  78286. assert( v ); /* VDBE has already been allocated */
  78287. if( sqlite3FkReferences(pTab)==0 ){
  78288. /* Search for a deferred foreign key constraint for which this table
  78289. ** is the child table. If one cannot be found, return without
  78290. ** generating any VDBE code. If one can be found, then jump over
  78291. ** the entire DELETE if there are no outstanding deferred constraints
  78292. ** when this statement is run. */
  78293. FKey *p;
  78294. for(p=pTab->pFKey; p; p=p->pNextFrom){
  78295. if( p->isDeferred ) break;
  78296. }
  78297. if( !p ) return;
  78298. iSkip = sqlite3VdbeMakeLabel(v);
  78299. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  78300. }
  78301. pParse->disableTriggers = 1;
  78302. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  78303. pParse->disableTriggers = 0;
  78304. /* If the DELETE has generated immediate foreign key constraint
  78305. ** violations, halt the VDBE and return an error at this point, before
  78306. ** any modifications to the schema are made. This is because statement
  78307. ** transactions are not able to rollback schema changes. */
  78308. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  78309. sqlite3HaltConstraint(
  78310. pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
  78311. );
  78312. if( iSkip ){
  78313. sqlite3VdbeResolveLabel(v, iSkip);
  78314. }
  78315. }
  78316. }
  78317. /*
  78318. ** This function is called when inserting, deleting or updating a row of
  78319. ** table pTab to generate VDBE code to perform foreign key constraint
  78320. ** processing for the operation.
  78321. **
  78322. ** For a DELETE operation, parameter regOld is passed the index of the
  78323. ** first register in an array of (pTab->nCol+1) registers containing the
  78324. ** rowid of the row being deleted, followed by each of the column values
  78325. ** of the row being deleted, from left to right. Parameter regNew is passed
  78326. ** zero in this case.
  78327. **
  78328. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  78329. ** first register of an array of (pTab->nCol+1) registers containing the new
  78330. ** row data.
  78331. **
  78332. ** For an UPDATE operation, this function is called twice. Once before
  78333. ** the original record is deleted from the table using the calling convention
  78334. ** described for DELETE. Then again after the original record is deleted
  78335. ** but before the new record is inserted using the INSERT convention.
  78336. */
  78337. SQLITE_PRIVATE void sqlite3FkCheck(
  78338. Parse *pParse, /* Parse context */
  78339. Table *pTab, /* Row is being deleted from this table */
  78340. int regOld, /* Previous row data is stored here */
  78341. int regNew /* New row data is stored here */
  78342. ){
  78343. sqlite3 *db = pParse->db; /* Database handle */
  78344. FKey *pFKey; /* Used to iterate through FKs */
  78345. int iDb; /* Index of database containing pTab */
  78346. const char *zDb; /* Name of database containing pTab */
  78347. int isIgnoreErrors = pParse->disableTriggers;
  78348. /* Exactly one of regOld and regNew should be non-zero. */
  78349. assert( (regOld==0)!=(regNew==0) );
  78350. /* If foreign-keys are disabled, this function is a no-op. */
  78351. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  78352. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  78353. zDb = db->aDb[iDb].zName;
  78354. /* Loop through all the foreign key constraints for which pTab is the
  78355. ** child table (the table that the foreign key definition is part of). */
  78356. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  78357. Table *pTo; /* Parent table of foreign key pFKey */
  78358. Index *pIdx = 0; /* Index on key columns in pTo */
  78359. int *aiFree = 0;
  78360. int *aiCol;
  78361. int iCol;
  78362. int i;
  78363. int isIgnore = 0;
  78364. /* Find the parent table of this foreign key. Also find a unique index
  78365. ** on the parent key columns in the parent table. If either of these
  78366. ** schema items cannot be located, set an error in pParse and return
  78367. ** early. */
  78368. if( pParse->disableTriggers ){
  78369. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  78370. }else{
  78371. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  78372. }
  78373. if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  78374. if( !isIgnoreErrors || db->mallocFailed ) return;
  78375. continue;
  78376. }
  78377. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  78378. if( aiFree ){
  78379. aiCol = aiFree;
  78380. }else{
  78381. iCol = pFKey->aCol[0].iFrom;
  78382. aiCol = &iCol;
  78383. }
  78384. for(i=0; i<pFKey->nCol; i++){
  78385. if( aiCol[i]==pTab->iPKey ){
  78386. aiCol[i] = -1;
  78387. }
  78388. #ifndef SQLITE_OMIT_AUTHORIZATION
  78389. /* Request permission to read the parent key columns. If the
  78390. ** authorization callback returns SQLITE_IGNORE, behave as if any
  78391. ** values read from the parent table are NULL. */
  78392. if( db->xAuth ){
  78393. int rcauth;
  78394. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  78395. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  78396. isIgnore = (rcauth==SQLITE_IGNORE);
  78397. }
  78398. #endif
  78399. }
  78400. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  78401. ** a cursor to use to search the unique index on the parent key columns
  78402. ** in the parent table. */
  78403. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  78404. pParse->nTab++;
  78405. if( regOld!=0 ){
  78406. /* A row is being removed from the child table. Search for the parent.
  78407. ** If the parent does not exist, removing the child row resolves an
  78408. ** outstanding foreign key constraint violation. */
  78409. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  78410. }
  78411. if( regNew!=0 ){
  78412. /* A row is being added to the child table. If a parent row cannot
  78413. ** be found, adding the child row has violated the FK constraint. */
  78414. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  78415. }
  78416. sqlite3DbFree(db, aiFree);
  78417. }
  78418. /* Loop through all the foreign key constraints that refer to this table */
  78419. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  78420. Index *pIdx = 0; /* Foreign key index for pFKey */
  78421. SrcList *pSrc;
  78422. int *aiCol = 0;
  78423. if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
  78424. assert( regOld==0 && regNew!=0 );
  78425. /* Inserting a single row into a parent table cannot cause an immediate
  78426. ** foreign key violation. So do nothing in this case. */
  78427. continue;
  78428. }
  78429. if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  78430. if( !isIgnoreErrors || db->mallocFailed ) return;
  78431. continue;
  78432. }
  78433. assert( aiCol || pFKey->nCol==1 );
  78434. /* Create a SrcList structure containing a single table (the table
  78435. ** the foreign key that refers to this table is attached to). This
  78436. ** is required for the sqlite3WhereXXX() interface. */
  78437. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  78438. if( pSrc ){
  78439. struct SrcList_item *pItem = pSrc->a;
  78440. pItem->pTab = pFKey->pFrom;
  78441. pItem->zName = pFKey->pFrom->zName;
  78442. pItem->pTab->nRef++;
  78443. pItem->iCursor = pParse->nTab++;
  78444. if( regNew!=0 ){
  78445. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  78446. }
  78447. if( regOld!=0 ){
  78448. /* If there is a RESTRICT action configured for the current operation
  78449. ** on the parent table of this FK, then throw an exception
  78450. ** immediately if the FK constraint is violated, even if this is a
  78451. ** deferred trigger. That's what RESTRICT means. To defer checking
  78452. ** the constraint, the FK should specify NO ACTION (represented
  78453. ** using OE_None). NO ACTION is the default. */
  78454. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  78455. }
  78456. pItem->zName = 0;
  78457. sqlite3SrcListDelete(db, pSrc);
  78458. }
  78459. sqlite3DbFree(db, aiCol);
  78460. }
  78461. }
  78462. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  78463. /*
  78464. ** This function is called before generating code to update or delete a
  78465. ** row contained in table pTab.
  78466. */
  78467. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  78468. Parse *pParse, /* Parse context */
  78469. Table *pTab /* Table being modified */
  78470. ){
  78471. u32 mask = 0;
  78472. if( pParse->db->flags&SQLITE_ForeignKeys ){
  78473. FKey *p;
  78474. int i;
  78475. for(p=pTab->pFKey; p; p=p->pNextFrom){
  78476. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  78477. }
  78478. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  78479. Index *pIdx = 0;
  78480. locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
  78481. if( pIdx ){
  78482. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  78483. }
  78484. }
  78485. }
  78486. return mask;
  78487. }
  78488. /*
  78489. ** This function is called before generating code to update or delete a
  78490. ** row contained in table pTab. If the operation is a DELETE, then
  78491. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  78492. ** to an array of size N, where N is the number of columns in table pTab.
  78493. ** If the i'th column is not modified by the UPDATE, then the corresponding
  78494. ** entry in the aChange[] array is set to -1. If the column is modified,
  78495. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  78496. ** UPDATE statement modifies the rowid fields of the table.
  78497. **
  78498. ** If any foreign key processing will be required, this function returns
  78499. ** true. If there is no foreign key related processing, this function
  78500. ** returns false.
  78501. */
  78502. SQLITE_PRIVATE int sqlite3FkRequired(
  78503. Parse *pParse, /* Parse context */
  78504. Table *pTab, /* Table being modified */
  78505. int *aChange, /* Non-NULL for UPDATE operations */
  78506. int chngRowid /* True for UPDATE that affects rowid */
  78507. ){
  78508. if( pParse->db->flags&SQLITE_ForeignKeys ){
  78509. if( !aChange ){
  78510. /* A DELETE operation. Foreign key processing is required if the
  78511. ** table in question is either the child or parent table for any
  78512. ** foreign key constraint. */
  78513. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  78514. }else{
  78515. /* This is an UPDATE. Foreign key processing is only required if the
  78516. ** operation modifies one or more child or parent key columns. */
  78517. int i;
  78518. FKey *p;
  78519. /* Check if any child key columns are being modified. */
  78520. for(p=pTab->pFKey; p; p=p->pNextFrom){
  78521. for(i=0; i<p->nCol; i++){
  78522. int iChildKey = p->aCol[i].iFrom;
  78523. if( aChange[iChildKey]>=0 ) return 1;
  78524. if( iChildKey==pTab->iPKey && chngRowid ) return 1;
  78525. }
  78526. }
  78527. /* Check if any parent key columns are being modified. */
  78528. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  78529. for(i=0; i<p->nCol; i++){
  78530. char *zKey = p->aCol[i].zCol;
  78531. int iKey;
  78532. for(iKey=0; iKey<pTab->nCol; iKey++){
  78533. Column *pCol = &pTab->aCol[iKey];
  78534. if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
  78535. if( aChange[iKey]>=0 ) return 1;
  78536. if( iKey==pTab->iPKey && chngRowid ) return 1;
  78537. }
  78538. }
  78539. }
  78540. }
  78541. }
  78542. }
  78543. return 0;
  78544. }
  78545. /*
  78546. ** This function is called when an UPDATE or DELETE operation is being
  78547. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  78548. ** If the current operation is an UPDATE, then the pChanges parameter is
  78549. ** passed a pointer to the list of columns being modified. If it is a
  78550. ** DELETE, pChanges is passed a NULL pointer.
  78551. **
  78552. ** It returns a pointer to a Trigger structure containing a trigger
  78553. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  78554. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  78555. ** returned (these actions require no special handling by the triggers
  78556. ** sub-system, code for them is created by fkScanChildren()).
  78557. **
  78558. ** For example, if pFKey is the foreign key and pTab is table "p" in
  78559. ** the following schema:
  78560. **
  78561. ** CREATE TABLE p(pk PRIMARY KEY);
  78562. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  78563. **
  78564. ** then the returned trigger structure is equivalent to:
  78565. **
  78566. ** CREATE TRIGGER ... DELETE ON p BEGIN
  78567. ** DELETE FROM c WHERE ck = old.pk;
  78568. ** END;
  78569. **
  78570. ** The returned pointer is cached as part of the foreign key object. It
  78571. ** is eventually freed along with the rest of the foreign key object by
  78572. ** sqlite3FkDelete().
  78573. */
  78574. static Trigger *fkActionTrigger(
  78575. Parse *pParse, /* Parse context */
  78576. Table *pTab, /* Table being updated or deleted from */
  78577. FKey *pFKey, /* Foreign key to get action for */
  78578. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  78579. ){
  78580. sqlite3 *db = pParse->db; /* Database handle */
  78581. int action; /* One of OE_None, OE_Cascade etc. */
  78582. Trigger *pTrigger; /* Trigger definition to return */
  78583. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  78584. action = pFKey->aAction[iAction];
  78585. pTrigger = pFKey->apTrigger[iAction];
  78586. if( action!=OE_None && !pTrigger ){
  78587. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  78588. char const *zFrom; /* Name of child table */
  78589. int nFrom; /* Length in bytes of zFrom */
  78590. Index *pIdx = 0; /* Parent key index for this FK */
  78591. int *aiCol = 0; /* child table cols -> parent key cols */
  78592. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  78593. Expr *pWhere = 0; /* WHERE clause of trigger step */
  78594. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  78595. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  78596. int i; /* Iterator variable */
  78597. Expr *pWhen = 0; /* WHEN clause for the trigger */
  78598. if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  78599. assert( aiCol || pFKey->nCol==1 );
  78600. for(i=0; i<pFKey->nCol; i++){
  78601. Token tOld = { "old", 3 }; /* Literal "old" token */
  78602. Token tNew = { "new", 3 }; /* Literal "new" token */
  78603. Token tFromCol; /* Name of column in child table */
  78604. Token tToCol; /* Name of column in parent table */
  78605. int iFromCol; /* Idx of column in child table */
  78606. Expr *pEq; /* tFromCol = OLD.tToCol */
  78607. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  78608. assert( iFromCol>=0 );
  78609. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  78610. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  78611. tToCol.n = sqlite3Strlen30(tToCol.z);
  78612. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  78613. /* Create the expression "OLD.zToCol = zFromCol". It is important
  78614. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  78615. ** that the affinity and collation sequence associated with the
  78616. ** parent table are used for the comparison. */
  78617. pEq = sqlite3PExpr(pParse, TK_EQ,
  78618. sqlite3PExpr(pParse, TK_DOT,
  78619. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  78620. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  78621. , 0),
  78622. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  78623. , 0);
  78624. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  78625. /* For ON UPDATE, construct the next term of the WHEN clause.
  78626. ** The final WHEN clause will be like this:
  78627. **
  78628. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  78629. */
  78630. if( pChanges ){
  78631. pEq = sqlite3PExpr(pParse, TK_IS,
  78632. sqlite3PExpr(pParse, TK_DOT,
  78633. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  78634. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  78635. 0),
  78636. sqlite3PExpr(pParse, TK_DOT,
  78637. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  78638. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  78639. 0),
  78640. 0);
  78641. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  78642. }
  78643. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  78644. Expr *pNew;
  78645. if( action==OE_Cascade ){
  78646. pNew = sqlite3PExpr(pParse, TK_DOT,
  78647. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  78648. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  78649. , 0);
  78650. }else if( action==OE_SetDflt ){
  78651. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  78652. if( pDflt ){
  78653. pNew = sqlite3ExprDup(db, pDflt, 0);
  78654. }else{
  78655. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  78656. }
  78657. }else{
  78658. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  78659. }
  78660. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  78661. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  78662. }
  78663. }
  78664. sqlite3DbFree(db, aiCol);
  78665. zFrom = pFKey->pFrom->zName;
  78666. nFrom = sqlite3Strlen30(zFrom);
  78667. if( action==OE_Restrict ){
  78668. Token tFrom;
  78669. Expr *pRaise;
  78670. tFrom.z = zFrom;
  78671. tFrom.n = nFrom;
  78672. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  78673. if( pRaise ){
  78674. pRaise->affinity = OE_Abort;
  78675. }
  78676. pSelect = sqlite3SelectNew(pParse,
  78677. sqlite3ExprListAppend(pParse, 0, pRaise),
  78678. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  78679. pWhere,
  78680. 0, 0, 0, 0, 0, 0
  78681. );
  78682. pWhere = 0;
  78683. }
  78684. /* Disable lookaside memory allocation */
  78685. enableLookaside = db->lookaside.bEnabled;
  78686. db->lookaside.bEnabled = 0;
  78687. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  78688. sizeof(Trigger) + /* struct Trigger */
  78689. sizeof(TriggerStep) + /* Single step in trigger program */
  78690. nFrom + 1 /* Space for pStep->target.z */
  78691. );
  78692. if( pTrigger ){
  78693. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  78694. pStep->target.z = (char *)&pStep[1];
  78695. pStep->target.n = nFrom;
  78696. memcpy((char *)pStep->target.z, zFrom, nFrom);
  78697. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  78698. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  78699. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  78700. if( pWhen ){
  78701. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  78702. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  78703. }
  78704. }
  78705. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  78706. db->lookaside.bEnabled = enableLookaside;
  78707. sqlite3ExprDelete(db, pWhere);
  78708. sqlite3ExprDelete(db, pWhen);
  78709. sqlite3ExprListDelete(db, pList);
  78710. sqlite3SelectDelete(db, pSelect);
  78711. if( db->mallocFailed==1 ){
  78712. fkTriggerDelete(db, pTrigger);
  78713. return 0;
  78714. }
  78715. switch( action ){
  78716. case OE_Restrict:
  78717. pStep->op = TK_SELECT;
  78718. break;
  78719. case OE_Cascade:
  78720. if( !pChanges ){
  78721. pStep->op = TK_DELETE;
  78722. break;
  78723. }
  78724. default:
  78725. pStep->op = TK_UPDATE;
  78726. }
  78727. pStep->pTrig = pTrigger;
  78728. pTrigger->pSchema = pTab->pSchema;
  78729. pTrigger->pTabSchema = pTab->pSchema;
  78730. pFKey->apTrigger[iAction] = pTrigger;
  78731. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  78732. }
  78733. return pTrigger;
  78734. }
  78735. /*
  78736. ** This function is called when deleting or updating a row to implement
  78737. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  78738. */
  78739. SQLITE_PRIVATE void sqlite3FkActions(
  78740. Parse *pParse, /* Parse context */
  78741. Table *pTab, /* Table being updated or deleted from */
  78742. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  78743. int regOld /* Address of array containing old row */
  78744. ){
  78745. /* If foreign-key support is enabled, iterate through all FKs that
  78746. ** refer to table pTab. If there is an action associated with the FK
  78747. ** for this operation (either update or delete), invoke the associated
  78748. ** trigger sub-program. */
  78749. if( pParse->db->flags&SQLITE_ForeignKeys ){
  78750. FKey *pFKey; /* Iterator variable */
  78751. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  78752. Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  78753. if( pAction ){
  78754. sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
  78755. }
  78756. }
  78757. }
  78758. }
  78759. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  78760. /*
  78761. ** Free all memory associated with foreign key definitions attached to
  78762. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  78763. ** hash table.
  78764. */
  78765. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  78766. FKey *pFKey; /* Iterator variable */
  78767. FKey *pNext; /* Copy of pFKey->pNextFrom */
  78768. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  78769. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  78770. /* Remove the FK from the fkeyHash hash table. */
  78771. if( !db || db->pnBytesFreed==0 ){
  78772. if( pFKey->pPrevTo ){
  78773. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  78774. }else{
  78775. void *p = (void *)pFKey->pNextTo;
  78776. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  78777. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  78778. }
  78779. if( pFKey->pNextTo ){
  78780. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  78781. }
  78782. }
  78783. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  78784. ** classified as either immediate or deferred.
  78785. */
  78786. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  78787. /* Delete any triggers created to implement actions for this FK. */
  78788. #ifndef SQLITE_OMIT_TRIGGER
  78789. fkTriggerDelete(db, pFKey->apTrigger[0]);
  78790. fkTriggerDelete(db, pFKey->apTrigger[1]);
  78791. #endif
  78792. pNext = pFKey->pNextFrom;
  78793. sqlite3DbFree(db, pFKey);
  78794. }
  78795. }
  78796. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  78797. /************** End of fkey.c ************************************************/
  78798. /************** Begin file insert.c ******************************************/
  78799. /*
  78800. ** 2001 September 15
  78801. **
  78802. ** The author disclaims copyright to this source code. In place of
  78803. ** a legal notice, here is a blessing:
  78804. **
  78805. ** May you do good and not evil.
  78806. ** May you find forgiveness for yourself and forgive others.
  78807. ** May you share freely, never taking more than you give.
  78808. **
  78809. *************************************************************************
  78810. ** This file contains C code routines that are called by the parser
  78811. ** to handle INSERT statements in SQLite.
  78812. */
  78813. /*
  78814. ** Generate code that will open a table for reading.
  78815. */
  78816. SQLITE_PRIVATE void sqlite3OpenTable(
  78817. Parse *p, /* Generate code into this VDBE */
  78818. int iCur, /* The cursor number of the table */
  78819. int iDb, /* The database index in sqlite3.aDb[] */
  78820. Table *pTab, /* The table to be opened */
  78821. int opcode /* OP_OpenRead or OP_OpenWrite */
  78822. ){
  78823. Vdbe *v;
  78824. if( IsVirtual(pTab) ) return;
  78825. v = sqlite3GetVdbe(p);
  78826. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  78827. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  78828. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  78829. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  78830. VdbeComment((v, "%s", pTab->zName));
  78831. }
  78832. /*
  78833. ** Return a pointer to the column affinity string associated with index
  78834. ** pIdx. A column affinity string has one character for each column in
  78835. ** the table, according to the affinity of the column:
  78836. **
  78837. ** Character Column affinity
  78838. ** ------------------------------
  78839. ** 'a' TEXT
  78840. ** 'b' NONE
  78841. ** 'c' NUMERIC
  78842. ** 'd' INTEGER
  78843. ** 'e' REAL
  78844. **
  78845. ** An extra 'b' is appended to the end of the string to cover the
  78846. ** rowid that appears as the last column in every index.
  78847. **
  78848. ** Memory for the buffer containing the column index affinity string
  78849. ** is managed along with the rest of the Index structure. It will be
  78850. ** released when sqlite3DeleteIndex() is called.
  78851. */
  78852. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  78853. if( !pIdx->zColAff ){
  78854. /* The first time a column affinity string for a particular index is
  78855. ** required, it is allocated and populated here. It is then stored as
  78856. ** a member of the Index structure for subsequent use.
  78857. **
  78858. ** The column affinity string will eventually be deleted by
  78859. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  78860. ** up.
  78861. */
  78862. int n;
  78863. Table *pTab = pIdx->pTable;
  78864. sqlite3 *db = sqlite3VdbeDb(v);
  78865. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
  78866. if( !pIdx->zColAff ){
  78867. db->mallocFailed = 1;
  78868. return 0;
  78869. }
  78870. for(n=0; n<pIdx->nColumn; n++){
  78871. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  78872. }
  78873. pIdx->zColAff[n++] = SQLITE_AFF_NONE;
  78874. pIdx->zColAff[n] = 0;
  78875. }
  78876. return pIdx->zColAff;
  78877. }
  78878. /*
  78879. ** Set P4 of the most recently inserted opcode to a column affinity
  78880. ** string for table pTab. A column affinity string has one character
  78881. ** for each column indexed by the index, according to the affinity of the
  78882. ** column:
  78883. **
  78884. ** Character Column affinity
  78885. ** ------------------------------
  78886. ** 'a' TEXT
  78887. ** 'b' NONE
  78888. ** 'c' NUMERIC
  78889. ** 'd' INTEGER
  78890. ** 'e' REAL
  78891. */
  78892. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  78893. /* The first time a column affinity string for a particular table
  78894. ** is required, it is allocated and populated here. It is then
  78895. ** stored as a member of the Table structure for subsequent use.
  78896. **
  78897. ** The column affinity string will eventually be deleted by
  78898. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  78899. */
  78900. if( !pTab->zColAff ){
  78901. char *zColAff;
  78902. int i;
  78903. sqlite3 *db = sqlite3VdbeDb(v);
  78904. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  78905. if( !zColAff ){
  78906. db->mallocFailed = 1;
  78907. return;
  78908. }
  78909. for(i=0; i<pTab->nCol; i++){
  78910. zColAff[i] = pTab->aCol[i].affinity;
  78911. }
  78912. zColAff[pTab->nCol] = '\0';
  78913. pTab->zColAff = zColAff;
  78914. }
  78915. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
  78916. }
  78917. /*
  78918. ** Return non-zero if the table pTab in database iDb or any of its indices
  78919. ** have been opened at any point in the VDBE program beginning at location
  78920. ** iStartAddr throught the end of the program. This is used to see if
  78921. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  78922. ** run without using temporary table for the results of the SELECT.
  78923. */
  78924. static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  78925. Vdbe *v = sqlite3GetVdbe(p);
  78926. int i;
  78927. int iEnd = sqlite3VdbeCurrentAddr(v);
  78928. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78929. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  78930. #endif
  78931. for(i=iStartAddr; i<iEnd; i++){
  78932. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  78933. assert( pOp!=0 );
  78934. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  78935. Index *pIndex;
  78936. int tnum = pOp->p2;
  78937. if( tnum==pTab->tnum ){
  78938. return 1;
  78939. }
  78940. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  78941. if( tnum==pIndex->tnum ){
  78942. return 1;
  78943. }
  78944. }
  78945. }
  78946. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78947. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  78948. assert( pOp->p4.pVtab!=0 );
  78949. assert( pOp->p4type==P4_VTAB );
  78950. return 1;
  78951. }
  78952. #endif
  78953. }
  78954. return 0;
  78955. }
  78956. #ifndef SQLITE_OMIT_AUTOINCREMENT
  78957. /*
  78958. ** Locate or create an AutoincInfo structure associated with table pTab
  78959. ** which is in database iDb. Return the register number for the register
  78960. ** that holds the maximum rowid.
  78961. **
  78962. ** There is at most one AutoincInfo structure per table even if the
  78963. ** same table is autoincremented multiple times due to inserts within
  78964. ** triggers. A new AutoincInfo structure is created if this is the
  78965. ** first use of table pTab. On 2nd and subsequent uses, the original
  78966. ** AutoincInfo structure is used.
  78967. **
  78968. ** Three memory locations are allocated:
  78969. **
  78970. ** (1) Register to hold the name of the pTab table.
  78971. ** (2) Register to hold the maximum ROWID of pTab.
  78972. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  78973. **
  78974. ** The 2nd register is the one that is returned. That is all the
  78975. ** insert routine needs to know about.
  78976. */
  78977. static int autoIncBegin(
  78978. Parse *pParse, /* Parsing context */
  78979. int iDb, /* Index of the database holding pTab */
  78980. Table *pTab /* The table we are writing to */
  78981. ){
  78982. int memId = 0; /* Register holding maximum rowid */
  78983. if( pTab->tabFlags & TF_Autoincrement ){
  78984. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  78985. AutoincInfo *pInfo;
  78986. pInfo = pToplevel->pAinc;
  78987. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  78988. if( pInfo==0 ){
  78989. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  78990. if( pInfo==0 ) return 0;
  78991. pInfo->pNext = pToplevel->pAinc;
  78992. pToplevel->pAinc = pInfo;
  78993. pInfo->pTab = pTab;
  78994. pInfo->iDb = iDb;
  78995. pToplevel->nMem++; /* Register to hold name of table */
  78996. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  78997. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  78998. }
  78999. memId = pInfo->regCtr;
  79000. }
  79001. return memId;
  79002. }
  79003. /*
  79004. ** This routine generates code that will initialize all of the
  79005. ** register used by the autoincrement tracker.
  79006. */
  79007. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  79008. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  79009. sqlite3 *db = pParse->db; /* The database connection */
  79010. Db *pDb; /* Database only autoinc table */
  79011. int memId; /* Register holding max rowid */
  79012. int addr; /* A VDBE address */
  79013. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  79014. /* This routine is never called during trigger-generation. It is
  79015. ** only called from the top-level */
  79016. assert( pParse->pTriggerTab==0 );
  79017. assert( pParse==sqlite3ParseToplevel(pParse) );
  79018. assert( v ); /* We failed long ago if this is not so */
  79019. for(p = pParse->pAinc; p; p = p->pNext){
  79020. pDb = &db->aDb[p->iDb];
  79021. memId = p->regCtr;
  79022. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  79023. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  79024. addr = sqlite3VdbeCurrentAddr(v);
  79025. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  79026. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
  79027. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  79028. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  79029. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  79030. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  79031. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  79032. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  79033. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
  79034. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  79035. sqlite3VdbeAddOp0(v, OP_Close);
  79036. }
  79037. }
  79038. /*
  79039. ** Update the maximum rowid for an autoincrement calculation.
  79040. **
  79041. ** This routine should be called when the top of the stack holds a
  79042. ** new rowid that is about to be inserted. If that new rowid is
  79043. ** larger than the maximum rowid in the memId memory cell, then the
  79044. ** memory cell is updated. The stack is unchanged.
  79045. */
  79046. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  79047. if( memId>0 ){
  79048. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  79049. }
  79050. }
  79051. /*
  79052. ** This routine generates the code needed to write autoincrement
  79053. ** maximum rowid values back into the sqlite_sequence register.
  79054. ** Every statement that might do an INSERT into an autoincrement
  79055. ** table (either directly or through triggers) needs to call this
  79056. ** routine just before the "exit" code.
  79057. */
  79058. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  79059. AutoincInfo *p;
  79060. Vdbe *v = pParse->pVdbe;
  79061. sqlite3 *db = pParse->db;
  79062. assert( v );
  79063. for(p = pParse->pAinc; p; p = p->pNext){
  79064. Db *pDb = &db->aDb[p->iDb];
  79065. int j1, j2, j3, j4, j5;
  79066. int iRec;
  79067. int memId = p->regCtr;
  79068. iRec = sqlite3GetTempReg(pParse);
  79069. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  79070. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  79071. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  79072. j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
  79073. j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
  79074. j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
  79075. sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
  79076. sqlite3VdbeJumpHere(v, j2);
  79077. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  79078. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  79079. sqlite3VdbeJumpHere(v, j4);
  79080. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  79081. sqlite3VdbeJumpHere(v, j1);
  79082. sqlite3VdbeJumpHere(v, j5);
  79083. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  79084. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  79085. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  79086. sqlite3VdbeAddOp0(v, OP_Close);
  79087. sqlite3ReleaseTempReg(pParse, iRec);
  79088. }
  79089. }
  79090. #else
  79091. /*
  79092. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  79093. ** above are all no-ops
  79094. */
  79095. # define autoIncBegin(A,B,C) (0)
  79096. # define autoIncStep(A,B,C)
  79097. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  79098. /* Forward declaration */
  79099. static int xferOptimization(
  79100. Parse *pParse, /* Parser context */
  79101. Table *pDest, /* The table we are inserting into */
  79102. Select *pSelect, /* A SELECT statement to use as the data source */
  79103. int onError, /* How to handle constraint errors */
  79104. int iDbDest /* The database of pDest */
  79105. );
  79106. /*
  79107. ** This routine is call to handle SQL of the following forms:
  79108. **
  79109. ** insert into TABLE (IDLIST) values(EXPRLIST)
  79110. ** insert into TABLE (IDLIST) select
  79111. **
  79112. ** The IDLIST following the table name is always optional. If omitted,
  79113. ** then a list of all columns for the table is substituted. The IDLIST
  79114. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  79115. **
  79116. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  79117. ** statement above, and pSelect is NULL. For the second form, pList is
  79118. ** NULL and pSelect is a pointer to the select statement used to generate
  79119. ** data for the insert.
  79120. **
  79121. ** The code generated follows one of four templates. For a simple
  79122. ** select with data coming from a VALUES clause, the code executes
  79123. ** once straight down through. Pseudo-code follows (we call this
  79124. ** the "1st template"):
  79125. **
  79126. ** open write cursor to <table> and its indices
  79127. ** puts VALUES clause expressions onto the stack
  79128. ** write the resulting record into <table>
  79129. ** cleanup
  79130. **
  79131. ** The three remaining templates assume the statement is of the form
  79132. **
  79133. ** INSERT INTO <table> SELECT ...
  79134. **
  79135. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  79136. ** in other words if the SELECT pulls all columns from a single table
  79137. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  79138. ** if <table2> and <table1> are distinct tables but have identical
  79139. ** schemas, including all the same indices, then a special optimization
  79140. ** is invoked that copies raw records from <table2> over to <table1>.
  79141. ** See the xferOptimization() function for the implementation of this
  79142. ** template. This is the 2nd template.
  79143. **
  79144. ** open a write cursor to <table>
  79145. ** open read cursor on <table2>
  79146. ** transfer all records in <table2> over to <table>
  79147. ** close cursors
  79148. ** foreach index on <table>
  79149. ** open a write cursor on the <table> index
  79150. ** open a read cursor on the corresponding <table2> index
  79151. ** transfer all records from the read to the write cursors
  79152. ** close cursors
  79153. ** end foreach
  79154. **
  79155. ** The 3rd template is for when the second template does not apply
  79156. ** and the SELECT clause does not read from <table> at any time.
  79157. ** The generated code follows this template:
  79158. **
  79159. ** EOF <- 0
  79160. ** X <- A
  79161. ** goto B
  79162. ** A: setup for the SELECT
  79163. ** loop over the rows in the SELECT
  79164. ** load values into registers R..R+n
  79165. ** yield X
  79166. ** end loop
  79167. ** cleanup after the SELECT
  79168. ** EOF <- 1
  79169. ** yield X
  79170. ** goto A
  79171. ** B: open write cursor to <table> and its indices
  79172. ** C: yield X
  79173. ** if EOF goto D
  79174. ** insert the select result into <table> from R..R+n
  79175. ** goto C
  79176. ** D: cleanup
  79177. **
  79178. ** The 4th template is used if the insert statement takes its
  79179. ** values from a SELECT but the data is being inserted into a table
  79180. ** that is also read as part of the SELECT. In the third form,
  79181. ** we have to use a intermediate table to store the results of
  79182. ** the select. The template is like this:
  79183. **
  79184. ** EOF <- 0
  79185. ** X <- A
  79186. ** goto B
  79187. ** A: setup for the SELECT
  79188. ** loop over the tables in the SELECT
  79189. ** load value into register R..R+n
  79190. ** yield X
  79191. ** end loop
  79192. ** cleanup after the SELECT
  79193. ** EOF <- 1
  79194. ** yield X
  79195. ** halt-error
  79196. ** B: open temp table
  79197. ** L: yield X
  79198. ** if EOF goto M
  79199. ** insert row from R..R+n into temp table
  79200. ** goto L
  79201. ** M: open write cursor to <table> and its indices
  79202. ** rewind temp table
  79203. ** C: loop over rows of intermediate table
  79204. ** transfer values form intermediate table into <table>
  79205. ** end loop
  79206. ** D: cleanup
  79207. */
  79208. SQLITE_PRIVATE void sqlite3Insert(
  79209. Parse *pParse, /* Parser context */
  79210. SrcList *pTabList, /* Name of table into which we are inserting */
  79211. ExprList *pList, /* List of values to be inserted */
  79212. Select *pSelect, /* A SELECT statement to use as the data source */
  79213. IdList *pColumn, /* Column names corresponding to IDLIST. */
  79214. int onError /* How to handle constraint errors */
  79215. ){
  79216. sqlite3 *db; /* The main database structure */
  79217. Table *pTab; /* The table to insert into. aka TABLE */
  79218. char *zTab; /* Name of the table into which we are inserting */
  79219. const char *zDb; /* Name of the database holding this table */
  79220. int i, j, idx; /* Loop counters */
  79221. Vdbe *v; /* Generate code into this virtual machine */
  79222. Index *pIdx; /* For looping over indices of the table */
  79223. int nColumn; /* Number of columns in the data */
  79224. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  79225. int baseCur = 0; /* VDBE Cursor number for pTab */
  79226. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  79227. int endOfLoop; /* Label for the end of the insertion loop */
  79228. int useTempTable = 0; /* Store SELECT results in intermediate table */
  79229. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  79230. int addrInsTop = 0; /* Jump to label "D" */
  79231. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  79232. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  79233. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  79234. int iDb; /* Index of database holding TABLE */
  79235. Db *pDb; /* The database containing table being inserted into */
  79236. int appendFlag = 0; /* True if the insert is likely to be an append */
  79237. /* Register allocations */
  79238. int regFromSelect = 0;/* Base register for data coming from SELECT */
  79239. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  79240. int regRowCount = 0; /* Memory cell used for the row counter */
  79241. int regIns; /* Block of regs holding rowid+data being inserted */
  79242. int regRowid; /* registers holding insert rowid */
  79243. int regData; /* register holding first column to insert */
  79244. int regEof = 0; /* Register recording end of SELECT data */
  79245. int *aRegIdx = 0; /* One register allocated to each index */
  79246. #ifndef SQLITE_OMIT_TRIGGER
  79247. int isView; /* True if attempting to insert into a view */
  79248. Trigger *pTrigger; /* List of triggers on pTab, if required */
  79249. int tmask; /* Mask of trigger times */
  79250. #endif
  79251. db = pParse->db;
  79252. memset(&dest, 0, sizeof(dest));
  79253. if( pParse->nErr || db->mallocFailed ){
  79254. goto insert_cleanup;
  79255. }
  79256. /* Locate the table into which we will be inserting new information.
  79257. */
  79258. assert( pTabList->nSrc==1 );
  79259. zTab = pTabList->a[0].zName;
  79260. if( NEVER(zTab==0) ) goto insert_cleanup;
  79261. pTab = sqlite3SrcListLookup(pParse, pTabList);
  79262. if( pTab==0 ){
  79263. goto insert_cleanup;
  79264. }
  79265. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  79266. assert( iDb<db->nDb );
  79267. pDb = &db->aDb[iDb];
  79268. zDb = pDb->zName;
  79269. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  79270. goto insert_cleanup;
  79271. }
  79272. /* Figure out if we have any triggers and if the table being
  79273. ** inserted into is a view
  79274. */
  79275. #ifndef SQLITE_OMIT_TRIGGER
  79276. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  79277. isView = pTab->pSelect!=0;
  79278. #else
  79279. # define pTrigger 0
  79280. # define tmask 0
  79281. # define isView 0
  79282. #endif
  79283. #ifdef SQLITE_OMIT_VIEW
  79284. # undef isView
  79285. # define isView 0
  79286. #endif
  79287. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  79288. /* If pTab is really a view, make sure it has been initialized.
  79289. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  79290. ** module table).
  79291. */
  79292. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  79293. goto insert_cleanup;
  79294. }
  79295. /* Ensure that:
  79296. * (a) the table is not read-only,
  79297. * (b) that if it is a view then ON INSERT triggers exist
  79298. */
  79299. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  79300. goto insert_cleanup;
  79301. }
  79302. /* Allocate a VDBE
  79303. */
  79304. v = sqlite3GetVdbe(pParse);
  79305. if( v==0 ) goto insert_cleanup;
  79306. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  79307. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  79308. #ifndef SQLITE_OMIT_XFER_OPT
  79309. /* If the statement is of the form
  79310. **
  79311. ** INSERT INTO <table1> SELECT * FROM <table2>;
  79312. **
  79313. ** Then special optimizations can be applied that make the transfer
  79314. ** very fast and which reduce fragmentation of indices.
  79315. **
  79316. ** This is the 2nd template.
  79317. */
  79318. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  79319. assert( !pTrigger );
  79320. assert( pList==0 );
  79321. goto insert_end;
  79322. }
  79323. #endif /* SQLITE_OMIT_XFER_OPT */
  79324. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  79325. ** sqlite_sequence table and store it in memory cell regAutoinc.
  79326. */
  79327. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  79328. /* Figure out how many columns of data are supplied. If the data
  79329. ** is coming from a SELECT statement, then generate a co-routine that
  79330. ** produces a single row of the SELECT on each invocation. The
  79331. ** co-routine is the common header to the 3rd and 4th templates.
  79332. */
  79333. if( pSelect ){
  79334. /* Data is coming from a SELECT. Generate code to implement that SELECT
  79335. ** as a co-routine. The code is common to both the 3rd and 4th
  79336. ** templates:
  79337. **
  79338. ** EOF <- 0
  79339. ** X <- A
  79340. ** goto B
  79341. ** A: setup for the SELECT
  79342. ** loop over the tables in the SELECT
  79343. ** load value into register R..R+n
  79344. ** yield X
  79345. ** end loop
  79346. ** cleanup after the SELECT
  79347. ** EOF <- 1
  79348. ** yield X
  79349. ** halt-error
  79350. **
  79351. ** On each invocation of the co-routine, it puts a single row of the
  79352. ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
  79353. ** (These output registers are allocated by sqlite3Select().) When
  79354. ** the SELECT completes, it sets the EOF flag stored in regEof.
  79355. */
  79356. int rc, j1;
  79357. regEof = ++pParse->nMem;
  79358. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  79359. VdbeComment((v, "SELECT eof flag"));
  79360. sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
  79361. addrSelect = sqlite3VdbeCurrentAddr(v)+2;
  79362. sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
  79363. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  79364. VdbeComment((v, "Jump over SELECT coroutine"));
  79365. /* Resolve the expressions in the SELECT statement and execute it. */
  79366. rc = sqlite3Select(pParse, pSelect, &dest);
  79367. assert( pParse->nErr==0 || rc );
  79368. if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
  79369. goto insert_cleanup;
  79370. }
  79371. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  79372. sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */
  79373. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  79374. VdbeComment((v, "End of SELECT coroutine"));
  79375. sqlite3VdbeJumpHere(v, j1); /* label B: */
  79376. regFromSelect = dest.iMem;
  79377. assert( pSelect->pEList );
  79378. nColumn = pSelect->pEList->nExpr;
  79379. assert( dest.nMem==nColumn );
  79380. /* Set useTempTable to TRUE if the result of the SELECT statement
  79381. ** should be written into a temporary table (template 4). Set to
  79382. ** FALSE if each* row of the SELECT can be written directly into
  79383. ** the destination table (template 3).
  79384. **
  79385. ** A temp table must be used if the table being updated is also one
  79386. ** of the tables being read by the SELECT statement. Also use a
  79387. ** temp table in the case of row triggers.
  79388. */
  79389. if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
  79390. useTempTable = 1;
  79391. }
  79392. if( useTempTable ){
  79393. /* Invoke the coroutine to extract information from the SELECT
  79394. ** and add it to a transient table srcTab. The code generated
  79395. ** here is from the 4th template:
  79396. **
  79397. ** B: open temp table
  79398. ** L: yield X
  79399. ** if EOF goto M
  79400. ** insert row from R..R+n into temp table
  79401. ** goto L
  79402. ** M: ...
  79403. */
  79404. int regRec; /* Register to hold packed record */
  79405. int regTempRowid; /* Register to hold temp table ROWID */
  79406. int addrTop; /* Label "L" */
  79407. int addrIf; /* Address of jump to M */
  79408. srcTab = pParse->nTab++;
  79409. regRec = sqlite3GetTempReg(pParse);
  79410. regTempRowid = sqlite3GetTempReg(pParse);
  79411. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  79412. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
  79413. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  79414. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  79415. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  79416. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  79417. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  79418. sqlite3VdbeJumpHere(v, addrIf);
  79419. sqlite3ReleaseTempReg(pParse, regRec);
  79420. sqlite3ReleaseTempReg(pParse, regTempRowid);
  79421. }
  79422. }else{
  79423. /* This is the case if the data for the INSERT is coming from a VALUES
  79424. ** clause
  79425. */
  79426. NameContext sNC;
  79427. memset(&sNC, 0, sizeof(sNC));
  79428. sNC.pParse = pParse;
  79429. srcTab = -1;
  79430. assert( useTempTable==0 );
  79431. nColumn = pList ? pList->nExpr : 0;
  79432. for(i=0; i<nColumn; i++){
  79433. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  79434. goto insert_cleanup;
  79435. }
  79436. }
  79437. }
  79438. /* Make sure the number of columns in the source data matches the number
  79439. ** of columns to be inserted into the table.
  79440. */
  79441. if( IsVirtual(pTab) ){
  79442. for(i=0; i<pTab->nCol; i++){
  79443. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  79444. }
  79445. }
  79446. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  79447. sqlite3ErrorMsg(pParse,
  79448. "table %S has %d columns but %d values were supplied",
  79449. pTabList, 0, pTab->nCol-nHidden, nColumn);
  79450. goto insert_cleanup;
  79451. }
  79452. if( pColumn!=0 && nColumn!=pColumn->nId ){
  79453. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  79454. goto insert_cleanup;
  79455. }
  79456. /* If the INSERT statement included an IDLIST term, then make sure
  79457. ** all elements of the IDLIST really are columns of the table and
  79458. ** remember the column indices.
  79459. **
  79460. ** If the table has an INTEGER PRIMARY KEY column and that column
  79461. ** is named in the IDLIST, then record in the keyColumn variable
  79462. ** the index into IDLIST of the primary key column. keyColumn is
  79463. ** the index of the primary key as it appears in IDLIST, not as
  79464. ** is appears in the original table. (The index of the primary
  79465. ** key in the original table is pTab->iPKey.)
  79466. */
  79467. if( pColumn ){
  79468. for(i=0; i<pColumn->nId; i++){
  79469. pColumn->a[i].idx = -1;
  79470. }
  79471. for(i=0; i<pColumn->nId; i++){
  79472. for(j=0; j<pTab->nCol; j++){
  79473. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  79474. pColumn->a[i].idx = j;
  79475. if( j==pTab->iPKey ){
  79476. keyColumn = i;
  79477. }
  79478. break;
  79479. }
  79480. }
  79481. if( j>=pTab->nCol ){
  79482. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  79483. keyColumn = i;
  79484. }else{
  79485. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  79486. pTabList, 0, pColumn->a[i].zName);
  79487. pParse->checkSchema = 1;
  79488. goto insert_cleanup;
  79489. }
  79490. }
  79491. }
  79492. }
  79493. /* If there is no IDLIST term but the table has an integer primary
  79494. ** key, the set the keyColumn variable to the primary key column index
  79495. ** in the original table definition.
  79496. */
  79497. if( pColumn==0 && nColumn>0 ){
  79498. keyColumn = pTab->iPKey;
  79499. }
  79500. /* Initialize the count of rows to be inserted
  79501. */
  79502. if( db->flags & SQLITE_CountRows ){
  79503. regRowCount = ++pParse->nMem;
  79504. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  79505. }
  79506. /* If this is not a view, open the table and and all indices */
  79507. if( !isView ){
  79508. int nIdx;
  79509. baseCur = pParse->nTab;
  79510. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  79511. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  79512. if( aRegIdx==0 ){
  79513. goto insert_cleanup;
  79514. }
  79515. for(i=0; i<nIdx; i++){
  79516. aRegIdx[i] = ++pParse->nMem;
  79517. }
  79518. }
  79519. /* This is the top of the main insertion loop */
  79520. if( useTempTable ){
  79521. /* This block codes the top of loop only. The complete loop is the
  79522. ** following pseudocode (template 4):
  79523. **
  79524. ** rewind temp table
  79525. ** C: loop over rows of intermediate table
  79526. ** transfer values form intermediate table into <table>
  79527. ** end loop
  79528. ** D: ...
  79529. */
  79530. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  79531. addrCont = sqlite3VdbeCurrentAddr(v);
  79532. }else if( pSelect ){
  79533. /* This block codes the top of loop only. The complete loop is the
  79534. ** following pseudocode (template 3):
  79535. **
  79536. ** C: yield X
  79537. ** if EOF goto D
  79538. ** insert the select result into <table> from R..R+n
  79539. ** goto C
  79540. ** D: ...
  79541. */
  79542. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
  79543. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  79544. }
  79545. /* Allocate registers for holding the rowid of the new row,
  79546. ** the content of the new row, and the assemblied row record.
  79547. */
  79548. regRowid = regIns = pParse->nMem+1;
  79549. pParse->nMem += pTab->nCol + 1;
  79550. if( IsVirtual(pTab) ){
  79551. regRowid++;
  79552. pParse->nMem++;
  79553. }
  79554. regData = regRowid+1;
  79555. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  79556. */
  79557. endOfLoop = sqlite3VdbeMakeLabel(v);
  79558. if( tmask & TRIGGER_BEFORE ){
  79559. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  79560. /* build the NEW.* reference row. Note that if there is an INTEGER
  79561. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  79562. ** translated into a unique ID for the row. But on a BEFORE trigger,
  79563. ** we do not know what the unique ID will be (because the insert has
  79564. ** not happened yet) so we substitute a rowid of -1
  79565. */
  79566. if( keyColumn<0 ){
  79567. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  79568. }else{
  79569. int j1;
  79570. if( useTempTable ){
  79571. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
  79572. }else{
  79573. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  79574. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
  79575. }
  79576. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
  79577. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  79578. sqlite3VdbeJumpHere(v, j1);
  79579. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
  79580. }
  79581. /* Cannot have triggers on a virtual table. If it were possible,
  79582. ** this block would have to account for hidden column.
  79583. */
  79584. assert( !IsVirtual(pTab) );
  79585. /* Create the new column data
  79586. */
  79587. for(i=0; i<pTab->nCol; i++){
  79588. if( pColumn==0 ){
  79589. j = i;
  79590. }else{
  79591. for(j=0; j<pColumn->nId; j++){
  79592. if( pColumn->a[j].idx==i ) break;
  79593. }
  79594. }
  79595. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  79596. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  79597. }else if( useTempTable ){
  79598. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  79599. }else{
  79600. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  79601. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  79602. }
  79603. }
  79604. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  79605. ** do not attempt any conversions before assembling the record.
  79606. ** If this is a real table, attempt conversions as required by the
  79607. ** table column affinities.
  79608. */
  79609. if( !isView ){
  79610. sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
  79611. sqlite3TableAffinityStr(v, pTab);
  79612. }
  79613. /* Fire BEFORE or INSTEAD OF triggers */
  79614. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  79615. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  79616. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  79617. }
  79618. /* Push the record number for the new entry onto the stack. The
  79619. ** record number is a randomly generate integer created by NewRowid
  79620. ** except when the table has an INTEGER PRIMARY KEY column, in which
  79621. ** case the record number is the same as that column.
  79622. */
  79623. if( !isView ){
  79624. if( IsVirtual(pTab) ){
  79625. /* The row that the VUpdate opcode will delete: none */
  79626. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  79627. }
  79628. if( keyColumn>=0 ){
  79629. if( useTempTable ){
  79630. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  79631. }else if( pSelect ){
  79632. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  79633. }else{
  79634. VdbeOp *pOp;
  79635. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  79636. pOp = sqlite3VdbeGetOp(v, -1);
  79637. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  79638. appendFlag = 1;
  79639. pOp->opcode = OP_NewRowid;
  79640. pOp->p1 = baseCur;
  79641. pOp->p2 = regRowid;
  79642. pOp->p3 = regAutoinc;
  79643. }
  79644. }
  79645. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  79646. ** to generate a unique primary key value.
  79647. */
  79648. if( !appendFlag ){
  79649. int j1;
  79650. if( !IsVirtual(pTab) ){
  79651. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  79652. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  79653. sqlite3VdbeJumpHere(v, j1);
  79654. }else{
  79655. j1 = sqlite3VdbeCurrentAddr(v);
  79656. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  79657. }
  79658. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  79659. }
  79660. }else if( IsVirtual(pTab) ){
  79661. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  79662. }else{
  79663. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  79664. appendFlag = 1;
  79665. }
  79666. autoIncStep(pParse, regAutoinc, regRowid);
  79667. /* Push onto the stack, data for all columns of the new entry, beginning
  79668. ** with the first column.
  79669. */
  79670. nHidden = 0;
  79671. for(i=0; i<pTab->nCol; i++){
  79672. int iRegStore = regRowid+1+i;
  79673. if( i==pTab->iPKey ){
  79674. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  79675. ** Whenever this column is read, the record number will be substituted
  79676. ** in its place. So will fill this column with a NULL to avoid
  79677. ** taking up data space with information that will never be used. */
  79678. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  79679. continue;
  79680. }
  79681. if( pColumn==0 ){
  79682. if( IsHiddenColumn(&pTab->aCol[i]) ){
  79683. assert( IsVirtual(pTab) );
  79684. j = -1;
  79685. nHidden++;
  79686. }else{
  79687. j = i - nHidden;
  79688. }
  79689. }else{
  79690. for(j=0; j<pColumn->nId; j++){
  79691. if( pColumn->a[j].idx==i ) break;
  79692. }
  79693. }
  79694. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  79695. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  79696. }else if( useTempTable ){
  79697. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  79698. }else if( pSelect ){
  79699. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  79700. }else{
  79701. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  79702. }
  79703. }
  79704. /* Generate code to check constraints and generate index keys and
  79705. ** do the insertion.
  79706. */
  79707. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79708. if( IsVirtual(pTab) ){
  79709. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  79710. sqlite3VtabMakeWritable(pParse, pTab);
  79711. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  79712. sqlite3MayAbort(pParse);
  79713. }else
  79714. #endif
  79715. {
  79716. int isReplace; /* Set to true if constraints may cause a replace */
  79717. sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
  79718. keyColumn>=0, 0, onError, endOfLoop, &isReplace
  79719. );
  79720. sqlite3FkCheck(pParse, pTab, 0, regIns);
  79721. sqlite3CompleteInsertion(
  79722. pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  79723. );
  79724. }
  79725. }
  79726. /* Update the count of rows that are inserted
  79727. */
  79728. if( (db->flags & SQLITE_CountRows)!=0 ){
  79729. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  79730. }
  79731. if( pTrigger ){
  79732. /* Code AFTER triggers */
  79733. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  79734. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  79735. }
  79736. /* The bottom of the main insertion loop, if the data source
  79737. ** is a SELECT statement.
  79738. */
  79739. sqlite3VdbeResolveLabel(v, endOfLoop);
  79740. if( useTempTable ){
  79741. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  79742. sqlite3VdbeJumpHere(v, addrInsTop);
  79743. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  79744. }else if( pSelect ){
  79745. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  79746. sqlite3VdbeJumpHere(v, addrInsTop);
  79747. }
  79748. if( !IsVirtual(pTab) && !isView ){
  79749. /* Close all tables opened */
  79750. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  79751. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  79752. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  79753. }
  79754. }
  79755. insert_end:
  79756. /* Update the sqlite_sequence table by storing the content of the
  79757. ** maximum rowid counter values recorded while inserting into
  79758. ** autoincrement tables.
  79759. */
  79760. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  79761. sqlite3AutoincrementEnd(pParse);
  79762. }
  79763. /*
  79764. ** Return the number of rows inserted. If this routine is
  79765. ** generating code because of a call to sqlite3NestedParse(), do not
  79766. ** invoke the callback function.
  79767. */
  79768. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  79769. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  79770. sqlite3VdbeSetNumCols(v, 1);
  79771. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  79772. }
  79773. insert_cleanup:
  79774. sqlite3SrcListDelete(db, pTabList);
  79775. sqlite3ExprListDelete(db, pList);
  79776. sqlite3SelectDelete(db, pSelect);
  79777. sqlite3IdListDelete(db, pColumn);
  79778. sqlite3DbFree(db, aRegIdx);
  79779. }
  79780. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  79781. ** thely may interfere with compilation of other functions in this file
  79782. ** (or in another file, if this file becomes part of the amalgamation). */
  79783. #ifdef isView
  79784. #undef isView
  79785. #endif
  79786. #ifdef pTrigger
  79787. #undef pTrigger
  79788. #endif
  79789. #ifdef tmask
  79790. #undef tmask
  79791. #endif
  79792. /*
  79793. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  79794. **
  79795. ** The input is a range of consecutive registers as follows:
  79796. **
  79797. ** 1. The rowid of the row after the update.
  79798. **
  79799. ** 2. The data in the first column of the entry after the update.
  79800. **
  79801. ** i. Data from middle columns...
  79802. **
  79803. ** N. The data in the last column of the entry after the update.
  79804. **
  79805. ** The regRowid parameter is the index of the register containing (1).
  79806. **
  79807. ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
  79808. ** the address of a register containing the rowid before the update takes
  79809. ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
  79810. ** is false, indicating an INSERT statement, then a non-zero rowidChng
  79811. ** indicates that the rowid was explicitly specified as part of the
  79812. ** INSERT statement. If rowidChng is false, it means that the rowid is
  79813. ** computed automatically in an insert or that the rowid value is not
  79814. ** modified by an update.
  79815. **
  79816. ** The code generated by this routine store new index entries into
  79817. ** registers identified by aRegIdx[]. No index entry is created for
  79818. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  79819. ** the same as the order of indices on the linked list of indices
  79820. ** attached to the table.
  79821. **
  79822. ** This routine also generates code to check constraints. NOT NULL,
  79823. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  79824. ** then the appropriate action is performed. There are five possible
  79825. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  79826. **
  79827. ** Constraint type Action What Happens
  79828. ** --------------- ---------- ----------------------------------------
  79829. ** any ROLLBACK The current transaction is rolled back and
  79830. ** sqlite3_exec() returns immediately with a
  79831. ** return code of SQLITE_CONSTRAINT.
  79832. **
  79833. ** any ABORT Back out changes from the current command
  79834. ** only (do not do a complete rollback) then
  79835. ** cause sqlite3_exec() to return immediately
  79836. ** with SQLITE_CONSTRAINT.
  79837. **
  79838. ** any FAIL Sqlite_exec() returns immediately with a
  79839. ** return code of SQLITE_CONSTRAINT. The
  79840. ** transaction is not rolled back and any
  79841. ** prior changes are retained.
  79842. **
  79843. ** any IGNORE The record number and data is popped from
  79844. ** the stack and there is an immediate jump
  79845. ** to label ignoreDest.
  79846. **
  79847. ** NOT NULL REPLACE The NULL value is replace by the default
  79848. ** value for that column. If the default value
  79849. ** is NULL, the action is the same as ABORT.
  79850. **
  79851. ** UNIQUE REPLACE The other row that conflicts with the row
  79852. ** being inserted is removed.
  79853. **
  79854. ** CHECK REPLACE Illegal. The results in an exception.
  79855. **
  79856. ** Which action to take is determined by the overrideError parameter.
  79857. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  79858. ** is used. Or if pParse->onError==OE_Default then the onError value
  79859. ** for the constraint is used.
  79860. **
  79861. ** The calling routine must open a read/write cursor for pTab with
  79862. ** cursor number "baseCur". All indices of pTab must also have open
  79863. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  79864. ** Except, if there is no possibility of a REPLACE action then
  79865. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  79866. */
  79867. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  79868. Parse *pParse, /* The parser context */
  79869. Table *pTab, /* the table into which we are inserting */
  79870. int baseCur, /* Index of a read/write cursor pointing at pTab */
  79871. int regRowid, /* Index of the range of input registers */
  79872. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  79873. int rowidChng, /* True if the rowid might collide with existing entry */
  79874. int isUpdate, /* True for UPDATE, False for INSERT */
  79875. int overrideError, /* Override onError to this if not OE_Default */
  79876. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  79877. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  79878. ){
  79879. int i; /* loop counter */
  79880. Vdbe *v; /* VDBE under constrution */
  79881. int nCol; /* Number of columns */
  79882. int onError; /* Conflict resolution strategy */
  79883. int j1; /* Addresss of jump instruction */
  79884. int j2 = 0, j3; /* Addresses of jump instructions */
  79885. int regData; /* Register containing first data column */
  79886. int iCur; /* Table cursor number */
  79887. Index *pIdx; /* Pointer to one of the indices */
  79888. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  79889. int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  79890. v = sqlite3GetVdbe(pParse);
  79891. assert( v!=0 );
  79892. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  79893. nCol = pTab->nCol;
  79894. regData = regRowid + 1;
  79895. /* Test all NOT NULL constraints.
  79896. */
  79897. for(i=0; i<nCol; i++){
  79898. if( i==pTab->iPKey ){
  79899. continue;
  79900. }
  79901. onError = pTab->aCol[i].notNull;
  79902. if( onError==OE_None ) continue;
  79903. if( overrideError!=OE_Default ){
  79904. onError = overrideError;
  79905. }else if( onError==OE_Default ){
  79906. onError = OE_Abort;
  79907. }
  79908. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  79909. onError = OE_Abort;
  79910. }
  79911. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  79912. || onError==OE_Ignore || onError==OE_Replace );
  79913. switch( onError ){
  79914. case OE_Abort:
  79915. sqlite3MayAbort(pParse);
  79916. case OE_Rollback:
  79917. case OE_Fail: {
  79918. char *zMsg;
  79919. sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  79920. SQLITE_CONSTRAINT, onError, regData+i);
  79921. zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
  79922. pTab->zName, pTab->aCol[i].zName);
  79923. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  79924. break;
  79925. }
  79926. case OE_Ignore: {
  79927. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  79928. break;
  79929. }
  79930. default: {
  79931. assert( onError==OE_Replace );
  79932. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  79933. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  79934. sqlite3VdbeJumpHere(v, j1);
  79935. break;
  79936. }
  79937. }
  79938. }
  79939. /* Test all CHECK constraints
  79940. */
  79941. #ifndef SQLITE_OMIT_CHECK
  79942. if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
  79943. int allOk = sqlite3VdbeMakeLabel(v);
  79944. pParse->ckBase = regData;
  79945. sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
  79946. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  79947. if( onError==OE_Ignore ){
  79948. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  79949. }else{
  79950. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  79951. sqlite3HaltConstraint(pParse, onError, 0, 0);
  79952. }
  79953. sqlite3VdbeResolveLabel(v, allOk);
  79954. }
  79955. #endif /* !defined(SQLITE_OMIT_CHECK) */
  79956. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  79957. ** of the new record does not previously exist. Except, if this
  79958. ** is an UPDATE and the primary key is not changing, that is OK.
  79959. */
  79960. if( rowidChng ){
  79961. onError = pTab->keyConf;
  79962. if( overrideError!=OE_Default ){
  79963. onError = overrideError;
  79964. }else if( onError==OE_Default ){
  79965. onError = OE_Abort;
  79966. }
  79967. if( isUpdate ){
  79968. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  79969. }
  79970. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  79971. switch( onError ){
  79972. default: {
  79973. onError = OE_Abort;
  79974. /* Fall thru into the next case */
  79975. }
  79976. case OE_Rollback:
  79977. case OE_Abort:
  79978. case OE_Fail: {
  79979. sqlite3HaltConstraint(
  79980. pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
  79981. break;
  79982. }
  79983. case OE_Replace: {
  79984. /* If there are DELETE triggers on this table and the
  79985. ** recursive-triggers flag is set, call GenerateRowDelete() to
  79986. ** remove the conflicting row from the the table. This will fire
  79987. ** the triggers and remove both the table and index b-tree entries.
  79988. **
  79989. ** Otherwise, if there are no triggers or the recursive-triggers
  79990. ** flag is not set, but the table has one or more indexes, call
  79991. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  79992. ** only. The table b-tree entry will be replaced by the new entry
  79993. ** when it is inserted.
  79994. **
  79995. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  79996. ** also invoke MultiWrite() to indicate that this VDBE may require
  79997. ** statement rollback (if the statement is aborted after the delete
  79998. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  79999. ** but being more selective here allows statements like:
  80000. **
  80001. ** REPLACE INTO t(rowid) VALUES($newrowid)
  80002. **
  80003. ** to run without a statement journal if there are no indexes on the
  80004. ** table.
  80005. */
  80006. Trigger *pTrigger = 0;
  80007. if( pParse->db->flags&SQLITE_RecTriggers ){
  80008. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  80009. }
  80010. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  80011. sqlite3MultiWrite(pParse);
  80012. sqlite3GenerateRowDelete(
  80013. pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
  80014. );
  80015. }else if( pTab->pIndex ){
  80016. sqlite3MultiWrite(pParse);
  80017. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  80018. }
  80019. seenReplace = 1;
  80020. break;
  80021. }
  80022. case OE_Ignore: {
  80023. assert( seenReplace==0 );
  80024. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  80025. break;
  80026. }
  80027. }
  80028. sqlite3VdbeJumpHere(v, j3);
  80029. if( isUpdate ){
  80030. sqlite3VdbeJumpHere(v, j2);
  80031. }
  80032. }
  80033. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  80034. ** index and making sure that duplicate entries do not already exist.
  80035. ** Add the new records to the indices as we go.
  80036. */
  80037. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  80038. int regIdx;
  80039. int regR;
  80040. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  80041. /* Create a key for accessing the index entry */
  80042. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  80043. for(i=0; i<pIdx->nColumn; i++){
  80044. int idx = pIdx->aiColumn[i];
  80045. if( idx==pTab->iPKey ){
  80046. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  80047. }else{
  80048. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  80049. }
  80050. }
  80051. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  80052. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  80053. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  80054. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  80055. /* Find out what action to take in case there is an indexing conflict */
  80056. onError = pIdx->onError;
  80057. if( onError==OE_None ){
  80058. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  80059. continue; /* pIdx is not a UNIQUE index */
  80060. }
  80061. if( overrideError!=OE_Default ){
  80062. onError = overrideError;
  80063. }else if( onError==OE_Default ){
  80064. onError = OE_Abort;
  80065. }
  80066. if( seenReplace ){
  80067. if( onError==OE_Ignore ) onError = OE_Replace;
  80068. else if( onError==OE_Fail ) onError = OE_Abort;
  80069. }
  80070. /* Check to see if the new index entry will be unique */
  80071. regR = sqlite3GetTempReg(pParse);
  80072. sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  80073. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  80074. regR, SQLITE_INT_TO_PTR(regIdx),
  80075. P4_INT32);
  80076. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  80077. /* Generate code that executes if the new index entry is not unique */
  80078. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  80079. || onError==OE_Ignore || onError==OE_Replace );
  80080. switch( onError ){
  80081. case OE_Rollback:
  80082. case OE_Abort:
  80083. case OE_Fail: {
  80084. int j;
  80085. StrAccum errMsg;
  80086. const char *zSep;
  80087. char *zErr;
  80088. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  80089. errMsg.db = pParse->db;
  80090. zSep = pIdx->nColumn>1 ? "columns " : "column ";
  80091. for(j=0; j<pIdx->nColumn; j++){
  80092. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  80093. sqlite3StrAccumAppend(&errMsg, zSep, -1);
  80094. zSep = ", ";
  80095. sqlite3StrAccumAppend(&errMsg, zCol, -1);
  80096. }
  80097. sqlite3StrAccumAppend(&errMsg,
  80098. pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
  80099. zErr = sqlite3StrAccumFinish(&errMsg);
  80100. sqlite3HaltConstraint(pParse, onError, zErr, 0);
  80101. sqlite3DbFree(errMsg.db, zErr);
  80102. break;
  80103. }
  80104. case OE_Ignore: {
  80105. assert( seenReplace==0 );
  80106. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  80107. break;
  80108. }
  80109. default: {
  80110. Trigger *pTrigger = 0;
  80111. assert( onError==OE_Replace );
  80112. sqlite3MultiWrite(pParse);
  80113. if( pParse->db->flags&SQLITE_RecTriggers ){
  80114. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  80115. }
  80116. sqlite3GenerateRowDelete(
  80117. pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  80118. );
  80119. seenReplace = 1;
  80120. break;
  80121. }
  80122. }
  80123. sqlite3VdbeJumpHere(v, j3);
  80124. sqlite3ReleaseTempReg(pParse, regR);
  80125. }
  80126. if( pbMayReplace ){
  80127. *pbMayReplace = seenReplace;
  80128. }
  80129. }
  80130. /*
  80131. ** This routine generates code to finish the INSERT or UPDATE operation
  80132. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  80133. ** A consecutive range of registers starting at regRowid contains the
  80134. ** rowid and the content to be inserted.
  80135. **
  80136. ** The arguments to this routine should be the same as the first six
  80137. ** arguments to sqlite3GenerateConstraintChecks.
  80138. */
  80139. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  80140. Parse *pParse, /* The parser context */
  80141. Table *pTab, /* the table into which we are inserting */
  80142. int baseCur, /* Index of a read/write cursor pointing at pTab */
  80143. int regRowid, /* Range of content */
  80144. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  80145. int isUpdate, /* True for UPDATE, False for INSERT */
  80146. int appendBias, /* True if this is likely to be an append */
  80147. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  80148. ){
  80149. int i;
  80150. Vdbe *v;
  80151. int nIdx;
  80152. Index *pIdx;
  80153. u8 pik_flags;
  80154. int regData;
  80155. int regRec;
  80156. v = sqlite3GetVdbe(pParse);
  80157. assert( v!=0 );
  80158. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  80159. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  80160. for(i=nIdx-1; i>=0; i--){
  80161. if( aRegIdx[i]==0 ) continue;
  80162. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  80163. if( useSeekResult ){
  80164. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  80165. }
  80166. }
  80167. regData = regRowid + 1;
  80168. regRec = sqlite3GetTempReg(pParse);
  80169. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  80170. sqlite3TableAffinityStr(v, pTab);
  80171. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  80172. if( pParse->nested ){
  80173. pik_flags = 0;
  80174. }else{
  80175. pik_flags = OPFLAG_NCHANGE;
  80176. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  80177. }
  80178. if( appendBias ){
  80179. pik_flags |= OPFLAG_APPEND;
  80180. }
  80181. if( useSeekResult ){
  80182. pik_flags |= OPFLAG_USESEEKRESULT;
  80183. }
  80184. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  80185. if( !pParse->nested ){
  80186. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  80187. }
  80188. sqlite3VdbeChangeP5(v, pik_flags);
  80189. }
  80190. /*
  80191. ** Generate code that will open cursors for a table and for all
  80192. ** indices of that table. The "baseCur" parameter is the cursor number used
  80193. ** for the table. Indices are opened on subsequent cursors.
  80194. **
  80195. ** Return the number of indices on the table.
  80196. */
  80197. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  80198. Parse *pParse, /* Parsing context */
  80199. Table *pTab, /* Table to be opened */
  80200. int baseCur, /* Cursor number assigned to the table */
  80201. int op /* OP_OpenRead or OP_OpenWrite */
  80202. ){
  80203. int i;
  80204. int iDb;
  80205. Index *pIdx;
  80206. Vdbe *v;
  80207. if( IsVirtual(pTab) ) return 0;
  80208. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  80209. v = sqlite3GetVdbe(pParse);
  80210. assert( v!=0 );
  80211. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  80212. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  80213. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  80214. assert( pIdx->pSchema==pTab->pSchema );
  80215. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  80216. (char*)pKey, P4_KEYINFO_HANDOFF);
  80217. VdbeComment((v, "%s", pIdx->zName));
  80218. }
  80219. if( pParse->nTab<baseCur+i ){
  80220. pParse->nTab = baseCur+i;
  80221. }
  80222. return i-1;
  80223. }
  80224. #ifdef SQLITE_TEST
  80225. /*
  80226. ** The following global variable is incremented whenever the
  80227. ** transfer optimization is used. This is used for testing
  80228. ** purposes only - to make sure the transfer optimization really
  80229. ** is happening when it is suppose to.
  80230. */
  80231. SQLITE_API int sqlite3_xferopt_count;
  80232. #endif /* SQLITE_TEST */
  80233. #ifndef SQLITE_OMIT_XFER_OPT
  80234. /*
  80235. ** Check to collation names to see if they are compatible.
  80236. */
  80237. static int xferCompatibleCollation(const char *z1, const char *z2){
  80238. if( z1==0 ){
  80239. return z2==0;
  80240. }
  80241. if( z2==0 ){
  80242. return 0;
  80243. }
  80244. return sqlite3StrICmp(z1, z2)==0;
  80245. }
  80246. /*
  80247. ** Check to see if index pSrc is compatible as a source of data
  80248. ** for index pDest in an insert transfer optimization. The rules
  80249. ** for a compatible index:
  80250. **
  80251. ** * The index is over the same set of columns
  80252. ** * The same DESC and ASC markings occurs on all columns
  80253. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  80254. ** * The same collating sequence on each column
  80255. */
  80256. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  80257. int i;
  80258. assert( pDest && pSrc );
  80259. assert( pDest->pTable!=pSrc->pTable );
  80260. if( pDest->nColumn!=pSrc->nColumn ){
  80261. return 0; /* Different number of columns */
  80262. }
  80263. if( pDest->onError!=pSrc->onError ){
  80264. return 0; /* Different conflict resolution strategies */
  80265. }
  80266. for(i=0; i<pSrc->nColumn; i++){
  80267. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  80268. return 0; /* Different columns indexed */
  80269. }
  80270. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  80271. return 0; /* Different sort orders */
  80272. }
  80273. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  80274. return 0; /* Different collating sequences */
  80275. }
  80276. }
  80277. /* If no test above fails then the indices must be compatible */
  80278. return 1;
  80279. }
  80280. /*
  80281. ** Attempt the transfer optimization on INSERTs of the form
  80282. **
  80283. ** INSERT INTO tab1 SELECT * FROM tab2;
  80284. **
  80285. ** This optimization is only attempted if
  80286. **
  80287. ** (1) tab1 and tab2 have identical schemas including all the
  80288. ** same indices and constraints
  80289. **
  80290. ** (2) tab1 and tab2 are different tables
  80291. **
  80292. ** (3) There must be no triggers on tab1
  80293. **
  80294. ** (4) The result set of the SELECT statement is "*"
  80295. **
  80296. ** (5) The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
  80297. ** or LIMIT clause.
  80298. **
  80299. ** (6) The SELECT statement is a simple (not a compound) select that
  80300. ** contains only tab2 in its FROM clause
  80301. **
  80302. ** This method for implementing the INSERT transfers raw records from
  80303. ** tab2 over to tab1. The columns are not decoded. Raw records from
  80304. ** the indices of tab2 are transfered to tab1 as well. In so doing,
  80305. ** the resulting tab1 has much less fragmentation.
  80306. **
  80307. ** This routine returns TRUE if the optimization is attempted. If any
  80308. ** of the conditions above fail so that the optimization should not
  80309. ** be attempted, then this routine returns FALSE.
  80310. */
  80311. static int xferOptimization(
  80312. Parse *pParse, /* Parser context */
  80313. Table *pDest, /* The table we are inserting into */
  80314. Select *pSelect, /* A SELECT statement to use as the data source */
  80315. int onError, /* How to handle constraint errors */
  80316. int iDbDest /* The database of pDest */
  80317. ){
  80318. ExprList *pEList; /* The result set of the SELECT */
  80319. Table *pSrc; /* The table in the FROM clause of SELECT */
  80320. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  80321. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  80322. int i; /* Loop counter */
  80323. int iDbSrc; /* The database of pSrc */
  80324. int iSrc, iDest; /* Cursors from source and destination */
  80325. int addr1, addr2; /* Loop addresses */
  80326. int emptyDestTest; /* Address of test for empty pDest */
  80327. int emptySrcTest; /* Address of test for empty pSrc */
  80328. Vdbe *v; /* The VDBE we are building */
  80329. KeyInfo *pKey; /* Key information for an index */
  80330. int regAutoinc; /* Memory register used by AUTOINC */
  80331. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  80332. int regData, regRowid; /* Registers holding data and rowid */
  80333. if( pSelect==0 ){
  80334. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  80335. }
  80336. if( sqlite3TriggerList(pParse, pDest) ){
  80337. return 0; /* tab1 must not have triggers */
  80338. }
  80339. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80340. if( pDest->tabFlags & TF_Virtual ){
  80341. return 0; /* tab1 must not be a virtual table */
  80342. }
  80343. #endif
  80344. if( onError==OE_Default ){
  80345. onError = OE_Abort;
  80346. }
  80347. if( onError!=OE_Abort && onError!=OE_Rollback ){
  80348. return 0; /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
  80349. }
  80350. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  80351. if( pSelect->pSrc->nSrc!=1 ){
  80352. return 0; /* FROM clause must have exactly one term */
  80353. }
  80354. if( pSelect->pSrc->a[0].pSelect ){
  80355. return 0; /* FROM clause cannot contain a subquery */
  80356. }
  80357. if( pSelect->pWhere ){
  80358. return 0; /* SELECT may not have a WHERE clause */
  80359. }
  80360. if( pSelect->pOrderBy ){
  80361. return 0; /* SELECT may not have an ORDER BY clause */
  80362. }
  80363. /* Do not need to test for a HAVING clause. If HAVING is present but
  80364. ** there is no ORDER BY, we will get an error. */
  80365. if( pSelect->pGroupBy ){
  80366. return 0; /* SELECT may not have a GROUP BY clause */
  80367. }
  80368. if( pSelect->pLimit ){
  80369. return 0; /* SELECT may not have a LIMIT clause */
  80370. }
  80371. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  80372. if( pSelect->pPrior ){
  80373. return 0; /* SELECT may not be a compound query */
  80374. }
  80375. if( pSelect->selFlags & SF_Distinct ){
  80376. return 0; /* SELECT may not be DISTINCT */
  80377. }
  80378. pEList = pSelect->pEList;
  80379. assert( pEList!=0 );
  80380. if( pEList->nExpr!=1 ){
  80381. return 0; /* The result set must have exactly one column */
  80382. }
  80383. assert( pEList->a[0].pExpr );
  80384. if( pEList->a[0].pExpr->op!=TK_ALL ){
  80385. return 0; /* The result set must be the special operator "*" */
  80386. }
  80387. /* At this point we have established that the statement is of the
  80388. ** correct syntactic form to participate in this optimization. Now
  80389. ** we have to check the semantics.
  80390. */
  80391. pItem = pSelect->pSrc->a;
  80392. pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
  80393. if( pSrc==0 ){
  80394. return 0; /* FROM clause does not contain a real table */
  80395. }
  80396. if( pSrc==pDest ){
  80397. return 0; /* tab1 and tab2 may not be the same table */
  80398. }
  80399. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80400. if( pSrc->tabFlags & TF_Virtual ){
  80401. return 0; /* tab2 must not be a virtual table */
  80402. }
  80403. #endif
  80404. if( pSrc->pSelect ){
  80405. return 0; /* tab2 may not be a view */
  80406. }
  80407. if( pDest->nCol!=pSrc->nCol ){
  80408. return 0; /* Number of columns must be the same in tab1 and tab2 */
  80409. }
  80410. if( pDest->iPKey!=pSrc->iPKey ){
  80411. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  80412. }
  80413. for(i=0; i<pDest->nCol; i++){
  80414. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  80415. return 0; /* Affinity must be the same on all columns */
  80416. }
  80417. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  80418. return 0; /* Collating sequence must be the same on all columns */
  80419. }
  80420. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  80421. return 0; /* tab2 must be NOT NULL if tab1 is */
  80422. }
  80423. }
  80424. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  80425. if( pDestIdx->onError!=OE_None ){
  80426. destHasUniqueIdx = 1;
  80427. }
  80428. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  80429. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  80430. }
  80431. if( pSrcIdx==0 ){
  80432. return 0; /* pDestIdx has no corresponding index in pSrc */
  80433. }
  80434. }
  80435. #ifndef SQLITE_OMIT_CHECK
  80436. if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
  80437. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  80438. }
  80439. #endif
  80440. /* If we get this far, it means either:
  80441. **
  80442. ** * We can always do the transfer if the table contains an
  80443. ** an integer primary key
  80444. **
  80445. ** * We can conditionally do the transfer if the destination
  80446. ** table is empty.
  80447. */
  80448. #ifdef SQLITE_TEST
  80449. sqlite3_xferopt_count++;
  80450. #endif
  80451. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  80452. v = sqlite3GetVdbe(pParse);
  80453. sqlite3CodeVerifySchema(pParse, iDbSrc);
  80454. iSrc = pParse->nTab++;
  80455. iDest = pParse->nTab++;
  80456. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  80457. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  80458. if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
  80459. /* If tables do not have an INTEGER PRIMARY KEY and there
  80460. ** are indices to be copied and the destination is not empty,
  80461. ** we have to disallow the transfer optimization because the
  80462. ** the rowids might change which will mess up indexing.
  80463. **
  80464. ** Or if the destination has a UNIQUE index and is not empty,
  80465. ** we also disallow the transfer optimization because we cannot
  80466. ** insure that all entries in the union of DEST and SRC will be
  80467. ** unique.
  80468. */
  80469. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  80470. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  80471. sqlite3VdbeJumpHere(v, addr1);
  80472. }else{
  80473. emptyDestTest = 0;
  80474. }
  80475. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  80476. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  80477. regData = sqlite3GetTempReg(pParse);
  80478. regRowid = sqlite3GetTempReg(pParse);
  80479. if( pDest->iPKey>=0 ){
  80480. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  80481. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  80482. sqlite3HaltConstraint(
  80483. pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
  80484. sqlite3VdbeJumpHere(v, addr2);
  80485. autoIncStep(pParse, regAutoinc, regRowid);
  80486. }else if( pDest->pIndex==0 ){
  80487. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  80488. }else{
  80489. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  80490. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  80491. }
  80492. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  80493. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  80494. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  80495. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  80496. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  80497. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  80498. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  80499. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  80500. }
  80501. assert( pSrcIdx );
  80502. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  80503. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  80504. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  80505. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  80506. (char*)pKey, P4_KEYINFO_HANDOFF);
  80507. VdbeComment((v, "%s", pSrcIdx->zName));
  80508. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  80509. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  80510. (char*)pKey, P4_KEYINFO_HANDOFF);
  80511. VdbeComment((v, "%s", pDestIdx->zName));
  80512. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  80513. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  80514. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  80515. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  80516. sqlite3VdbeJumpHere(v, addr1);
  80517. }
  80518. sqlite3VdbeJumpHere(v, emptySrcTest);
  80519. sqlite3ReleaseTempReg(pParse, regRowid);
  80520. sqlite3ReleaseTempReg(pParse, regData);
  80521. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  80522. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  80523. if( emptyDestTest ){
  80524. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  80525. sqlite3VdbeJumpHere(v, emptyDestTest);
  80526. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  80527. return 0;
  80528. }else{
  80529. return 1;
  80530. }
  80531. }
  80532. #endif /* SQLITE_OMIT_XFER_OPT */
  80533. /************** End of insert.c **********************************************/
  80534. /************** Begin file legacy.c ******************************************/
  80535. /*
  80536. ** 2001 September 15
  80537. **
  80538. ** The author disclaims copyright to this source code. In place of
  80539. ** a legal notice, here is a blessing:
  80540. **
  80541. ** May you do good and not evil.
  80542. ** May you find forgiveness for yourself and forgive others.
  80543. ** May you share freely, never taking more than you give.
  80544. **
  80545. *************************************************************************
  80546. ** Main file for the SQLite library. The routines in this file
  80547. ** implement the programmer interface to the library. Routines in
  80548. ** other files are for internal use by SQLite and should not be
  80549. ** accessed by users of the library.
  80550. */
  80551. /*
  80552. ** Execute SQL code. Return one of the SQLITE_ success/failure
  80553. ** codes. Also write an error message into memory obtained from
  80554. ** malloc() and make *pzErrMsg point to that message.
  80555. **
  80556. ** If the SQL is a query, then for each row in the query result
  80557. ** the xCallback() function is called. pArg becomes the first
  80558. ** argument to xCallback(). If xCallback=NULL then no callback
  80559. ** is invoked, even for queries.
  80560. */
  80561. SQLITE_API int sqlite3_exec(
  80562. sqlite3 *db, /* The database on which the SQL executes */
  80563. const char *zSql, /* The SQL to be executed */
  80564. sqlite3_callback xCallback, /* Invoke this callback routine */
  80565. void *pArg, /* First argument to xCallback() */
  80566. char **pzErrMsg /* Write error messages here */
  80567. ){
  80568. int rc = SQLITE_OK; /* Return code */
  80569. const char *zLeftover; /* Tail of unprocessed SQL */
  80570. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  80571. char **azCols = 0; /* Names of result columns */
  80572. int nRetry = 0; /* Number of retry attempts */
  80573. int callbackIsInit; /* True if callback data is initialized */
  80574. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  80575. if( zSql==0 ) zSql = "";
  80576. sqlite3_mutex_enter(db->mutex);
  80577. sqlite3Error(db, SQLITE_OK, 0);
  80578. while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
  80579. int nCol;
  80580. char **azVals = 0;
  80581. pStmt = 0;
  80582. rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
  80583. assert( rc==SQLITE_OK || pStmt==0 );
  80584. if( rc!=SQLITE_OK ){
  80585. continue;
  80586. }
  80587. if( !pStmt ){
  80588. /* this happens for a comment or white-space */
  80589. zSql = zLeftover;
  80590. continue;
  80591. }
  80592. callbackIsInit = 0;
  80593. nCol = sqlite3_column_count(pStmt);
  80594. while( 1 ){
  80595. int i;
  80596. rc = sqlite3_step(pStmt);
  80597. /* Invoke the callback function if required */
  80598. if( xCallback && (SQLITE_ROW==rc ||
  80599. (SQLITE_DONE==rc && !callbackIsInit
  80600. && db->flags&SQLITE_NullCallback)) ){
  80601. if( !callbackIsInit ){
  80602. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  80603. if( azCols==0 ){
  80604. goto exec_out;
  80605. }
  80606. for(i=0; i<nCol; i++){
  80607. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  80608. /* sqlite3VdbeSetColName() installs column names as UTF8
  80609. ** strings so there is no way for sqlite3_column_name() to fail. */
  80610. assert( azCols[i]!=0 );
  80611. }
  80612. callbackIsInit = 1;
  80613. }
  80614. if( rc==SQLITE_ROW ){
  80615. azVals = &azCols[nCol];
  80616. for(i=0; i<nCol; i++){
  80617. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  80618. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  80619. db->mallocFailed = 1;
  80620. goto exec_out;
  80621. }
  80622. }
  80623. }
  80624. if( xCallback(pArg, nCol, azVals, azCols) ){
  80625. rc = SQLITE_ABORT;
  80626. sqlite3VdbeFinalize((Vdbe *)pStmt);
  80627. pStmt = 0;
  80628. sqlite3Error(db, SQLITE_ABORT, 0);
  80629. goto exec_out;
  80630. }
  80631. }
  80632. if( rc!=SQLITE_ROW ){
  80633. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  80634. pStmt = 0;
  80635. if( rc!=SQLITE_SCHEMA ){
  80636. nRetry = 0;
  80637. zSql = zLeftover;
  80638. while( sqlite3Isspace(zSql[0]) ) zSql++;
  80639. }
  80640. break;
  80641. }
  80642. }
  80643. sqlite3DbFree(db, azCols);
  80644. azCols = 0;
  80645. }
  80646. exec_out:
  80647. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  80648. sqlite3DbFree(db, azCols);
  80649. rc = sqlite3ApiExit(db, rc);
  80650. if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
  80651. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  80652. *pzErrMsg = sqlite3Malloc(nErrMsg);
  80653. if( *pzErrMsg ){
  80654. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  80655. }else{
  80656. rc = SQLITE_NOMEM;
  80657. sqlite3Error(db, SQLITE_NOMEM, 0);
  80658. }
  80659. }else if( pzErrMsg ){
  80660. *pzErrMsg = 0;
  80661. }
  80662. assert( (rc&db->errMask)==rc );
  80663. sqlite3_mutex_leave(db->mutex);
  80664. return rc;
  80665. }
  80666. /************** End of legacy.c **********************************************/
  80667. /************** Begin file loadext.c *****************************************/
  80668. /*
  80669. ** 2006 June 7
  80670. **
  80671. ** The author disclaims copyright to this source code. In place of
  80672. ** a legal notice, here is a blessing:
  80673. **
  80674. ** May you do good and not evil.
  80675. ** May you find forgiveness for yourself and forgive others.
  80676. ** May you share freely, never taking more than you give.
  80677. **
  80678. *************************************************************************
  80679. ** This file contains code used to dynamically load extensions into
  80680. ** the SQLite library.
  80681. */
  80682. #ifndef SQLITE_CORE
  80683. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  80684. #endif
  80685. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  80686. /************** Begin file sqlite3ext.h **************************************/
  80687. /*
  80688. ** 2006 June 7
  80689. **
  80690. ** The author disclaims copyright to this source code. In place of
  80691. ** a legal notice, here is a blessing:
  80692. **
  80693. ** May you do good and not evil.
  80694. ** May you find forgiveness for yourself and forgive others.
  80695. ** May you share freely, never taking more than you give.
  80696. **
  80697. *************************************************************************
  80698. ** This header file defines the SQLite interface for use by
  80699. ** shared libraries that want to be imported as extensions into
  80700. ** an SQLite instance. Shared libraries that intend to be loaded
  80701. ** as extensions by SQLite should #include this file instead of
  80702. ** sqlite3.h.
  80703. */
  80704. #ifndef _SQLITE3EXT_H_
  80705. #define _SQLITE3EXT_H_
  80706. typedef struct sqlite3_api_routines sqlite3_api_routines;
  80707. /*
  80708. ** The following structure holds pointers to all of the SQLite API
  80709. ** routines.
  80710. **
  80711. ** WARNING: In order to maintain backwards compatibility, add new
  80712. ** interfaces to the end of this structure only. If you insert new
  80713. ** interfaces in the middle of this structure, then older different
  80714. ** versions of SQLite will not be able to load each others' shared
  80715. ** libraries!
  80716. */
  80717. struct sqlite3_api_routines {
  80718. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  80719. int (*aggregate_count)(sqlite3_context*);
  80720. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  80721. int (*bind_double)(sqlite3_stmt*,int,double);
  80722. int (*bind_int)(sqlite3_stmt*,int,int);
  80723. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  80724. int (*bind_null)(sqlite3_stmt*,int);
  80725. int (*bind_parameter_count)(sqlite3_stmt*);
  80726. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  80727. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  80728. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  80729. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  80730. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  80731. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  80732. int (*busy_timeout)(sqlite3*,int ms);
  80733. int (*changes)(sqlite3*);
  80734. int (*close)(sqlite3*);
  80735. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
  80736. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
  80737. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  80738. int (*column_bytes)(sqlite3_stmt*,int iCol);
  80739. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  80740. int (*column_count)(sqlite3_stmt*pStmt);
  80741. const char * (*column_database_name)(sqlite3_stmt*,int);
  80742. const void * (*column_database_name16)(sqlite3_stmt*,int);
  80743. const char * (*column_decltype)(sqlite3_stmt*,int i);
  80744. const void * (*column_decltype16)(sqlite3_stmt*,int);
  80745. double (*column_double)(sqlite3_stmt*,int iCol);
  80746. int (*column_int)(sqlite3_stmt*,int iCol);
  80747. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  80748. const char * (*column_name)(sqlite3_stmt*,int);
  80749. const void * (*column_name16)(sqlite3_stmt*,int);
  80750. const char * (*column_origin_name)(sqlite3_stmt*,int);
  80751. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  80752. const char * (*column_table_name)(sqlite3_stmt*,int);
  80753. const void * (*column_table_name16)(sqlite3_stmt*,int);
  80754. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  80755. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  80756. int (*column_type)(sqlite3_stmt*,int iCol);
  80757. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  80758. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  80759. int (*complete)(const char*sql);
  80760. int (*complete16)(const void*sql);
  80761. int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
  80762. int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
  80763. int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
  80764. int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*));
  80765. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  80766. int (*data_count)(sqlite3_stmt*pStmt);
  80767. sqlite3 * (*db_handle)(sqlite3_stmt*);
  80768. int (*declare_vtab)(sqlite3*,const char*);
  80769. int (*enable_shared_cache)(int);
  80770. int (*errcode)(sqlite3*db);
  80771. const char * (*errmsg)(sqlite3*);
  80772. const void * (*errmsg16)(sqlite3*);
  80773. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  80774. int (*expired)(sqlite3_stmt*);
  80775. int (*finalize)(sqlite3_stmt*pStmt);
  80776. void (*free)(void*);
  80777. void (*free_table)(char**result);
  80778. int (*get_autocommit)(sqlite3*);
  80779. void * (*get_auxdata)(sqlite3_context*,int);
  80780. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  80781. int (*global_recover)(void);
  80782. void (*interruptx)(sqlite3*);
  80783. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  80784. const char * (*libversion)(void);
  80785. int (*libversion_number)(void);
  80786. void *(*malloc)(int);
  80787. char * (*mprintf)(const char*,...);
  80788. int (*open)(const char*,sqlite3**);
  80789. int (*open16)(const void*,sqlite3**);
  80790. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  80791. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  80792. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  80793. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  80794. void *(*realloc)(void*,int);
  80795. int (*reset)(sqlite3_stmt*pStmt);
  80796. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  80797. void (*result_double)(sqlite3_context*,double);
  80798. void (*result_error)(sqlite3_context*,const char*,int);
  80799. void (*result_error16)(sqlite3_context*,const void*,int);
  80800. void (*result_int)(sqlite3_context*,int);
  80801. void (*result_int64)(sqlite3_context*,sqlite_int64);
  80802. void (*result_null)(sqlite3_context*);
  80803. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  80804. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  80805. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  80806. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  80807. void (*result_value)(sqlite3_context*,sqlite3_value*);
  80808. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  80809. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
  80810. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  80811. char * (*snprintf)(int,char*,const char*,...);
  80812. int (*step)(sqlite3_stmt*);
  80813. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
  80814. void (*thread_cleanup)(void);
  80815. int (*total_changes)(sqlite3*);
  80816. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  80817. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  80818. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
  80819. void * (*user_data)(sqlite3_context*);
  80820. const void * (*value_blob)(sqlite3_value*);
  80821. int (*value_bytes)(sqlite3_value*);
  80822. int (*value_bytes16)(sqlite3_value*);
  80823. double (*value_double)(sqlite3_value*);
  80824. int (*value_int)(sqlite3_value*);
  80825. sqlite_int64 (*value_int64)(sqlite3_value*);
  80826. int (*value_numeric_type)(sqlite3_value*);
  80827. const unsigned char * (*value_text)(sqlite3_value*);
  80828. const void * (*value_text16)(sqlite3_value*);
  80829. const void * (*value_text16be)(sqlite3_value*);
  80830. const void * (*value_text16le)(sqlite3_value*);
  80831. int (*value_type)(sqlite3_value*);
  80832. char *(*vmprintf)(const char*,va_list);
  80833. /* Added ??? */
  80834. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  80835. /* Added by 3.3.13 */
  80836. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  80837. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  80838. int (*clear_bindings)(sqlite3_stmt*);
  80839. /* Added by 3.4.1 */
  80840. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
  80841. /* Added by 3.5.0 */
  80842. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  80843. int (*blob_bytes)(sqlite3_blob*);
  80844. int (*blob_close)(sqlite3_blob*);
  80845. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
  80846. int (*blob_read)(sqlite3_blob*,void*,int,int);
  80847. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  80848. int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
  80849. int (*file_control)(sqlite3*,const char*,int,void*);
  80850. sqlite3_int64 (*memory_highwater)(int);
  80851. sqlite3_int64 (*memory_used)(void);
  80852. sqlite3_mutex *(*mutex_alloc)(int);
  80853. void (*mutex_enter)(sqlite3_mutex*);
  80854. void (*mutex_free)(sqlite3_mutex*);
  80855. void (*mutex_leave)(sqlite3_mutex*);
  80856. int (*mutex_try)(sqlite3_mutex*);
  80857. int (*open_v2)(const char*,sqlite3**,int,const char*);
  80858. int (*release_memory)(int);
  80859. void (*result_error_nomem)(sqlite3_context*);
  80860. void (*result_error_toobig)(sqlite3_context*);
  80861. int (*sleep)(int);
  80862. void (*soft_heap_limit)(int);
  80863. sqlite3_vfs *(*vfs_find)(const char*);
  80864. int (*vfs_register)(sqlite3_vfs*,int);
  80865. int (*vfs_unregister)(sqlite3_vfs*);
  80866. int (*xthreadsafe)(void);
  80867. void (*result_zeroblob)(sqlite3_context*,int);
  80868. void (*result_error_code)(sqlite3_context*,int);
  80869. int (*test_control)(int, ...);
  80870. void (*randomness)(int,void*);
  80871. sqlite3 *(*context_db_handle)(sqlite3_context*);
  80872. int (*extended_result_codes)(sqlite3*,int);
  80873. int (*limit)(sqlite3*,int,int);
  80874. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  80875. const char *(*sql)(sqlite3_stmt*);
  80876. int (*status)(int,int*,int*,int);
  80877. int (*backup_finish)(sqlite3_backup*);
  80878. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  80879. int (*backup_pagecount)(sqlite3_backup*);
  80880. int (*backup_remaining)(sqlite3_backup*);
  80881. int (*backup_step)(sqlite3_backup*,int);
  80882. const char *(*compileoption_get)(int);
  80883. int (*compileoption_used)(const char*);
  80884. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*),void(*xDestroy)(void*));
  80885. int (*db_config)(sqlite3*,int,...);
  80886. sqlite3_mutex *(*db_mutex)(sqlite3*);
  80887. int (*db_status)(sqlite3*,int,int*,int*,int);
  80888. int (*extended_errcode)(sqlite3*);
  80889. void (*log)(int,const char*,...);
  80890. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  80891. const char *(*sourceid)(void);
  80892. int (*stmt_status)(sqlite3_stmt*,int,int);
  80893. int (*strnicmp)(const char*,const char*,int);
  80894. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  80895. int (*wal_autocheckpoint)(sqlite3*,int);
  80896. int (*wal_checkpoint)(sqlite3*,const char*);
  80897. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  80898. };
  80899. /*
  80900. ** The following macros redefine the API routines so that they are
  80901. ** redirected throught the global sqlite3_api structure.
  80902. **
  80903. ** This header file is also used by the loadext.c source file
  80904. ** (part of the main SQLite library - not an extension) so that
  80905. ** it can get access to the sqlite3_api_routines structure
  80906. ** definition. But the main library does not want to redefine
  80907. ** the API. So the redefinition macros are only valid if the
  80908. ** SQLITE_CORE macros is undefined.
  80909. */
  80910. #ifndef SQLITE_CORE
  80911. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  80912. #ifndef SQLITE_OMIT_DEPRECATED
  80913. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  80914. #endif
  80915. #define sqlite3_bind_blob sqlite3_api->bind_blob
  80916. #define sqlite3_bind_double sqlite3_api->bind_double
  80917. #define sqlite3_bind_int sqlite3_api->bind_int
  80918. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  80919. #define sqlite3_bind_null sqlite3_api->bind_null
  80920. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  80921. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  80922. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  80923. #define sqlite3_bind_text sqlite3_api->bind_text
  80924. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  80925. #define sqlite3_bind_value sqlite3_api->bind_value
  80926. #define sqlite3_busy_handler sqlite3_api->busy_handler
  80927. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  80928. #define sqlite3_changes sqlite3_api->changes
  80929. #define sqlite3_close sqlite3_api->close
  80930. #define sqlite3_collation_needed sqlite3_api->collation_needed
  80931. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  80932. #define sqlite3_column_blob sqlite3_api->column_blob
  80933. #define sqlite3_column_bytes sqlite3_api->column_bytes
  80934. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  80935. #define sqlite3_column_count sqlite3_api->column_count
  80936. #define sqlite3_column_database_name sqlite3_api->column_database_name
  80937. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  80938. #define sqlite3_column_decltype sqlite3_api->column_decltype
  80939. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  80940. #define sqlite3_column_double sqlite3_api->column_double
  80941. #define sqlite3_column_int sqlite3_api->column_int
  80942. #define sqlite3_column_int64 sqlite3_api->column_int64
  80943. #define sqlite3_column_name sqlite3_api->column_name
  80944. #define sqlite3_column_name16 sqlite3_api->column_name16
  80945. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  80946. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  80947. #define sqlite3_column_table_name sqlite3_api->column_table_name
  80948. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  80949. #define sqlite3_column_text sqlite3_api->column_text
  80950. #define sqlite3_column_text16 sqlite3_api->column_text16
  80951. #define sqlite3_column_type sqlite3_api->column_type
  80952. #define sqlite3_column_value sqlite3_api->column_value
  80953. #define sqlite3_commit_hook sqlite3_api->commit_hook
  80954. #define sqlite3_complete sqlite3_api->complete
  80955. #define sqlite3_complete16 sqlite3_api->complete16
  80956. #define sqlite3_create_collation sqlite3_api->create_collation
  80957. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  80958. #define sqlite3_create_function sqlite3_api->create_function
  80959. #define sqlite3_create_function16 sqlite3_api->create_function16
  80960. #define sqlite3_create_module sqlite3_api->create_module
  80961. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  80962. #define sqlite3_data_count sqlite3_api->data_count
  80963. #define sqlite3_db_handle sqlite3_api->db_handle
  80964. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  80965. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  80966. #define sqlite3_errcode sqlite3_api->errcode
  80967. #define sqlite3_errmsg sqlite3_api->errmsg
  80968. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  80969. #define sqlite3_exec sqlite3_api->exec
  80970. #ifndef SQLITE_OMIT_DEPRECATED
  80971. #define sqlite3_expired sqlite3_api->expired
  80972. #endif
  80973. #define sqlite3_finalize sqlite3_api->finalize
  80974. #define sqlite3_free sqlite3_api->free
  80975. #define sqlite3_free_table sqlite3_api->free_table
  80976. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  80977. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  80978. #define sqlite3_get_table sqlite3_api->get_table
  80979. #ifndef SQLITE_OMIT_DEPRECATED
  80980. #define sqlite3_global_recover sqlite3_api->global_recover
  80981. #endif
  80982. #define sqlite3_interrupt sqlite3_api->interruptx
  80983. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  80984. #define sqlite3_libversion sqlite3_api->libversion
  80985. #define sqlite3_libversion_number sqlite3_api->libversion_number
  80986. #define sqlite3_malloc sqlite3_api->malloc
  80987. #define sqlite3_mprintf sqlite3_api->mprintf
  80988. #define sqlite3_open sqlite3_api->open
  80989. #define sqlite3_open16 sqlite3_api->open16
  80990. #define sqlite3_prepare sqlite3_api->prepare
  80991. #define sqlite3_prepare16 sqlite3_api->prepare16
  80992. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  80993. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  80994. #define sqlite3_profile sqlite3_api->profile
  80995. #define sqlite3_progress_handler sqlite3_api->progress_handler
  80996. #define sqlite3_realloc sqlite3_api->realloc
  80997. #define sqlite3_reset sqlite3_api->reset
  80998. #define sqlite3_result_blob sqlite3_api->result_blob
  80999. #define sqlite3_result_double sqlite3_api->result_double
  81000. #define sqlite3_result_error sqlite3_api->result_error
  81001. #define sqlite3_result_error16 sqlite3_api->result_error16
  81002. #define sqlite3_result_int sqlite3_api->result_int
  81003. #define sqlite3_result_int64 sqlite3_api->result_int64
  81004. #define sqlite3_result_null sqlite3_api->result_null
  81005. #define sqlite3_result_text sqlite3_api->result_text
  81006. #define sqlite3_result_text16 sqlite3_api->result_text16
  81007. #define sqlite3_result_text16be sqlite3_api->result_text16be
  81008. #define sqlite3_result_text16le sqlite3_api->result_text16le
  81009. #define sqlite3_result_value sqlite3_api->result_value
  81010. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  81011. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  81012. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  81013. #define sqlite3_snprintf sqlite3_api->snprintf
  81014. #define sqlite3_step sqlite3_api->step
  81015. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  81016. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  81017. #define sqlite3_total_changes sqlite3_api->total_changes
  81018. #define sqlite3_trace sqlite3_api->trace
  81019. #ifndef SQLITE_OMIT_DEPRECATED
  81020. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  81021. #endif
  81022. #define sqlite3_update_hook sqlite3_api->update_hook
  81023. #define sqlite3_user_data sqlite3_api->user_data
  81024. #define sqlite3_value_blob sqlite3_api->value_blob
  81025. #define sqlite3_value_bytes sqlite3_api->value_bytes
  81026. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  81027. #define sqlite3_value_double sqlite3_api->value_double
  81028. #define sqlite3_value_int sqlite3_api->value_int
  81029. #define sqlite3_value_int64 sqlite3_api->value_int64
  81030. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  81031. #define sqlite3_value_text sqlite3_api->value_text
  81032. #define sqlite3_value_text16 sqlite3_api->value_text16
  81033. #define sqlite3_value_text16be sqlite3_api->value_text16be
  81034. #define sqlite3_value_text16le sqlite3_api->value_text16le
  81035. #define sqlite3_value_type sqlite3_api->value_type
  81036. #define sqlite3_vmprintf sqlite3_api->vmprintf
  81037. #define sqlite3_overload_function sqlite3_api->overload_function
  81038. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  81039. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  81040. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  81041. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  81042. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  81043. #define sqlite3_blob_close sqlite3_api->blob_close
  81044. #define sqlite3_blob_open sqlite3_api->blob_open
  81045. #define sqlite3_blob_read sqlite3_api->blob_read
  81046. #define sqlite3_blob_write sqlite3_api->blob_write
  81047. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  81048. #define sqlite3_file_control sqlite3_api->file_control
  81049. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  81050. #define sqlite3_memory_used sqlite3_api->memory_used
  81051. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  81052. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  81053. #define sqlite3_mutex_free sqlite3_api->mutex_free
  81054. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  81055. #define sqlite3_mutex_try sqlite3_api->mutex_try
  81056. #define sqlite3_open_v2 sqlite3_api->open_v2
  81057. #define sqlite3_release_memory sqlite3_api->release_memory
  81058. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  81059. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  81060. #define sqlite3_sleep sqlite3_api->sleep
  81061. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  81062. #define sqlite3_vfs_find sqlite3_api->vfs_find
  81063. #define sqlite3_vfs_register sqlite3_api->vfs_register
  81064. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  81065. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  81066. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  81067. #define sqlite3_result_error_code sqlite3_api->result_error_code
  81068. #define sqlite3_test_control sqlite3_api->test_control
  81069. #define sqlite3_randomness sqlite3_api->randomness
  81070. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  81071. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  81072. #define sqlite3_limit sqlite3_api->limit
  81073. #define sqlite3_next_stmt sqlite3_api->next_stmt
  81074. #define sqlite3_sql sqlite3_api->sql
  81075. #define sqlite3_status sqlite3_api->status
  81076. #define sqlite3_backup_finish sqlite3_api->backup_finish
  81077. #define sqlite3_backup_init sqlite3_api->backup_init
  81078. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  81079. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  81080. #define sqlite3_backup_step sqlite3_api->backup_step
  81081. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  81082. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  81083. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  81084. #define sqlite3_db_config sqlite3_api->db_config
  81085. #define sqlite3_db_mutex sqlite3_api->db_mutex
  81086. #define sqlite3_db_status sqlite3_api->db_status
  81087. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  81088. #define sqlite3_log sqlite3_api->log
  81089. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  81090. #define sqlite3_sourceid sqlite3_api->sourceid
  81091. #define sqlite3_stmt_status sqlite3_api->stmt_status
  81092. #define sqlite3_strnicmp sqlite3_api->strnicmp
  81093. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  81094. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  81095. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  81096. #define sqlite3_wal_hook sqlite3_api->wal_hook
  81097. #endif /* SQLITE_CORE */
  81098. #define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0;
  81099. #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v;
  81100. #endif /* _SQLITE3EXT_H_ */
  81101. /************** End of sqlite3ext.h ******************************************/
  81102. /************** Continuing where we left off in loadext.c ********************/
  81103. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  81104. /*
  81105. ** Some API routines are omitted when various features are
  81106. ** excluded from a build of SQLite. Substitute a NULL pointer
  81107. ** for any missing APIs.
  81108. */
  81109. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  81110. # define sqlite3_column_database_name 0
  81111. # define sqlite3_column_database_name16 0
  81112. # define sqlite3_column_table_name 0
  81113. # define sqlite3_column_table_name16 0
  81114. # define sqlite3_column_origin_name 0
  81115. # define sqlite3_column_origin_name16 0
  81116. # define sqlite3_table_column_metadata 0
  81117. #endif
  81118. #ifdef SQLITE_OMIT_AUTHORIZATION
  81119. # define sqlite3_set_authorizer 0
  81120. #endif
  81121. #ifdef SQLITE_OMIT_UTF16
  81122. # define sqlite3_bind_text16 0
  81123. # define sqlite3_collation_needed16 0
  81124. # define sqlite3_column_decltype16 0
  81125. # define sqlite3_column_name16 0
  81126. # define sqlite3_column_text16 0
  81127. # define sqlite3_complete16 0
  81128. # define sqlite3_create_collation16 0
  81129. # define sqlite3_create_function16 0
  81130. # define sqlite3_errmsg16 0
  81131. # define sqlite3_open16 0
  81132. # define sqlite3_prepare16 0
  81133. # define sqlite3_prepare16_v2 0
  81134. # define sqlite3_result_error16 0
  81135. # define sqlite3_result_text16 0
  81136. # define sqlite3_result_text16be 0
  81137. # define sqlite3_result_text16le 0
  81138. # define sqlite3_value_text16 0
  81139. # define sqlite3_value_text16be 0
  81140. # define sqlite3_value_text16le 0
  81141. # define sqlite3_column_database_name16 0
  81142. # define sqlite3_column_table_name16 0
  81143. # define sqlite3_column_origin_name16 0
  81144. #endif
  81145. #ifdef SQLITE_OMIT_COMPLETE
  81146. # define sqlite3_complete 0
  81147. # define sqlite3_complete16 0
  81148. #endif
  81149. #ifdef SQLITE_OMIT_DECLTYPE
  81150. # define sqlite3_column_decltype16 0
  81151. # define sqlite3_column_decltype 0
  81152. #endif
  81153. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  81154. # define sqlite3_progress_handler 0
  81155. #endif
  81156. #ifdef SQLITE_OMIT_VIRTUALTABLE
  81157. # define sqlite3_create_module 0
  81158. # define sqlite3_create_module_v2 0
  81159. # define sqlite3_declare_vtab 0
  81160. #endif
  81161. #ifdef SQLITE_OMIT_SHARED_CACHE
  81162. # define sqlite3_enable_shared_cache 0
  81163. #endif
  81164. #ifdef SQLITE_OMIT_TRACE
  81165. # define sqlite3_profile 0
  81166. # define sqlite3_trace 0
  81167. #endif
  81168. #ifdef SQLITE_OMIT_GET_TABLE
  81169. # define sqlite3_free_table 0
  81170. # define sqlite3_get_table 0
  81171. #endif
  81172. #ifdef SQLITE_OMIT_INCRBLOB
  81173. #define sqlite3_bind_zeroblob 0
  81174. #define sqlite3_blob_bytes 0
  81175. #define sqlite3_blob_close 0
  81176. #define sqlite3_blob_open 0
  81177. #define sqlite3_blob_read 0
  81178. #define sqlite3_blob_write 0
  81179. #endif
  81180. /*
  81181. ** The following structure contains pointers to all SQLite API routines.
  81182. ** A pointer to this structure is passed into extensions when they are
  81183. ** loaded so that the extension can make calls back into the SQLite
  81184. ** library.
  81185. **
  81186. ** When adding new APIs, add them to the bottom of this structure
  81187. ** in order to preserve backwards compatibility.
  81188. **
  81189. ** Extensions that use newer APIs should first call the
  81190. ** sqlite3_libversion_number() to make sure that the API they
  81191. ** intend to use is supported by the library. Extensions should
  81192. ** also check to make sure that the pointer to the function is
  81193. ** not NULL before calling it.
  81194. */
  81195. static const sqlite3_api_routines sqlite3Apis = {
  81196. sqlite3_aggregate_context,
  81197. #ifndef SQLITE_OMIT_DEPRECATED
  81198. sqlite3_aggregate_count,
  81199. #else
  81200. 0,
  81201. #endif
  81202. sqlite3_bind_blob,
  81203. sqlite3_bind_double,
  81204. sqlite3_bind_int,
  81205. sqlite3_bind_int64,
  81206. sqlite3_bind_null,
  81207. sqlite3_bind_parameter_count,
  81208. sqlite3_bind_parameter_index,
  81209. sqlite3_bind_parameter_name,
  81210. sqlite3_bind_text,
  81211. sqlite3_bind_text16,
  81212. sqlite3_bind_value,
  81213. sqlite3_busy_handler,
  81214. sqlite3_busy_timeout,
  81215. sqlite3_changes,
  81216. sqlite3_close,
  81217. sqlite3_collation_needed,
  81218. sqlite3_collation_needed16,
  81219. sqlite3_column_blob,
  81220. sqlite3_column_bytes,
  81221. sqlite3_column_bytes16,
  81222. sqlite3_column_count,
  81223. sqlite3_column_database_name,
  81224. sqlite3_column_database_name16,
  81225. sqlite3_column_decltype,
  81226. sqlite3_column_decltype16,
  81227. sqlite3_column_double,
  81228. sqlite3_column_int,
  81229. sqlite3_column_int64,
  81230. sqlite3_column_name,
  81231. sqlite3_column_name16,
  81232. sqlite3_column_origin_name,
  81233. sqlite3_column_origin_name16,
  81234. sqlite3_column_table_name,
  81235. sqlite3_column_table_name16,
  81236. sqlite3_column_text,
  81237. sqlite3_column_text16,
  81238. sqlite3_column_type,
  81239. sqlite3_column_value,
  81240. sqlite3_commit_hook,
  81241. sqlite3_complete,
  81242. sqlite3_complete16,
  81243. sqlite3_create_collation,
  81244. sqlite3_create_collation16,
  81245. sqlite3_create_function,
  81246. sqlite3_create_function16,
  81247. sqlite3_create_module,
  81248. sqlite3_data_count,
  81249. sqlite3_db_handle,
  81250. sqlite3_declare_vtab,
  81251. sqlite3_enable_shared_cache,
  81252. sqlite3_errcode,
  81253. sqlite3_errmsg,
  81254. sqlite3_errmsg16,
  81255. sqlite3_exec,
  81256. #ifndef SQLITE_OMIT_DEPRECATED
  81257. sqlite3_expired,
  81258. #else
  81259. 0,
  81260. #endif
  81261. sqlite3_finalize,
  81262. sqlite3_free,
  81263. sqlite3_free_table,
  81264. sqlite3_get_autocommit,
  81265. sqlite3_get_auxdata,
  81266. sqlite3_get_table,
  81267. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  81268. sqlite3_interrupt,
  81269. sqlite3_last_insert_rowid,
  81270. sqlite3_libversion,
  81271. sqlite3_libversion_number,
  81272. sqlite3_malloc,
  81273. sqlite3_mprintf,
  81274. sqlite3_open,
  81275. sqlite3_open16,
  81276. sqlite3_prepare,
  81277. sqlite3_prepare16,
  81278. sqlite3_profile,
  81279. sqlite3_progress_handler,
  81280. sqlite3_realloc,
  81281. sqlite3_reset,
  81282. sqlite3_result_blob,
  81283. sqlite3_result_double,
  81284. sqlite3_result_error,
  81285. sqlite3_result_error16,
  81286. sqlite3_result_int,
  81287. sqlite3_result_int64,
  81288. sqlite3_result_null,
  81289. sqlite3_result_text,
  81290. sqlite3_result_text16,
  81291. sqlite3_result_text16be,
  81292. sqlite3_result_text16le,
  81293. sqlite3_result_value,
  81294. sqlite3_rollback_hook,
  81295. sqlite3_set_authorizer,
  81296. sqlite3_set_auxdata,
  81297. sqlite3_snprintf,
  81298. sqlite3_step,
  81299. sqlite3_table_column_metadata,
  81300. #ifndef SQLITE_OMIT_DEPRECATED
  81301. sqlite3_thread_cleanup,
  81302. #else
  81303. 0,
  81304. #endif
  81305. sqlite3_total_changes,
  81306. sqlite3_trace,
  81307. #ifndef SQLITE_OMIT_DEPRECATED
  81308. sqlite3_transfer_bindings,
  81309. #else
  81310. 0,
  81311. #endif
  81312. sqlite3_update_hook,
  81313. sqlite3_user_data,
  81314. sqlite3_value_blob,
  81315. sqlite3_value_bytes,
  81316. sqlite3_value_bytes16,
  81317. sqlite3_value_double,
  81318. sqlite3_value_int,
  81319. sqlite3_value_int64,
  81320. sqlite3_value_numeric_type,
  81321. sqlite3_value_text,
  81322. sqlite3_value_text16,
  81323. sqlite3_value_text16be,
  81324. sqlite3_value_text16le,
  81325. sqlite3_value_type,
  81326. sqlite3_vmprintf,
  81327. /*
  81328. ** The original API set ends here. All extensions can call any
  81329. ** of the APIs above provided that the pointer is not NULL. But
  81330. ** before calling APIs that follow, extension should check the
  81331. ** sqlite3_libversion_number() to make sure they are dealing with
  81332. ** a library that is new enough to support that API.
  81333. *************************************************************************
  81334. */
  81335. sqlite3_overload_function,
  81336. /*
  81337. ** Added after 3.3.13
  81338. */
  81339. sqlite3_prepare_v2,
  81340. sqlite3_prepare16_v2,
  81341. sqlite3_clear_bindings,
  81342. /*
  81343. ** Added for 3.4.1
  81344. */
  81345. sqlite3_create_module_v2,
  81346. /*
  81347. ** Added for 3.5.0
  81348. */
  81349. sqlite3_bind_zeroblob,
  81350. sqlite3_blob_bytes,
  81351. sqlite3_blob_close,
  81352. sqlite3_blob_open,
  81353. sqlite3_blob_read,
  81354. sqlite3_blob_write,
  81355. sqlite3_create_collation_v2,
  81356. sqlite3_file_control,
  81357. sqlite3_memory_highwater,
  81358. sqlite3_memory_used,
  81359. #ifdef SQLITE_MUTEX_OMIT
  81360. 0,
  81361. 0,
  81362. 0,
  81363. 0,
  81364. 0,
  81365. #else
  81366. sqlite3_mutex_alloc,
  81367. sqlite3_mutex_enter,
  81368. sqlite3_mutex_free,
  81369. sqlite3_mutex_leave,
  81370. sqlite3_mutex_try,
  81371. #endif
  81372. sqlite3_open_v2,
  81373. sqlite3_release_memory,
  81374. sqlite3_result_error_nomem,
  81375. sqlite3_result_error_toobig,
  81376. sqlite3_sleep,
  81377. sqlite3_soft_heap_limit,
  81378. sqlite3_vfs_find,
  81379. sqlite3_vfs_register,
  81380. sqlite3_vfs_unregister,
  81381. /*
  81382. ** Added for 3.5.8
  81383. */
  81384. sqlite3_threadsafe,
  81385. sqlite3_result_zeroblob,
  81386. sqlite3_result_error_code,
  81387. sqlite3_test_control,
  81388. sqlite3_randomness,
  81389. sqlite3_context_db_handle,
  81390. /*
  81391. ** Added for 3.6.0
  81392. */
  81393. sqlite3_extended_result_codes,
  81394. sqlite3_limit,
  81395. sqlite3_next_stmt,
  81396. sqlite3_sql,
  81397. sqlite3_status,
  81398. /*
  81399. ** Added for 3.7.4
  81400. */
  81401. sqlite3_backup_finish,
  81402. sqlite3_backup_init,
  81403. sqlite3_backup_pagecount,
  81404. sqlite3_backup_remaining,
  81405. sqlite3_backup_step,
  81406. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  81407. sqlite3_compileoption_get,
  81408. sqlite3_compileoption_used,
  81409. #else
  81410. 0,
  81411. 0,
  81412. #endif
  81413. sqlite3_create_function_v2,
  81414. sqlite3_db_config,
  81415. sqlite3_db_mutex,
  81416. sqlite3_db_status,
  81417. sqlite3_extended_errcode,
  81418. sqlite3_log,
  81419. sqlite3_soft_heap_limit64,
  81420. sqlite3_sourceid,
  81421. sqlite3_stmt_status,
  81422. sqlite3_strnicmp,
  81423. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  81424. sqlite3_unlock_notify,
  81425. #else
  81426. 0,
  81427. #endif
  81428. #ifndef SQLITE_OMIT_WAL
  81429. sqlite3_wal_autocheckpoint,
  81430. sqlite3_wal_checkpoint,
  81431. sqlite3_wal_hook,
  81432. #else
  81433. 0,
  81434. 0,
  81435. 0,
  81436. #endif
  81437. };
  81438. /*
  81439. ** Attempt to load an SQLite extension library contained in the file
  81440. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  81441. ** default entry point name (sqlite3_extension_init) is used. Use
  81442. ** of the default name is recommended.
  81443. **
  81444. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  81445. **
  81446. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  81447. ** error message text. The calling function should free this memory
  81448. ** by calling sqlite3DbFree(db, ).
  81449. */
  81450. static int sqlite3LoadExtension(
  81451. sqlite3 *db, /* Load the extension into this database connection */
  81452. const char *zFile, /* Name of the shared library containing extension */
  81453. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  81454. char **pzErrMsg /* Put error message here if not 0 */
  81455. ){
  81456. sqlite3_vfs *pVfs = db->pVfs;
  81457. void *handle;
  81458. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  81459. char *zErrmsg = 0;
  81460. void **aHandle;
  81461. const int nMsg = 300;
  81462. if( pzErrMsg ) *pzErrMsg = 0;
  81463. /* Ticket #1863. To avoid a creating security problems for older
  81464. ** applications that relink against newer versions of SQLite, the
  81465. ** ability to run load_extension is turned off by default. One
  81466. ** must call sqlite3_enable_load_extension() to turn on extension
  81467. ** loading. Otherwise you get the following error.
  81468. */
  81469. if( (db->flags & SQLITE_LoadExtension)==0 ){
  81470. if( pzErrMsg ){
  81471. *pzErrMsg = sqlite3_mprintf("not authorized");
  81472. }
  81473. return SQLITE_ERROR;
  81474. }
  81475. if( zProc==0 ){
  81476. zProc = "sqlite3_extension_init";
  81477. }
  81478. handle = sqlite3OsDlOpen(pVfs, zFile);
  81479. if( handle==0 ){
  81480. if( pzErrMsg ){
  81481. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  81482. if( zErrmsg ){
  81483. sqlite3_snprintf(nMsg, zErrmsg,
  81484. "unable to open shared library [%s]", zFile);
  81485. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  81486. }
  81487. }
  81488. return SQLITE_ERROR;
  81489. }
  81490. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  81491. sqlite3OsDlSym(pVfs, handle, zProc);
  81492. if( xInit==0 ){
  81493. if( pzErrMsg ){
  81494. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  81495. if( zErrmsg ){
  81496. sqlite3_snprintf(nMsg, zErrmsg,
  81497. "no entry point [%s] in shared library [%s]", zProc,zFile);
  81498. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  81499. }
  81500. sqlite3OsDlClose(pVfs, handle);
  81501. }
  81502. return SQLITE_ERROR;
  81503. }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  81504. if( pzErrMsg ){
  81505. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  81506. }
  81507. sqlite3_free(zErrmsg);
  81508. sqlite3OsDlClose(pVfs, handle);
  81509. return SQLITE_ERROR;
  81510. }
  81511. /* Append the new shared library handle to the db->aExtension array. */
  81512. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  81513. if( aHandle==0 ){
  81514. return SQLITE_NOMEM;
  81515. }
  81516. if( db->nExtension>0 ){
  81517. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  81518. }
  81519. sqlite3DbFree(db, db->aExtension);
  81520. db->aExtension = aHandle;
  81521. db->aExtension[db->nExtension++] = handle;
  81522. return SQLITE_OK;
  81523. }
  81524. SQLITE_API int sqlite3_load_extension(
  81525. sqlite3 *db, /* Load the extension into this database connection */
  81526. const char *zFile, /* Name of the shared library containing extension */
  81527. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  81528. char **pzErrMsg /* Put error message here if not 0 */
  81529. ){
  81530. int rc;
  81531. sqlite3_mutex_enter(db->mutex);
  81532. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  81533. rc = sqlite3ApiExit(db, rc);
  81534. sqlite3_mutex_leave(db->mutex);
  81535. return rc;
  81536. }
  81537. /*
  81538. ** Call this routine when the database connection is closing in order
  81539. ** to clean up loaded extensions
  81540. */
  81541. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  81542. int i;
  81543. assert( sqlite3_mutex_held(db->mutex) );
  81544. for(i=0; i<db->nExtension; i++){
  81545. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  81546. }
  81547. sqlite3DbFree(db, db->aExtension);
  81548. }
  81549. /*
  81550. ** Enable or disable extension loading. Extension loading is disabled by
  81551. ** default so as not to open security holes in older applications.
  81552. */
  81553. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  81554. sqlite3_mutex_enter(db->mutex);
  81555. if( onoff ){
  81556. db->flags |= SQLITE_LoadExtension;
  81557. }else{
  81558. db->flags &= ~SQLITE_LoadExtension;
  81559. }
  81560. sqlite3_mutex_leave(db->mutex);
  81561. return SQLITE_OK;
  81562. }
  81563. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  81564. /*
  81565. ** The auto-extension code added regardless of whether or not extension
  81566. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  81567. ** code if regular extension loading is not available. This is that
  81568. ** dummy pointer.
  81569. */
  81570. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  81571. static const sqlite3_api_routines sqlite3Apis = { 0 };
  81572. #endif
  81573. /*
  81574. ** The following object holds the list of automatically loaded
  81575. ** extensions.
  81576. **
  81577. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  81578. ** mutex must be held while accessing this list.
  81579. */
  81580. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  81581. static SQLITE_WSD struct sqlite3AutoExtList {
  81582. int nExt; /* Number of entries in aExt[] */
  81583. void (**aExt)(void); /* Pointers to the extension init functions */
  81584. } sqlite3Autoext = { 0, 0 };
  81585. /* The "wsdAutoext" macro will resolve to the autoextension
  81586. ** state vector. If writable static data is unsupported on the target,
  81587. ** we have to locate the state vector at run-time. In the more common
  81588. ** case where writable static data is supported, wsdStat can refer directly
  81589. ** to the "sqlite3Autoext" state vector declared above.
  81590. */
  81591. #ifdef SQLITE_OMIT_WSD
  81592. # define wsdAutoextInit \
  81593. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  81594. # define wsdAutoext x[0]
  81595. #else
  81596. # define wsdAutoextInit
  81597. # define wsdAutoext sqlite3Autoext
  81598. #endif
  81599. /*
  81600. ** Register a statically linked extension that is automatically
  81601. ** loaded by every new database connection.
  81602. */
  81603. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  81604. int rc = SQLITE_OK;
  81605. #ifndef SQLITE_OMIT_AUTOINIT
  81606. rc = sqlite3_initialize();
  81607. if( rc ){
  81608. return rc;
  81609. }else
  81610. #endif
  81611. {
  81612. int i;
  81613. #if SQLITE_THREADSAFE
  81614. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  81615. #endif
  81616. wsdAutoextInit;
  81617. sqlite3_mutex_enter(mutex);
  81618. for(i=0; i<wsdAutoext.nExt; i++){
  81619. if( wsdAutoext.aExt[i]==xInit ) break;
  81620. }
  81621. if( i==wsdAutoext.nExt ){
  81622. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  81623. void (**aNew)(void);
  81624. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  81625. if( aNew==0 ){
  81626. rc = SQLITE_NOMEM;
  81627. }else{
  81628. wsdAutoext.aExt = aNew;
  81629. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  81630. wsdAutoext.nExt++;
  81631. }
  81632. }
  81633. sqlite3_mutex_leave(mutex);
  81634. assert( (rc&0xff)==rc );
  81635. return rc;
  81636. }
  81637. }
  81638. /*
  81639. ** Reset the automatic extension loading mechanism.
  81640. */
  81641. SQLITE_API void sqlite3_reset_auto_extension(void){
  81642. #ifndef SQLITE_OMIT_AUTOINIT
  81643. if( sqlite3_initialize()==SQLITE_OK )
  81644. #endif
  81645. {
  81646. #if SQLITE_THREADSAFE
  81647. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  81648. #endif
  81649. wsdAutoextInit;
  81650. sqlite3_mutex_enter(mutex);
  81651. sqlite3_free(wsdAutoext.aExt);
  81652. wsdAutoext.aExt = 0;
  81653. wsdAutoext.nExt = 0;
  81654. sqlite3_mutex_leave(mutex);
  81655. }
  81656. }
  81657. /*
  81658. ** Load all automatic extensions.
  81659. **
  81660. ** If anything goes wrong, set an error in the database connection.
  81661. */
  81662. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  81663. int i;
  81664. int go = 1;
  81665. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  81666. wsdAutoextInit;
  81667. if( wsdAutoext.nExt==0 ){
  81668. /* Common case: early out without every having to acquire a mutex */
  81669. return;
  81670. }
  81671. for(i=0; go; i++){
  81672. char *zErrmsg;
  81673. #if SQLITE_THREADSAFE
  81674. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  81675. #endif
  81676. sqlite3_mutex_enter(mutex);
  81677. if( i>=wsdAutoext.nExt ){
  81678. xInit = 0;
  81679. go = 0;
  81680. }else{
  81681. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  81682. wsdAutoext.aExt[i];
  81683. }
  81684. sqlite3_mutex_leave(mutex);
  81685. zErrmsg = 0;
  81686. if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
  81687. sqlite3Error(db, SQLITE_ERROR,
  81688. "automatic extension loading failed: %s", zErrmsg);
  81689. go = 0;
  81690. }
  81691. sqlite3_free(zErrmsg);
  81692. }
  81693. }
  81694. /************** End of loadext.c *********************************************/
  81695. /************** Begin file pragma.c ******************************************/
  81696. /*
  81697. ** 2003 April 6
  81698. **
  81699. ** The author disclaims copyright to this source code. In place of
  81700. ** a legal notice, here is a blessing:
  81701. **
  81702. ** May you do good and not evil.
  81703. ** May you find forgiveness for yourself and forgive others.
  81704. ** May you share freely, never taking more than you give.
  81705. **
  81706. *************************************************************************
  81707. ** This file contains code used to implement the PRAGMA command.
  81708. */
  81709. /* Ignore this whole file if pragmas are disabled
  81710. */
  81711. #if !defined(SQLITE_OMIT_PRAGMA)
  81712. /*
  81713. ** Interpret the given string as a safety level. Return 0 for OFF,
  81714. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  81715. ** unrecognized string argument.
  81716. **
  81717. ** Note that the values returned are one less that the values that
  81718. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  81719. ** to support legacy SQL code. The safety level used to be boolean
  81720. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  81721. */
  81722. static u8 getSafetyLevel(const char *z){
  81723. /* 123456789 123456789 */
  81724. static const char zText[] = "onoffalseyestruefull";
  81725. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  81726. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  81727. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  81728. int i, n;
  81729. if( sqlite3Isdigit(*z) ){
  81730. return (u8)sqlite3Atoi(z);
  81731. }
  81732. n = sqlite3Strlen30(z);
  81733. for(i=0; i<ArraySize(iLength); i++){
  81734. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  81735. return iValue[i];
  81736. }
  81737. }
  81738. return 1;
  81739. }
  81740. /*
  81741. ** Interpret the given string as a boolean value.
  81742. */
  81743. static u8 getBoolean(const char *z){
  81744. return getSafetyLevel(z)&1;
  81745. }
  81746. /*
  81747. ** Interpret the given string as a locking mode value.
  81748. */
  81749. static int getLockingMode(const char *z){
  81750. if( z ){
  81751. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  81752. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  81753. }
  81754. return PAGER_LOCKINGMODE_QUERY;
  81755. }
  81756. #ifndef SQLITE_OMIT_AUTOVACUUM
  81757. /*
  81758. ** Interpret the given string as an auto-vacuum mode value.
  81759. **
  81760. ** The following strings, "none", "full" and "incremental" are
  81761. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  81762. */
  81763. static int getAutoVacuum(const char *z){
  81764. int i;
  81765. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  81766. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  81767. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  81768. i = sqlite3Atoi(z);
  81769. return (u8)((i>=0&&i<=2)?i:0);
  81770. }
  81771. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  81772. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  81773. /*
  81774. ** Interpret the given string as a temp db location. Return 1 for file
  81775. ** backed temporary databases, 2 for the Red-Black tree in memory database
  81776. ** and 0 to use the compile-time default.
  81777. */
  81778. static int getTempStore(const char *z){
  81779. if( z[0]>='0' && z[0]<='2' ){
  81780. return z[0] - '0';
  81781. }else if( sqlite3StrICmp(z, "file")==0 ){
  81782. return 1;
  81783. }else if( sqlite3StrICmp(z, "memory")==0 ){
  81784. return 2;
  81785. }else{
  81786. return 0;
  81787. }
  81788. }
  81789. #endif /* SQLITE_PAGER_PRAGMAS */
  81790. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  81791. /*
  81792. ** Invalidate temp storage, either when the temp storage is changed
  81793. ** from default, or when 'file' and the temp_store_directory has changed
  81794. */
  81795. static int invalidateTempStorage(Parse *pParse){
  81796. sqlite3 *db = pParse->db;
  81797. if( db->aDb[1].pBt!=0 ){
  81798. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  81799. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  81800. "from within a transaction");
  81801. return SQLITE_ERROR;
  81802. }
  81803. sqlite3BtreeClose(db->aDb[1].pBt);
  81804. db->aDb[1].pBt = 0;
  81805. sqlite3ResetInternalSchema(db, -1);
  81806. }
  81807. return SQLITE_OK;
  81808. }
  81809. #endif /* SQLITE_PAGER_PRAGMAS */
  81810. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  81811. /*
  81812. ** If the TEMP database is open, close it and mark the database schema
  81813. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  81814. ** or DEFAULT_TEMP_STORE pragmas.
  81815. */
  81816. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  81817. int ts = getTempStore(zStorageType);
  81818. sqlite3 *db = pParse->db;
  81819. if( db->temp_store==ts ) return SQLITE_OK;
  81820. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  81821. return SQLITE_ERROR;
  81822. }
  81823. db->temp_store = (u8)ts;
  81824. return SQLITE_OK;
  81825. }
  81826. #endif /* SQLITE_PAGER_PRAGMAS */
  81827. /*
  81828. ** Generate code to return a single integer value.
  81829. */
  81830. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  81831. Vdbe *v = sqlite3GetVdbe(pParse);
  81832. int mem = ++pParse->nMem;
  81833. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  81834. if( pI64 ){
  81835. memcpy(pI64, &value, sizeof(value));
  81836. }
  81837. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  81838. sqlite3VdbeSetNumCols(v, 1);
  81839. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  81840. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  81841. }
  81842. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  81843. /*
  81844. ** Check to see if zRight and zLeft refer to a pragma that queries
  81845. ** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
  81846. ** Also, implement the pragma.
  81847. */
  81848. static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
  81849. static const struct sPragmaType {
  81850. const char *zName; /* Name of the pragma */
  81851. int mask; /* Mask for the db->flags value */
  81852. } aPragma[] = {
  81853. { "full_column_names", SQLITE_FullColNames },
  81854. { "short_column_names", SQLITE_ShortColNames },
  81855. { "count_changes", SQLITE_CountRows },
  81856. { "empty_result_callbacks", SQLITE_NullCallback },
  81857. { "legacy_file_format", SQLITE_LegacyFileFmt },
  81858. { "fullfsync", SQLITE_FullFSync },
  81859. { "checkpoint_fullfsync", SQLITE_CkptFullFSync },
  81860. { "reverse_unordered_selects", SQLITE_ReverseOrder },
  81861. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  81862. { "automatic_index", SQLITE_AutoIndex },
  81863. #endif
  81864. #ifdef SQLITE_DEBUG
  81865. { "sql_trace", SQLITE_SqlTrace },
  81866. { "vdbe_listing", SQLITE_VdbeListing },
  81867. { "vdbe_trace", SQLITE_VdbeTrace },
  81868. #endif
  81869. #ifndef SQLITE_OMIT_CHECK
  81870. { "ignore_check_constraints", SQLITE_IgnoreChecks },
  81871. #endif
  81872. /* The following is VERY experimental */
  81873. { "writable_schema", SQLITE_WriteSchema|SQLITE_RecoveryMode },
  81874. { "omit_readlock", SQLITE_NoReadlock },
  81875. /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
  81876. ** flag if there are any active statements. */
  81877. { "read_uncommitted", SQLITE_ReadUncommitted },
  81878. { "recursive_triggers", SQLITE_RecTriggers },
  81879. /* This flag may only be set if both foreign-key and trigger support
  81880. ** are present in the build. */
  81881. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  81882. { "foreign_keys", SQLITE_ForeignKeys },
  81883. #endif
  81884. };
  81885. int i;
  81886. const struct sPragmaType *p;
  81887. for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
  81888. if( sqlite3StrICmp(zLeft, p->zName)==0 ){
  81889. sqlite3 *db = pParse->db;
  81890. Vdbe *v;
  81891. v = sqlite3GetVdbe(pParse);
  81892. assert( v!=0 ); /* Already allocated by sqlite3Pragma() */
  81893. if( ALWAYS(v) ){
  81894. if( zRight==0 ){
  81895. returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
  81896. }else{
  81897. int mask = p->mask; /* Mask of bits to set or clear. */
  81898. if( db->autoCommit==0 ){
  81899. /* Foreign key support may not be enabled or disabled while not
  81900. ** in auto-commit mode. */
  81901. mask &= ~(SQLITE_ForeignKeys);
  81902. }
  81903. if( getBoolean(zRight) ){
  81904. db->flags |= mask;
  81905. }else{
  81906. db->flags &= ~mask;
  81907. }
  81908. /* Many of the flag-pragmas modify the code generated by the SQL
  81909. ** compiler (eg. count_changes). So add an opcode to expire all
  81910. ** compiled SQL statements after modifying a pragma value.
  81911. */
  81912. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  81913. }
  81914. }
  81915. return 1;
  81916. }
  81917. }
  81918. return 0;
  81919. }
  81920. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  81921. /*
  81922. ** Return a human-readable name for a constraint resolution action.
  81923. */
  81924. #ifndef SQLITE_OMIT_FOREIGN_KEY
  81925. static const char *actionName(u8 action){
  81926. const char *zName;
  81927. switch( action ){
  81928. case OE_SetNull: zName = "SET NULL"; break;
  81929. case OE_SetDflt: zName = "SET DEFAULT"; break;
  81930. case OE_Cascade: zName = "CASCADE"; break;
  81931. case OE_Restrict: zName = "RESTRICT"; break;
  81932. default: zName = "NO ACTION";
  81933. assert( action==OE_None ); break;
  81934. }
  81935. return zName;
  81936. }
  81937. #endif
  81938. /*
  81939. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  81940. ** defined in pager.h. This function returns the associated lowercase
  81941. ** journal-mode name.
  81942. */
  81943. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  81944. static char * const azModeName[] = {
  81945. "delete", "persist", "off", "truncate", "memory"
  81946. #ifndef SQLITE_OMIT_WAL
  81947. , "wal"
  81948. #endif
  81949. };
  81950. assert( PAGER_JOURNALMODE_DELETE==0 );
  81951. assert( PAGER_JOURNALMODE_PERSIST==1 );
  81952. assert( PAGER_JOURNALMODE_OFF==2 );
  81953. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  81954. assert( PAGER_JOURNALMODE_MEMORY==4 );
  81955. assert( PAGER_JOURNALMODE_WAL==5 );
  81956. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  81957. if( eMode==ArraySize(azModeName) ) return 0;
  81958. return azModeName[eMode];
  81959. }
  81960. /*
  81961. ** Process a pragma statement.
  81962. **
  81963. ** Pragmas are of this form:
  81964. **
  81965. ** PRAGMA [database.]id [= value]
  81966. **
  81967. ** The identifier might also be a string. The value is a string, and
  81968. ** identifier, or a number. If minusFlag is true, then the value is
  81969. ** a number that was preceded by a minus sign.
  81970. **
  81971. ** If the left side is "database.id" then pId1 is the database name
  81972. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  81973. ** id and pId2 is any empty string.
  81974. */
  81975. SQLITE_PRIVATE void sqlite3Pragma(
  81976. Parse *pParse,
  81977. Token *pId1, /* First part of [database.]id field */
  81978. Token *pId2, /* Second part of [database.]id field, or NULL */
  81979. Token *pValue, /* Token for <value>, or NULL */
  81980. int minusFlag /* True if a '-' sign preceded <value> */
  81981. ){
  81982. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  81983. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  81984. const char *zDb = 0; /* The database name */
  81985. Token *pId; /* Pointer to <id> token */
  81986. int iDb; /* Database index for <database> */
  81987. sqlite3 *db = pParse->db;
  81988. Db *pDb;
  81989. Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
  81990. if( v==0 ) return;
  81991. sqlite3VdbeRunOnlyOnce(v);
  81992. pParse->nMem = 2;
  81993. /* Interpret the [database.] part of the pragma statement. iDb is the
  81994. ** index of the database this pragma is being applied to in db.aDb[]. */
  81995. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  81996. if( iDb<0 ) return;
  81997. pDb = &db->aDb[iDb];
  81998. /* If the temp database has been explicitly named as part of the
  81999. ** pragma, make sure it is open.
  82000. */
  82001. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  82002. return;
  82003. }
  82004. zLeft = sqlite3NameFromToken(db, pId);
  82005. if( !zLeft ) return;
  82006. if( minusFlag ){
  82007. zRight = sqlite3MPrintf(db, "-%T", pValue);
  82008. }else{
  82009. zRight = sqlite3NameFromToken(db, pValue);
  82010. }
  82011. assert( pId2 );
  82012. zDb = pId2->n>0 ? pDb->zName : 0;
  82013. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  82014. goto pragma_out;
  82015. }
  82016. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  82017. /*
  82018. ** PRAGMA [database.]default_cache_size
  82019. ** PRAGMA [database.]default_cache_size=N
  82020. **
  82021. ** The first form reports the current persistent setting for the
  82022. ** page cache size. The value returned is the maximum number of
  82023. ** pages in the page cache. The second form sets both the current
  82024. ** page cache size value and the persistent page cache size value
  82025. ** stored in the database file.
  82026. **
  82027. ** Older versions of SQLite would set the default cache size to a
  82028. ** negative number to indicate synchronous=OFF. These days, synchronous
  82029. ** is always on by default regardless of the sign of the default cache
  82030. ** size. But continue to take the absolute value of the default cache
  82031. ** size of historical compatibility.
  82032. */
  82033. if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
  82034. static const VdbeOpList getCacheSize[] = {
  82035. { OP_Transaction, 0, 0, 0}, /* 0 */
  82036. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  82037. { OP_IfPos, 1, 7, 0},
  82038. { OP_Integer, 0, 2, 0},
  82039. { OP_Subtract, 1, 2, 1},
  82040. { OP_IfPos, 1, 7, 0},
  82041. { OP_Integer, 0, 1, 0}, /* 6 */
  82042. { OP_ResultRow, 1, 1, 0},
  82043. };
  82044. int addr;
  82045. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82046. sqlite3VdbeUsesBtree(v, iDb);
  82047. if( !zRight ){
  82048. sqlite3VdbeSetNumCols(v, 1);
  82049. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  82050. pParse->nMem += 2;
  82051. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  82052. sqlite3VdbeChangeP1(v, addr, iDb);
  82053. sqlite3VdbeChangeP1(v, addr+1, iDb);
  82054. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  82055. }else{
  82056. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  82057. sqlite3BeginWriteOperation(pParse, 0, iDb);
  82058. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  82059. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  82060. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82061. pDb->pSchema->cache_size = size;
  82062. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  82063. }
  82064. }else
  82065. /*
  82066. ** PRAGMA [database.]page_size
  82067. ** PRAGMA [database.]page_size=N
  82068. **
  82069. ** The first form reports the current setting for the
  82070. ** database page size in bytes. The second form sets the
  82071. ** database page size value. The value can only be set if
  82072. ** the database has not yet been created.
  82073. */
  82074. if( sqlite3StrICmp(zLeft,"page_size")==0 ){
  82075. Btree *pBt = pDb->pBt;
  82076. assert( pBt!=0 );
  82077. if( !zRight ){
  82078. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  82079. returnSingleInt(pParse, "page_size", size);
  82080. }else{
  82081. /* Malloc may fail when setting the page-size, as there is an internal
  82082. ** buffer that the pager module resizes using sqlite3_realloc().
  82083. */
  82084. db->nextPagesize = sqlite3Atoi(zRight);
  82085. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  82086. db->mallocFailed = 1;
  82087. }
  82088. }
  82089. }else
  82090. /*
  82091. ** PRAGMA [database.]secure_delete
  82092. ** PRAGMA [database.]secure_delete=ON/OFF
  82093. **
  82094. ** The first form reports the current setting for the
  82095. ** secure_delete flag. The second form changes the secure_delete
  82096. ** flag setting and reports thenew value.
  82097. */
  82098. if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
  82099. Btree *pBt = pDb->pBt;
  82100. int b = -1;
  82101. assert( pBt!=0 );
  82102. if( zRight ){
  82103. b = getBoolean(zRight);
  82104. }
  82105. if( pId2->n==0 && b>=0 ){
  82106. int ii;
  82107. for(ii=0; ii<db->nDb; ii++){
  82108. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  82109. }
  82110. }
  82111. b = sqlite3BtreeSecureDelete(pBt, b);
  82112. returnSingleInt(pParse, "secure_delete", b);
  82113. }else
  82114. /*
  82115. ** PRAGMA [database.]max_page_count
  82116. ** PRAGMA [database.]max_page_count=N
  82117. **
  82118. ** The first form reports the current setting for the
  82119. ** maximum number of pages in the database file. The
  82120. ** second form attempts to change this setting. Both
  82121. ** forms return the current setting.
  82122. **
  82123. ** PRAGMA [database.]page_count
  82124. **
  82125. ** Return the number of pages in the specified database.
  82126. */
  82127. if( sqlite3StrICmp(zLeft,"page_count")==0
  82128. || sqlite3StrICmp(zLeft,"max_page_count")==0
  82129. ){
  82130. int iReg;
  82131. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82132. sqlite3CodeVerifySchema(pParse, iDb);
  82133. iReg = ++pParse->nMem;
  82134. if( zLeft[0]=='p' ){
  82135. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  82136. }else{
  82137. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
  82138. }
  82139. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  82140. sqlite3VdbeSetNumCols(v, 1);
  82141. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  82142. }else
  82143. /*
  82144. ** PRAGMA [database.]locking_mode
  82145. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  82146. */
  82147. if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
  82148. const char *zRet = "normal";
  82149. int eMode = getLockingMode(zRight);
  82150. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  82151. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  82152. ** the current default locking mode (which may be different to
  82153. ** the locking-mode of the main database).
  82154. */
  82155. eMode = db->dfltLockMode;
  82156. }else{
  82157. Pager *pPager;
  82158. if( pId2->n==0 ){
  82159. /* This indicates that no database name was specified as part
  82160. ** of the PRAGMA command. In this case the locking-mode must be
  82161. ** set on all attached databases, as well as the main db file.
  82162. **
  82163. ** Also, the sqlite3.dfltLockMode variable is set so that
  82164. ** any subsequently attached databases also use the specified
  82165. ** locking mode.
  82166. */
  82167. int ii;
  82168. assert(pDb==&db->aDb[0]);
  82169. for(ii=2; ii<db->nDb; ii++){
  82170. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  82171. sqlite3PagerLockingMode(pPager, eMode);
  82172. }
  82173. db->dfltLockMode = (u8)eMode;
  82174. }
  82175. pPager = sqlite3BtreePager(pDb->pBt);
  82176. eMode = sqlite3PagerLockingMode(pPager, eMode);
  82177. }
  82178. assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
  82179. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  82180. zRet = "exclusive";
  82181. }
  82182. sqlite3VdbeSetNumCols(v, 1);
  82183. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  82184. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  82185. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  82186. }else
  82187. /*
  82188. ** PRAGMA [database.]journal_mode
  82189. ** PRAGMA [database.]journal_mode =
  82190. ** (delete|persist|off|truncate|memory|wal|off)
  82191. */
  82192. if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
  82193. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  82194. int ii; /* Loop counter */
  82195. /* Force the schema to be loaded on all databases. This cases all
  82196. ** database files to be opened and the journal_modes set. */
  82197. if( sqlite3ReadSchema(pParse) ){
  82198. goto pragma_out;
  82199. }
  82200. sqlite3VdbeSetNumCols(v, 1);
  82201. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  82202. if( zRight==0 ){
  82203. /* If there is no "=MODE" part of the pragma, do a query for the
  82204. ** current mode */
  82205. eMode = PAGER_JOURNALMODE_QUERY;
  82206. }else{
  82207. const char *zMode;
  82208. int n = sqlite3Strlen30(zRight);
  82209. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  82210. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  82211. }
  82212. if( !zMode ){
  82213. /* If the "=MODE" part does not match any known journal mode,
  82214. ** then do a query */
  82215. eMode = PAGER_JOURNALMODE_QUERY;
  82216. }
  82217. }
  82218. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  82219. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  82220. iDb = 0;
  82221. pId2->n = 1;
  82222. }
  82223. for(ii=db->nDb-1; ii>=0; ii--){
  82224. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  82225. sqlite3VdbeUsesBtree(v, ii);
  82226. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  82227. }
  82228. }
  82229. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  82230. }else
  82231. /*
  82232. ** PRAGMA [database.]journal_size_limit
  82233. ** PRAGMA [database.]journal_size_limit=N
  82234. **
  82235. ** Get or set the size limit on rollback journal files.
  82236. */
  82237. if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
  82238. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  82239. i64 iLimit = -2;
  82240. if( zRight ){
  82241. sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
  82242. if( iLimit<-1 ) iLimit = -1;
  82243. }
  82244. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  82245. returnSingleInt(pParse, "journal_size_limit", iLimit);
  82246. }else
  82247. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  82248. /*
  82249. ** PRAGMA [database.]auto_vacuum
  82250. ** PRAGMA [database.]auto_vacuum=N
  82251. **
  82252. ** Get or set the value of the database 'auto-vacuum' parameter.
  82253. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  82254. */
  82255. #ifndef SQLITE_OMIT_AUTOVACUUM
  82256. if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
  82257. Btree *pBt = pDb->pBt;
  82258. assert( pBt!=0 );
  82259. if( sqlite3ReadSchema(pParse) ){
  82260. goto pragma_out;
  82261. }
  82262. if( !zRight ){
  82263. int auto_vacuum;
  82264. if( ALWAYS(pBt) ){
  82265. auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
  82266. }else{
  82267. auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
  82268. }
  82269. returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
  82270. }else{
  82271. int eAuto = getAutoVacuum(zRight);
  82272. assert( eAuto>=0 && eAuto<=2 );
  82273. db->nextAutovac = (u8)eAuto;
  82274. if( ALWAYS(eAuto>=0) ){
  82275. /* Call SetAutoVacuum() to set initialize the internal auto and
  82276. ** incr-vacuum flags. This is required in case this connection
  82277. ** creates the database file. It is important that it is created
  82278. ** as an auto-vacuum capable db.
  82279. */
  82280. int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  82281. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  82282. /* When setting the auto_vacuum mode to either "full" or
  82283. ** "incremental", write the value of meta[6] in the database
  82284. ** file. Before writing to meta[6], check that meta[3] indicates
  82285. ** that this really is an auto-vacuum capable database.
  82286. */
  82287. static const VdbeOpList setMeta6[] = {
  82288. { OP_Transaction, 0, 1, 0}, /* 0 */
  82289. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  82290. { OP_If, 1, 0, 0}, /* 2 */
  82291. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  82292. { OP_Integer, 0, 1, 0}, /* 4 */
  82293. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  82294. };
  82295. int iAddr;
  82296. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  82297. sqlite3VdbeChangeP1(v, iAddr, iDb);
  82298. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  82299. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  82300. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  82301. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  82302. sqlite3VdbeUsesBtree(v, iDb);
  82303. }
  82304. }
  82305. }
  82306. }else
  82307. #endif
  82308. /*
  82309. ** PRAGMA [database.]incremental_vacuum(N)
  82310. **
  82311. ** Do N steps of incremental vacuuming on a database.
  82312. */
  82313. #ifndef SQLITE_OMIT_AUTOVACUUM
  82314. if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
  82315. int iLimit, addr;
  82316. if( sqlite3ReadSchema(pParse) ){
  82317. goto pragma_out;
  82318. }
  82319. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  82320. iLimit = 0x7fffffff;
  82321. }
  82322. sqlite3BeginWriteOperation(pParse, 0, iDb);
  82323. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  82324. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  82325. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  82326. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  82327. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  82328. sqlite3VdbeJumpHere(v, addr);
  82329. }else
  82330. #endif
  82331. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  82332. /*
  82333. ** PRAGMA [database.]cache_size
  82334. ** PRAGMA [database.]cache_size=N
  82335. **
  82336. ** The first form reports the current local setting for the
  82337. ** page cache size. The local setting can be different from
  82338. ** the persistent cache size value that is stored in the database
  82339. ** file itself. The value returned is the maximum number of
  82340. ** pages in the page cache. The second form sets the local
  82341. ** page cache size value. It does not change the persistent
  82342. ** cache size stored on the disk so the cache size will revert
  82343. ** to its default value when the database is closed and reopened.
  82344. ** N should be a positive integer.
  82345. */
  82346. if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
  82347. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82348. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82349. if( !zRight ){
  82350. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  82351. }else{
  82352. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  82353. pDb->pSchema->cache_size = size;
  82354. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  82355. }
  82356. }else
  82357. /*
  82358. ** PRAGMA temp_store
  82359. ** PRAGMA temp_store = "default"|"memory"|"file"
  82360. **
  82361. ** Return or set the local value of the temp_store flag. Changing
  82362. ** the local value does not make changes to the disk file and the default
  82363. ** value will be restored the next time the database is opened.
  82364. **
  82365. ** Note that it is possible for the library compile-time options to
  82366. ** override this setting
  82367. */
  82368. if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
  82369. if( !zRight ){
  82370. returnSingleInt(pParse, "temp_store", db->temp_store);
  82371. }else{
  82372. changeTempStorage(pParse, zRight);
  82373. }
  82374. }else
  82375. /*
  82376. ** PRAGMA temp_store_directory
  82377. ** PRAGMA temp_store_directory = ""|"directory_name"
  82378. **
  82379. ** Return or set the local value of the temp_store_directory flag. Changing
  82380. ** the value sets a specific directory to be used for temporary files.
  82381. ** Setting to a null string reverts to the default temporary directory search.
  82382. ** If temporary directory is changed, then invalidateTempStorage.
  82383. **
  82384. */
  82385. if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
  82386. if( !zRight ){
  82387. if( sqlite3_temp_directory ){
  82388. sqlite3VdbeSetNumCols(v, 1);
  82389. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  82390. "temp_store_directory", SQLITE_STATIC);
  82391. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  82392. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  82393. }
  82394. }else{
  82395. #ifndef SQLITE_OMIT_WSD
  82396. if( zRight[0] ){
  82397. int rc;
  82398. int res;
  82399. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  82400. if( rc!=SQLITE_OK || res==0 ){
  82401. sqlite3ErrorMsg(pParse, "not a writable directory");
  82402. goto pragma_out;
  82403. }
  82404. }
  82405. if( SQLITE_TEMP_STORE==0
  82406. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  82407. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  82408. ){
  82409. invalidateTempStorage(pParse);
  82410. }
  82411. sqlite3_free(sqlite3_temp_directory);
  82412. if( zRight[0] ){
  82413. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  82414. }else{
  82415. sqlite3_temp_directory = 0;
  82416. }
  82417. #endif /* SQLITE_OMIT_WSD */
  82418. }
  82419. }else
  82420. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  82421. # if defined(__APPLE__)
  82422. # define SQLITE_ENABLE_LOCKING_STYLE 1
  82423. # else
  82424. # define SQLITE_ENABLE_LOCKING_STYLE 0
  82425. # endif
  82426. #endif
  82427. #if SQLITE_ENABLE_LOCKING_STYLE
  82428. /*
  82429. ** PRAGMA [database.]lock_proxy_file
  82430. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  82431. **
  82432. ** Return or set the value of the lock_proxy_file flag. Changing
  82433. ** the value sets a specific file to be used for database access locks.
  82434. **
  82435. */
  82436. if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
  82437. if( !zRight ){
  82438. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  82439. char *proxy_file_path = NULL;
  82440. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  82441. sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
  82442. &proxy_file_path);
  82443. if( proxy_file_path ){
  82444. sqlite3VdbeSetNumCols(v, 1);
  82445. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  82446. "lock_proxy_file", SQLITE_STATIC);
  82447. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  82448. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  82449. }
  82450. }else{
  82451. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  82452. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  82453. int res;
  82454. if( zRight[0] ){
  82455. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  82456. zRight);
  82457. } else {
  82458. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  82459. NULL);
  82460. }
  82461. if( res!=SQLITE_OK ){
  82462. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  82463. goto pragma_out;
  82464. }
  82465. }
  82466. }else
  82467. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  82468. /*
  82469. ** PRAGMA [database.]synchronous
  82470. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  82471. **
  82472. ** Return or set the local value of the synchronous flag. Changing
  82473. ** the local value does not make changes to the disk file and the
  82474. ** default value will be restored the next time the database is
  82475. ** opened.
  82476. */
  82477. if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
  82478. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82479. if( !zRight ){
  82480. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  82481. }else{
  82482. if( !db->autoCommit ){
  82483. sqlite3ErrorMsg(pParse,
  82484. "Safety level may not be changed inside a transaction");
  82485. }else{
  82486. pDb->safety_level = getSafetyLevel(zRight)+1;
  82487. }
  82488. }
  82489. }else
  82490. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  82491. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  82492. if( flagPragma(pParse, zLeft, zRight) ){
  82493. /* The flagPragma() subroutine also generates any necessary code
  82494. ** there is nothing more to do here */
  82495. }else
  82496. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  82497. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  82498. /*
  82499. ** PRAGMA table_info(<table>)
  82500. **
  82501. ** Return a single row for each column of the named table. The columns of
  82502. ** the returned data set are:
  82503. **
  82504. ** cid: Column id (numbered from left to right, starting at 0)
  82505. ** name: Column name
  82506. ** type: Column declaration type.
  82507. ** notnull: True if 'NOT NULL' is part of column declaration
  82508. ** dflt_value: The default value for the column, if any.
  82509. */
  82510. if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
  82511. Table *pTab;
  82512. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82513. pTab = sqlite3FindTable(db, zRight, zDb);
  82514. if( pTab ){
  82515. int i;
  82516. int nHidden = 0;
  82517. Column *pCol;
  82518. sqlite3VdbeSetNumCols(v, 6);
  82519. pParse->nMem = 6;
  82520. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  82521. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  82522. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  82523. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  82524. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  82525. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  82526. sqlite3ViewGetColumnNames(pParse, pTab);
  82527. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  82528. if( IsHiddenColumn(pCol) ){
  82529. nHidden++;
  82530. continue;
  82531. }
  82532. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  82533. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  82534. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  82535. pCol->zType ? pCol->zType : "", 0);
  82536. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  82537. if( pCol->zDflt ){
  82538. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  82539. }else{
  82540. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  82541. }
  82542. sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
  82543. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  82544. }
  82545. }
  82546. }else
  82547. if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
  82548. Index *pIdx;
  82549. Table *pTab;
  82550. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82551. pIdx = sqlite3FindIndex(db, zRight, zDb);
  82552. if( pIdx ){
  82553. int i;
  82554. pTab = pIdx->pTable;
  82555. sqlite3VdbeSetNumCols(v, 3);
  82556. pParse->nMem = 3;
  82557. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  82558. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  82559. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  82560. for(i=0; i<pIdx->nColumn; i++){
  82561. int cnum = pIdx->aiColumn[i];
  82562. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  82563. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  82564. assert( pTab->nCol>cnum );
  82565. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  82566. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  82567. }
  82568. }
  82569. }else
  82570. if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
  82571. Index *pIdx;
  82572. Table *pTab;
  82573. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82574. pTab = sqlite3FindTable(db, zRight, zDb);
  82575. if( pTab ){
  82576. v = sqlite3GetVdbe(pParse);
  82577. pIdx = pTab->pIndex;
  82578. if( pIdx ){
  82579. int i = 0;
  82580. sqlite3VdbeSetNumCols(v, 3);
  82581. pParse->nMem = 3;
  82582. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  82583. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  82584. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  82585. while(pIdx){
  82586. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  82587. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  82588. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  82589. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  82590. ++i;
  82591. pIdx = pIdx->pNext;
  82592. }
  82593. }
  82594. }
  82595. }else
  82596. if( sqlite3StrICmp(zLeft, "database_list")==0 ){
  82597. int i;
  82598. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82599. sqlite3VdbeSetNumCols(v, 3);
  82600. pParse->nMem = 3;
  82601. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  82602. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  82603. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  82604. for(i=0; i<db->nDb; i++){
  82605. if( db->aDb[i].pBt==0 ) continue;
  82606. assert( db->aDb[i].zName!=0 );
  82607. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  82608. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  82609. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  82610. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  82611. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  82612. }
  82613. }else
  82614. if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
  82615. int i = 0;
  82616. HashElem *p;
  82617. sqlite3VdbeSetNumCols(v, 2);
  82618. pParse->nMem = 2;
  82619. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  82620. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  82621. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  82622. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  82623. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  82624. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  82625. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  82626. }
  82627. }else
  82628. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  82629. #ifndef SQLITE_OMIT_FOREIGN_KEY
  82630. if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
  82631. FKey *pFK;
  82632. Table *pTab;
  82633. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82634. pTab = sqlite3FindTable(db, zRight, zDb);
  82635. if( pTab ){
  82636. v = sqlite3GetVdbe(pParse);
  82637. pFK = pTab->pFKey;
  82638. if( pFK ){
  82639. int i = 0;
  82640. sqlite3VdbeSetNumCols(v, 8);
  82641. pParse->nMem = 8;
  82642. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  82643. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  82644. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  82645. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  82646. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  82647. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  82648. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  82649. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  82650. while(pFK){
  82651. int j;
  82652. for(j=0; j<pFK->nCol; j++){
  82653. char *zCol = pFK->aCol[j].zCol;
  82654. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  82655. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  82656. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  82657. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  82658. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  82659. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  82660. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  82661. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  82662. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  82663. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  82664. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  82665. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  82666. }
  82667. ++i;
  82668. pFK = pFK->pNextFrom;
  82669. }
  82670. }
  82671. }
  82672. }else
  82673. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  82674. #ifndef NDEBUG
  82675. if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
  82676. if( zRight ){
  82677. if( getBoolean(zRight) ){
  82678. sqlite3ParserTrace(stderr, "parser: ");
  82679. }else{
  82680. sqlite3ParserTrace(0, 0);
  82681. }
  82682. }
  82683. }else
  82684. #endif
  82685. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  82686. ** used will be case sensitive or not depending on the RHS.
  82687. */
  82688. if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
  82689. if( zRight ){
  82690. sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
  82691. }
  82692. }else
  82693. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  82694. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  82695. #endif
  82696. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  82697. /* Pragma "quick_check" is an experimental reduced version of
  82698. ** integrity_check designed to detect most database corruption
  82699. ** without most of the overhead of a full integrity-check.
  82700. */
  82701. if( sqlite3StrICmp(zLeft, "integrity_check")==0
  82702. || sqlite3StrICmp(zLeft, "quick_check")==0
  82703. ){
  82704. int i, j, addr, mxErr;
  82705. /* Code that appears at the end of the integrity check. If no error
  82706. ** messages have been generated, output OK. Otherwise output the
  82707. ** error message
  82708. */
  82709. static const VdbeOpList endCode[] = {
  82710. { OP_AddImm, 1, 0, 0}, /* 0 */
  82711. { OP_IfNeg, 1, 0, 0}, /* 1 */
  82712. { OP_String8, 0, 3, 0}, /* 2 */
  82713. { OP_ResultRow, 3, 1, 0},
  82714. };
  82715. int isQuick = (zLeft[0]=='q');
  82716. /* Initialize the VDBE program */
  82717. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82718. pParse->nMem = 6;
  82719. sqlite3VdbeSetNumCols(v, 1);
  82720. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  82721. /* Set the maximum error count */
  82722. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  82723. if( zRight ){
  82724. sqlite3GetInt32(zRight, &mxErr);
  82725. if( mxErr<=0 ){
  82726. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  82727. }
  82728. }
  82729. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  82730. /* Do an integrity check on each database file */
  82731. for(i=0; i<db->nDb; i++){
  82732. HashElem *x;
  82733. Hash *pTbls;
  82734. int cnt = 0;
  82735. if( OMIT_TEMPDB && i==1 ) continue;
  82736. sqlite3CodeVerifySchema(pParse, i);
  82737. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  82738. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  82739. sqlite3VdbeJumpHere(v, addr);
  82740. /* Do an integrity check of the B-Tree
  82741. **
  82742. ** Begin by filling registers 2, 3, ... with the root pages numbers
  82743. ** for all tables and indices in the database.
  82744. */
  82745. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82746. pTbls = &db->aDb[i].pSchema->tblHash;
  82747. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  82748. Table *pTab = sqliteHashData(x);
  82749. Index *pIdx;
  82750. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  82751. cnt++;
  82752. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  82753. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  82754. cnt++;
  82755. }
  82756. }
  82757. /* Make sure sufficient number of registers have been allocated */
  82758. if( pParse->nMem < cnt+4 ){
  82759. pParse->nMem = cnt+4;
  82760. }
  82761. /* Do the b-tree integrity checks */
  82762. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  82763. sqlite3VdbeChangeP5(v, (u8)i);
  82764. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  82765. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  82766. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  82767. P4_DYNAMIC);
  82768. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  82769. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  82770. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  82771. sqlite3VdbeJumpHere(v, addr);
  82772. /* Make sure all the indices are constructed correctly.
  82773. */
  82774. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  82775. Table *pTab = sqliteHashData(x);
  82776. Index *pIdx;
  82777. int loopTop;
  82778. if( pTab->pIndex==0 ) continue;
  82779. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  82780. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  82781. sqlite3VdbeJumpHere(v, addr);
  82782. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  82783. sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */
  82784. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
  82785. sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */
  82786. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  82787. int jmp2;
  82788. int r1;
  82789. static const VdbeOpList idxErr[] = {
  82790. { OP_AddImm, 1, -1, 0},
  82791. { OP_String8, 0, 3, 0}, /* 1 */
  82792. { OP_Rowid, 1, 4, 0},
  82793. { OP_String8, 0, 5, 0}, /* 3 */
  82794. { OP_String8, 0, 6, 0}, /* 4 */
  82795. { OP_Concat, 4, 3, 3},
  82796. { OP_Concat, 5, 3, 3},
  82797. { OP_Concat, 6, 3, 3},
  82798. { OP_ResultRow, 3, 1, 0},
  82799. { OP_IfPos, 1, 0, 0}, /* 9 */
  82800. { OP_Halt, 0, 0, 0},
  82801. };
  82802. r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
  82803. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  82804. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  82805. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  82806. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  82807. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  82808. sqlite3VdbeJumpHere(v, addr+9);
  82809. sqlite3VdbeJumpHere(v, jmp2);
  82810. }
  82811. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
  82812. sqlite3VdbeJumpHere(v, loopTop);
  82813. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  82814. static const VdbeOpList cntIdx[] = {
  82815. { OP_Integer, 0, 3, 0},
  82816. { OP_Rewind, 0, 0, 0}, /* 1 */
  82817. { OP_AddImm, 3, 1, 0},
  82818. { OP_Next, 0, 0, 0}, /* 3 */
  82819. { OP_Eq, 2, 0, 3}, /* 4 */
  82820. { OP_AddImm, 1, -1, 0},
  82821. { OP_String8, 0, 2, 0}, /* 6 */
  82822. { OP_String8, 0, 3, 0}, /* 7 */
  82823. { OP_Concat, 3, 2, 2},
  82824. { OP_ResultRow, 2, 1, 0},
  82825. };
  82826. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
  82827. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  82828. sqlite3VdbeJumpHere(v, addr);
  82829. addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
  82830. sqlite3VdbeChangeP1(v, addr+1, j+2);
  82831. sqlite3VdbeChangeP2(v, addr+1, addr+4);
  82832. sqlite3VdbeChangeP1(v, addr+3, j+2);
  82833. sqlite3VdbeChangeP2(v, addr+3, addr+2);
  82834. sqlite3VdbeJumpHere(v, addr+4);
  82835. sqlite3VdbeChangeP4(v, addr+6,
  82836. "wrong # of entries in index ", P4_STATIC);
  82837. sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
  82838. }
  82839. }
  82840. }
  82841. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  82842. sqlite3VdbeChangeP2(v, addr, -mxErr);
  82843. sqlite3VdbeJumpHere(v, addr+1);
  82844. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  82845. }else
  82846. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  82847. #ifndef SQLITE_OMIT_UTF16
  82848. /*
  82849. ** PRAGMA encoding
  82850. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  82851. **
  82852. ** In its first form, this pragma returns the encoding of the main
  82853. ** database. If the database is not initialized, it is initialized now.
  82854. **
  82855. ** The second form of this pragma is a no-op if the main database file
  82856. ** has not already been initialized. In this case it sets the default
  82857. ** encoding that will be used for the main database file if a new file
  82858. ** is created. If an existing main database file is opened, then the
  82859. ** default text encoding for the existing database is used.
  82860. **
  82861. ** In all cases new databases created using the ATTACH command are
  82862. ** created to use the same default text encoding as the main database. If
  82863. ** the main database has not been initialized and/or created when ATTACH
  82864. ** is executed, this is done before the ATTACH operation.
  82865. **
  82866. ** In the second form this pragma sets the text encoding to be used in
  82867. ** new database files created using this database handle. It is only
  82868. ** useful if invoked immediately after the main database i
  82869. */
  82870. if( sqlite3StrICmp(zLeft, "encoding")==0 ){
  82871. static const struct EncName {
  82872. char *zName;
  82873. u8 enc;
  82874. } encnames[] = {
  82875. { "UTF8", SQLITE_UTF8 },
  82876. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  82877. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  82878. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  82879. { "UTF16le", SQLITE_UTF16LE },
  82880. { "UTF16be", SQLITE_UTF16BE },
  82881. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  82882. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  82883. { 0, 0 }
  82884. };
  82885. const struct EncName *pEnc;
  82886. if( !zRight ){ /* "PRAGMA encoding" */
  82887. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  82888. sqlite3VdbeSetNumCols(v, 1);
  82889. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  82890. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  82891. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  82892. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  82893. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  82894. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  82895. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  82896. }else{ /* "PRAGMA encoding = XXX" */
  82897. /* Only change the value of sqlite.enc if the database handle is not
  82898. ** initialized. If the main database exists, the new sqlite.enc value
  82899. ** will be overwritten when the schema is next loaded. If it does not
  82900. ** already exists, it will be created to use the new encoding value.
  82901. */
  82902. if(
  82903. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  82904. DbHasProperty(db, 0, DB_Empty)
  82905. ){
  82906. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  82907. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  82908. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  82909. break;
  82910. }
  82911. }
  82912. if( !pEnc->zName ){
  82913. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  82914. }
  82915. }
  82916. }
  82917. }else
  82918. #endif /* SQLITE_OMIT_UTF16 */
  82919. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  82920. /*
  82921. ** PRAGMA [database.]schema_version
  82922. ** PRAGMA [database.]schema_version = <integer>
  82923. **
  82924. ** PRAGMA [database.]user_version
  82925. ** PRAGMA [database.]user_version = <integer>
  82926. **
  82927. ** The pragma's schema_version and user_version are used to set or get
  82928. ** the value of the schema-version and user-version, respectively. Both
  82929. ** the schema-version and the user-version are 32-bit signed integers
  82930. ** stored in the database header.
  82931. **
  82932. ** The schema-cookie is usually only manipulated internally by SQLite. It
  82933. ** is incremented by SQLite whenever the database schema is modified (by
  82934. ** creating or dropping a table or index). The schema version is used by
  82935. ** SQLite each time a query is executed to ensure that the internal cache
  82936. ** of the schema used when compiling the SQL query matches the schema of
  82937. ** the database against which the compiled query is actually executed.
  82938. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  82939. ** the schema-version is potentially dangerous and may lead to program
  82940. ** crashes or database corruption. Use with caution!
  82941. **
  82942. ** The user-version is not used internally by SQLite. It may be used by
  82943. ** applications for any purpose.
  82944. */
  82945. if( sqlite3StrICmp(zLeft, "schema_version")==0
  82946. || sqlite3StrICmp(zLeft, "user_version")==0
  82947. || sqlite3StrICmp(zLeft, "freelist_count")==0
  82948. ){
  82949. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  82950. sqlite3VdbeUsesBtree(v, iDb);
  82951. switch( zLeft[0] ){
  82952. case 'f': case 'F':
  82953. iCookie = BTREE_FREE_PAGE_COUNT;
  82954. break;
  82955. case 's': case 'S':
  82956. iCookie = BTREE_SCHEMA_VERSION;
  82957. break;
  82958. default:
  82959. iCookie = BTREE_USER_VERSION;
  82960. break;
  82961. }
  82962. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  82963. /* Write the specified cookie value */
  82964. static const VdbeOpList setCookie[] = {
  82965. { OP_Transaction, 0, 1, 0}, /* 0 */
  82966. { OP_Integer, 0, 1, 0}, /* 1 */
  82967. { OP_SetCookie, 0, 0, 1}, /* 2 */
  82968. };
  82969. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  82970. sqlite3VdbeChangeP1(v, addr, iDb);
  82971. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  82972. sqlite3VdbeChangeP1(v, addr+2, iDb);
  82973. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  82974. }else{
  82975. /* Read the specified cookie value */
  82976. static const VdbeOpList readCookie[] = {
  82977. { OP_Transaction, 0, 0, 0}, /* 0 */
  82978. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  82979. { OP_ResultRow, 1, 1, 0}
  82980. };
  82981. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  82982. sqlite3VdbeChangeP1(v, addr, iDb);
  82983. sqlite3VdbeChangeP1(v, addr+1, iDb);
  82984. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  82985. sqlite3VdbeSetNumCols(v, 1);
  82986. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  82987. }
  82988. }else
  82989. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  82990. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  82991. /*
  82992. ** PRAGMA compile_options
  82993. **
  82994. ** Return the names of all compile-time options used in this build,
  82995. ** one option per row.
  82996. */
  82997. if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
  82998. int i = 0;
  82999. const char *zOpt;
  83000. sqlite3VdbeSetNumCols(v, 1);
  83001. pParse->nMem = 1;
  83002. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  83003. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  83004. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  83005. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  83006. }
  83007. }else
  83008. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  83009. #ifndef SQLITE_OMIT_WAL
  83010. /*
  83011. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  83012. **
  83013. ** Checkpoint the database.
  83014. */
  83015. if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
  83016. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  83017. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  83018. if( zRight ){
  83019. if( sqlite3StrICmp(zRight, "full")==0 ){
  83020. eMode = SQLITE_CHECKPOINT_FULL;
  83021. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  83022. eMode = SQLITE_CHECKPOINT_RESTART;
  83023. }
  83024. }
  83025. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  83026. sqlite3VdbeSetNumCols(v, 3);
  83027. pParse->nMem = 3;
  83028. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  83029. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  83030. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  83031. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  83032. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  83033. }else
  83034. /*
  83035. ** PRAGMA wal_autocheckpoint
  83036. ** PRAGMA wal_autocheckpoint = N
  83037. **
  83038. ** Configure a database connection to automatically checkpoint a database
  83039. ** after accumulating N frames in the log. Or query for the current value
  83040. ** of N.
  83041. */
  83042. if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
  83043. if( zRight ){
  83044. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  83045. }
  83046. returnSingleInt(pParse, "wal_autocheckpoint",
  83047. db->xWalCallback==sqlite3WalDefaultHook ?
  83048. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  83049. }else
  83050. #endif
  83051. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  83052. /*
  83053. ** Report the current state of file logs for all databases
  83054. */
  83055. if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
  83056. static const char *const azLockName[] = {
  83057. "unlocked", "shared", "reserved", "pending", "exclusive"
  83058. };
  83059. int i;
  83060. sqlite3VdbeSetNumCols(v, 2);
  83061. pParse->nMem = 2;
  83062. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  83063. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  83064. for(i=0; i<db->nDb; i++){
  83065. Btree *pBt;
  83066. Pager *pPager;
  83067. const char *zState = "unknown";
  83068. int j;
  83069. if( db->aDb[i].zName==0 ) continue;
  83070. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  83071. pBt = db->aDb[i].pBt;
  83072. if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
  83073. zState = "closed";
  83074. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  83075. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  83076. zState = azLockName[j];
  83077. }
  83078. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  83079. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  83080. }
  83081. }else
  83082. #endif
  83083. #ifdef SQLITE_HAS_CODEC
  83084. if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
  83085. sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
  83086. }else
  83087. if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
  83088. sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
  83089. }else
  83090. if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
  83091. sqlite3StrICmp(zLeft, "hexrekey")==0) ){
  83092. int i, h1, h2;
  83093. char zKey[40];
  83094. for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
  83095. h1 += 9*(1&(h1>>6));
  83096. h2 += 9*(1&(h2>>6));
  83097. zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
  83098. }
  83099. if( (zLeft[3] & 0xf)==0xb ){
  83100. sqlite3_key(db, zKey, i/2);
  83101. }else{
  83102. sqlite3_rekey(db, zKey, i/2);
  83103. }
  83104. }else
  83105. #endif
  83106. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  83107. if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
  83108. #ifdef SQLITE_HAS_CODEC
  83109. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  83110. sqlite3_activate_see(&zRight[4]);
  83111. }
  83112. #endif
  83113. #ifdef SQLITE_ENABLE_CEROD
  83114. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  83115. sqlite3_activate_cerod(&zRight[6]);
  83116. }
  83117. #endif
  83118. }else
  83119. #endif
  83120. {/* Empty ELSE clause */}
  83121. /*
  83122. ** Reset the safety level, in case the fullfsync flag or synchronous
  83123. ** setting changed.
  83124. */
  83125. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  83126. if( db->autoCommit ){
  83127. sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
  83128. (db->flags&SQLITE_FullFSync)!=0,
  83129. (db->flags&SQLITE_CkptFullFSync)!=0);
  83130. }
  83131. #endif
  83132. pragma_out:
  83133. sqlite3DbFree(db, zLeft);
  83134. sqlite3DbFree(db, zRight);
  83135. }
  83136. #endif /* SQLITE_OMIT_PRAGMA */
  83137. /************** End of pragma.c **********************************************/
  83138. /************** Begin file prepare.c *****************************************/
  83139. /*
  83140. ** 2005 May 25
  83141. **
  83142. ** The author disclaims copyright to this source code. In place of
  83143. ** a legal notice, here is a blessing:
  83144. **
  83145. ** May you do good and not evil.
  83146. ** May you find forgiveness for yourself and forgive others.
  83147. ** May you share freely, never taking more than you give.
  83148. **
  83149. *************************************************************************
  83150. ** This file contains the implementation of the sqlite3_prepare()
  83151. ** interface, and routines that contribute to loading the database schema
  83152. ** from disk.
  83153. */
  83154. /*
  83155. ** Fill the InitData structure with an error message that indicates
  83156. ** that the database is corrupt.
  83157. */
  83158. static void corruptSchema(
  83159. InitData *pData, /* Initialization context */
  83160. const char *zObj, /* Object being parsed at the point of error */
  83161. const char *zExtra /* Error information */
  83162. ){
  83163. sqlite3 *db = pData->db;
  83164. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  83165. if( zObj==0 ) zObj = "?";
  83166. sqlite3SetString(pData->pzErrMsg, db,
  83167. "malformed database schema (%s)", zObj);
  83168. if( zExtra ){
  83169. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  83170. "%s - %s", *pData->pzErrMsg, zExtra);
  83171. }
  83172. }
  83173. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  83174. }
  83175. /*
  83176. ** This is the callback routine for the code that initializes the
  83177. ** database. See sqlite3Init() below for additional information.
  83178. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  83179. **
  83180. ** Each callback contains the following information:
  83181. **
  83182. ** argv[0] = name of thing being created
  83183. ** argv[1] = root page number for table or index. 0 for trigger or view.
  83184. ** argv[2] = SQL text for the CREATE statement.
  83185. **
  83186. */
  83187. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  83188. InitData *pData = (InitData*)pInit;
  83189. sqlite3 *db = pData->db;
  83190. int iDb = pData->iDb;
  83191. assert( argc==3 );
  83192. UNUSED_PARAMETER2(NotUsed, argc);
  83193. assert( sqlite3_mutex_held(db->mutex) );
  83194. DbClearProperty(db, iDb, DB_Empty);
  83195. if( db->mallocFailed ){
  83196. corruptSchema(pData, argv[0], 0);
  83197. return 1;
  83198. }
  83199. assert( iDb>=0 && iDb<db->nDb );
  83200. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  83201. if( argv[1]==0 ){
  83202. corruptSchema(pData, argv[0], 0);
  83203. }else if( argv[2] && argv[2][0] ){
  83204. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  83205. ** But because db->init.busy is set to 1, no VDBE code is generated
  83206. ** or executed. All the parser does is build the internal data
  83207. ** structures that describe the table, index, or view.
  83208. */
  83209. int rc;
  83210. sqlite3_stmt *pStmt;
  83211. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  83212. assert( db->init.busy );
  83213. db->init.iDb = iDb;
  83214. db->init.newTnum = sqlite3Atoi(argv[1]);
  83215. db->init.orphanTrigger = 0;
  83216. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  83217. rc = db->errCode;
  83218. assert( (rc&0xFF)==(rcp&0xFF) );
  83219. db->init.iDb = 0;
  83220. if( SQLITE_OK!=rc ){
  83221. if( db->init.orphanTrigger ){
  83222. assert( iDb==1 );
  83223. }else{
  83224. pData->rc = rc;
  83225. if( rc==SQLITE_NOMEM ){
  83226. db->mallocFailed = 1;
  83227. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  83228. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  83229. }
  83230. }
  83231. }
  83232. sqlite3_finalize(pStmt);
  83233. }else if( argv[0]==0 ){
  83234. corruptSchema(pData, 0, 0);
  83235. }else{
  83236. /* If the SQL column is blank it means this is an index that
  83237. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  83238. ** constraint for a CREATE TABLE. The index should have already
  83239. ** been created when we processed the CREATE TABLE. All we have
  83240. ** to do here is record the root page number for that index.
  83241. */
  83242. Index *pIndex;
  83243. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  83244. if( pIndex==0 ){
  83245. /* This can occur if there exists an index on a TEMP table which
  83246. ** has the same name as another index on a permanent index. Since
  83247. ** the permanent table is hidden by the TEMP table, we can also
  83248. ** safely ignore the index on the permanent table.
  83249. */
  83250. /* Do Nothing */;
  83251. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  83252. corruptSchema(pData, argv[0], "invalid rootpage");
  83253. }
  83254. }
  83255. return 0;
  83256. }
  83257. /*
  83258. ** Attempt to read the database schema and initialize internal
  83259. ** data structures for a single database file. The index of the
  83260. ** database file is given by iDb. iDb==0 is used for the main
  83261. ** database. iDb==1 should never be used. iDb>=2 is used for
  83262. ** auxiliary databases. Return one of the SQLITE_ error codes to
  83263. ** indicate success or failure.
  83264. */
  83265. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  83266. int rc;
  83267. int i;
  83268. int size;
  83269. Table *pTab;
  83270. Db *pDb;
  83271. char const *azArg[4];
  83272. int meta[5];
  83273. InitData initData;
  83274. char const *zMasterSchema;
  83275. char const *zMasterName;
  83276. int openedTransaction = 0;
  83277. /*
  83278. ** The master database table has a structure like this
  83279. */
  83280. static const char master_schema[] =
  83281. "CREATE TABLE sqlite_master(\n"
  83282. " type text,\n"
  83283. " name text,\n"
  83284. " tbl_name text,\n"
  83285. " rootpage integer,\n"
  83286. " sql text\n"
  83287. ")"
  83288. ;
  83289. #ifndef SQLITE_OMIT_TEMPDB
  83290. static const char temp_master_schema[] =
  83291. "CREATE TEMP TABLE sqlite_temp_master(\n"
  83292. " type text,\n"
  83293. " name text,\n"
  83294. " tbl_name text,\n"
  83295. " rootpage integer,\n"
  83296. " sql text\n"
  83297. ")"
  83298. ;
  83299. #else
  83300. #define temp_master_schema 0
  83301. #endif
  83302. assert( iDb>=0 && iDb<db->nDb );
  83303. assert( db->aDb[iDb].pSchema );
  83304. assert( sqlite3_mutex_held(db->mutex) );
  83305. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  83306. /* zMasterSchema and zInitScript are set to point at the master schema
  83307. ** and initialisation script appropriate for the database being
  83308. ** initialised. zMasterName is the name of the master table.
  83309. */
  83310. if( !OMIT_TEMPDB && iDb==1 ){
  83311. zMasterSchema = temp_master_schema;
  83312. }else{
  83313. zMasterSchema = master_schema;
  83314. }
  83315. zMasterName = SCHEMA_TABLE(iDb);
  83316. /* Construct the schema tables. */
  83317. azArg[0] = zMasterName;
  83318. azArg[1] = "1";
  83319. azArg[2] = zMasterSchema;
  83320. azArg[3] = 0;
  83321. initData.db = db;
  83322. initData.iDb = iDb;
  83323. initData.rc = SQLITE_OK;
  83324. initData.pzErrMsg = pzErrMsg;
  83325. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  83326. if( initData.rc ){
  83327. rc = initData.rc;
  83328. goto error_out;
  83329. }
  83330. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  83331. if( ALWAYS(pTab) ){
  83332. pTab->tabFlags |= TF_Readonly;
  83333. }
  83334. /* Create a cursor to hold the database open
  83335. */
  83336. pDb = &db->aDb[iDb];
  83337. if( pDb->pBt==0 ){
  83338. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  83339. DbSetProperty(db, 1, DB_SchemaLoaded);
  83340. }
  83341. return SQLITE_OK;
  83342. }
  83343. /* If there is not already a read-only (or read-write) transaction opened
  83344. ** on the b-tree database, open one now. If a transaction is opened, it
  83345. ** will be closed before this function returns. */
  83346. sqlite3BtreeEnter(pDb->pBt);
  83347. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  83348. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  83349. if( rc!=SQLITE_OK ){
  83350. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  83351. goto initone_error_out;
  83352. }
  83353. openedTransaction = 1;
  83354. }
  83355. /* Get the database meta information.
  83356. **
  83357. ** Meta values are as follows:
  83358. ** meta[0] Schema cookie. Changes with each schema change.
  83359. ** meta[1] File format of schema layer.
  83360. ** meta[2] Size of the page cache.
  83361. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  83362. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  83363. ** meta[5] User version
  83364. ** meta[6] Incremental vacuum mode
  83365. ** meta[7] unused
  83366. ** meta[8] unused
  83367. ** meta[9] unused
  83368. **
  83369. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  83370. ** the possible values of meta[4].
  83371. */
  83372. for(i=0; i<ArraySize(meta); i++){
  83373. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  83374. }
  83375. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  83376. /* If opening a non-empty database, check the text encoding. For the
  83377. ** main database, set sqlite3.enc to the encoding of the main database.
  83378. ** For an attached db, it is an error if the encoding is not the same
  83379. ** as sqlite3.enc.
  83380. */
  83381. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  83382. if( iDb==0 ){
  83383. u8 encoding;
  83384. /* If opening the main database, set ENC(db). */
  83385. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  83386. if( encoding==0 ) encoding = SQLITE_UTF8;
  83387. ENC(db) = encoding;
  83388. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  83389. }else{
  83390. /* If opening an attached database, the encoding much match ENC(db) */
  83391. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  83392. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  83393. " text encoding as main database");
  83394. rc = SQLITE_ERROR;
  83395. goto initone_error_out;
  83396. }
  83397. }
  83398. }else{
  83399. DbSetProperty(db, iDb, DB_Empty);
  83400. }
  83401. pDb->pSchema->enc = ENC(db);
  83402. if( pDb->pSchema->cache_size==0 ){
  83403. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  83404. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  83405. pDb->pSchema->cache_size = size;
  83406. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  83407. }
  83408. /*
  83409. ** file_format==1 Version 3.0.0.
  83410. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  83411. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  83412. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  83413. */
  83414. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  83415. if( pDb->pSchema->file_format==0 ){
  83416. pDb->pSchema->file_format = 1;
  83417. }
  83418. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  83419. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  83420. rc = SQLITE_ERROR;
  83421. goto initone_error_out;
  83422. }
  83423. /* Ticket #2804: When we open a database in the newer file format,
  83424. ** clear the legacy_file_format pragma flag so that a VACUUM will
  83425. ** not downgrade the database and thus invalidate any descending
  83426. ** indices that the user might have created.
  83427. */
  83428. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  83429. db->flags &= ~SQLITE_LegacyFileFmt;
  83430. }
  83431. /* Read the schema information out of the schema tables
  83432. */
  83433. assert( db->init.busy );
  83434. {
  83435. char *zSql;
  83436. zSql = sqlite3MPrintf(db,
  83437. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  83438. db->aDb[iDb].zName, zMasterName);
  83439. #ifndef SQLITE_OMIT_AUTHORIZATION
  83440. {
  83441. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  83442. xAuth = db->xAuth;
  83443. db->xAuth = 0;
  83444. #endif
  83445. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  83446. #ifndef SQLITE_OMIT_AUTHORIZATION
  83447. db->xAuth = xAuth;
  83448. }
  83449. #endif
  83450. if( rc==SQLITE_OK ) rc = initData.rc;
  83451. sqlite3DbFree(db, zSql);
  83452. #ifndef SQLITE_OMIT_ANALYZE
  83453. if( rc==SQLITE_OK ){
  83454. sqlite3AnalysisLoad(db, iDb);
  83455. }
  83456. #endif
  83457. }
  83458. if( db->mallocFailed ){
  83459. rc = SQLITE_NOMEM;
  83460. sqlite3ResetInternalSchema(db, -1);
  83461. }
  83462. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  83463. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  83464. ** the schema loaded, even if errors occurred. In this situation the
  83465. ** current sqlite3_prepare() operation will fail, but the following one
  83466. ** will attempt to compile the supplied statement against whatever subset
  83467. ** of the schema was loaded before the error occurred. The primary
  83468. ** purpose of this is to allow access to the sqlite_master table
  83469. ** even when its contents have been corrupted.
  83470. */
  83471. DbSetProperty(db, iDb, DB_SchemaLoaded);
  83472. rc = SQLITE_OK;
  83473. }
  83474. /* Jump here for an error that occurs after successfully allocating
  83475. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  83476. ** before that point, jump to error_out.
  83477. */
  83478. initone_error_out:
  83479. if( openedTransaction ){
  83480. sqlite3BtreeCommit(pDb->pBt);
  83481. }
  83482. sqlite3BtreeLeave(pDb->pBt);
  83483. error_out:
  83484. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  83485. db->mallocFailed = 1;
  83486. }
  83487. return rc;
  83488. }
  83489. /*
  83490. ** Initialize all database files - the main database file, the file
  83491. ** used to store temporary tables, and any additional database files
  83492. ** created using ATTACH statements. Return a success code. If an
  83493. ** error occurs, write an error message into *pzErrMsg.
  83494. **
  83495. ** After a database is initialized, the DB_SchemaLoaded bit is set
  83496. ** bit is set in the flags field of the Db structure. If the database
  83497. ** file was of zero-length, then the DB_Empty flag is also set.
  83498. */
  83499. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  83500. int i, rc;
  83501. int commit_internal = !(db->flags&SQLITE_InternChanges);
  83502. assert( sqlite3_mutex_held(db->mutex) );
  83503. rc = SQLITE_OK;
  83504. db->init.busy = 1;
  83505. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  83506. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  83507. rc = sqlite3InitOne(db, i, pzErrMsg);
  83508. if( rc ){
  83509. sqlite3ResetInternalSchema(db, i);
  83510. }
  83511. }
  83512. /* Once all the other databases have been initialised, load the schema
  83513. ** for the TEMP database. This is loaded last, as the TEMP database
  83514. ** schema may contain references to objects in other databases.
  83515. */
  83516. #ifndef SQLITE_OMIT_TEMPDB
  83517. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  83518. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  83519. rc = sqlite3InitOne(db, 1, pzErrMsg);
  83520. if( rc ){
  83521. sqlite3ResetInternalSchema(db, 1);
  83522. }
  83523. }
  83524. #endif
  83525. db->init.busy = 0;
  83526. if( rc==SQLITE_OK && commit_internal ){
  83527. sqlite3CommitInternalChanges(db);
  83528. }
  83529. return rc;
  83530. }
  83531. /*
  83532. ** This routine is a no-op if the database schema is already initialised.
  83533. ** Otherwise, the schema is loaded. An error code is returned.
  83534. */
  83535. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  83536. int rc = SQLITE_OK;
  83537. sqlite3 *db = pParse->db;
  83538. assert( sqlite3_mutex_held(db->mutex) );
  83539. if( !db->init.busy ){
  83540. rc = sqlite3Init(db, &pParse->zErrMsg);
  83541. }
  83542. if( rc!=SQLITE_OK ){
  83543. pParse->rc = rc;
  83544. pParse->nErr++;
  83545. }
  83546. return rc;
  83547. }
  83548. /*
  83549. ** Check schema cookies in all databases. If any cookie is out
  83550. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  83551. ** make no changes to pParse->rc.
  83552. */
  83553. static void schemaIsValid(Parse *pParse){
  83554. sqlite3 *db = pParse->db;
  83555. int iDb;
  83556. int rc;
  83557. int cookie;
  83558. assert( pParse->checkSchema );
  83559. assert( sqlite3_mutex_held(db->mutex) );
  83560. for(iDb=0; iDb<db->nDb; iDb++){
  83561. int openedTransaction = 0; /* True if a transaction is opened */
  83562. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  83563. if( pBt==0 ) continue;
  83564. /* If there is not already a read-only (or read-write) transaction opened
  83565. ** on the b-tree database, open one now. If a transaction is opened, it
  83566. ** will be closed immediately after reading the meta-value. */
  83567. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  83568. rc = sqlite3BtreeBeginTrans(pBt, 0);
  83569. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  83570. db->mallocFailed = 1;
  83571. }
  83572. if( rc!=SQLITE_OK ) return;
  83573. openedTransaction = 1;
  83574. }
  83575. /* Read the schema cookie from the database. If it does not match the
  83576. ** value stored as part of the in-memory schema representation,
  83577. ** set Parse.rc to SQLITE_SCHEMA. */
  83578. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  83579. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83580. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  83581. sqlite3ResetInternalSchema(db, iDb);
  83582. pParse->rc = SQLITE_SCHEMA;
  83583. }
  83584. /* Close the transaction, if one was opened. */
  83585. if( openedTransaction ){
  83586. sqlite3BtreeCommit(pBt);
  83587. }
  83588. }
  83589. }
  83590. /*
  83591. ** Convert a schema pointer into the iDb index that indicates
  83592. ** which database file in db->aDb[] the schema refers to.
  83593. **
  83594. ** If the same database is attached more than once, the first
  83595. ** attached database is returned.
  83596. */
  83597. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  83598. int i = -1000000;
  83599. /* If pSchema is NULL, then return -1000000. This happens when code in
  83600. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  83601. ** created by a sub-select). In this case the return value of this
  83602. ** function should never be used.
  83603. **
  83604. ** We return -1000000 instead of the more usual -1 simply because using
  83605. ** -1000000 as the incorrect index into db->aDb[] is much
  83606. ** more likely to cause a segfault than -1 (of course there are assert()
  83607. ** statements too, but it never hurts to play the odds).
  83608. */
  83609. assert( sqlite3_mutex_held(db->mutex) );
  83610. if( pSchema ){
  83611. for(i=0; ALWAYS(i<db->nDb); i++){
  83612. if( db->aDb[i].pSchema==pSchema ){
  83613. break;
  83614. }
  83615. }
  83616. assert( i>=0 && i<db->nDb );
  83617. }
  83618. return i;
  83619. }
  83620. /*
  83621. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  83622. */
  83623. static int sqlite3Prepare(
  83624. sqlite3 *db, /* Database handle. */
  83625. const char *zSql, /* UTF-8 encoded SQL statement. */
  83626. int nBytes, /* Length of zSql in bytes. */
  83627. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  83628. Vdbe *pReprepare, /* VM being reprepared */
  83629. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  83630. const char **pzTail /* OUT: End of parsed string */
  83631. ){
  83632. Parse *pParse; /* Parsing context */
  83633. char *zErrMsg = 0; /* Error message */
  83634. int rc = SQLITE_OK; /* Result code */
  83635. int i; /* Loop counter */
  83636. /* Allocate the parsing context */
  83637. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  83638. if( pParse==0 ){
  83639. rc = SQLITE_NOMEM;
  83640. goto end_prepare;
  83641. }
  83642. pParse->pReprepare = pReprepare;
  83643. assert( ppStmt && *ppStmt==0 );
  83644. assert( !db->mallocFailed );
  83645. assert( sqlite3_mutex_held(db->mutex) );
  83646. /* Check to verify that it is possible to get a read lock on all
  83647. ** database schemas. The inability to get a read lock indicates that
  83648. ** some other database connection is holding a write-lock, which in
  83649. ** turn means that the other connection has made uncommitted changes
  83650. ** to the schema.
  83651. **
  83652. ** Were we to proceed and prepare the statement against the uncommitted
  83653. ** schema changes and if those schema changes are subsequently rolled
  83654. ** back and different changes are made in their place, then when this
  83655. ** prepared statement goes to run the schema cookie would fail to detect
  83656. ** the schema change. Disaster would follow.
  83657. **
  83658. ** This thread is currently holding mutexes on all Btrees (because
  83659. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  83660. ** is not possible for another thread to start a new schema change
  83661. ** while this routine is running. Hence, we do not need to hold
  83662. ** locks on the schema, we just need to make sure nobody else is
  83663. ** holding them.
  83664. **
  83665. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  83666. ** but it does *not* override schema lock detection, so this all still
  83667. ** works even if READ_UNCOMMITTED is set.
  83668. */
  83669. for(i=0; i<db->nDb; i++) {
  83670. Btree *pBt = db->aDb[i].pBt;
  83671. if( pBt ){
  83672. assert( sqlite3BtreeHoldsMutex(pBt) );
  83673. rc = sqlite3BtreeSchemaLocked(pBt);
  83674. if( rc ){
  83675. const char *zDb = db->aDb[i].zName;
  83676. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  83677. testcase( db->flags & SQLITE_ReadUncommitted );
  83678. goto end_prepare;
  83679. }
  83680. }
  83681. }
  83682. sqlite3VtabUnlockList(db);
  83683. pParse->db = db;
  83684. pParse->nQueryLoop = (double)1;
  83685. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  83686. char *zSqlCopy;
  83687. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  83688. testcase( nBytes==mxLen );
  83689. testcase( nBytes==mxLen+1 );
  83690. if( nBytes>mxLen ){
  83691. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  83692. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  83693. goto end_prepare;
  83694. }
  83695. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  83696. if( zSqlCopy ){
  83697. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  83698. sqlite3DbFree(db, zSqlCopy);
  83699. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  83700. }else{
  83701. pParse->zTail = &zSql[nBytes];
  83702. }
  83703. }else{
  83704. sqlite3RunParser(pParse, zSql, &zErrMsg);
  83705. }
  83706. assert( 1==(int)pParse->nQueryLoop );
  83707. if( db->mallocFailed ){
  83708. pParse->rc = SQLITE_NOMEM;
  83709. }
  83710. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  83711. if( pParse->checkSchema ){
  83712. schemaIsValid(pParse);
  83713. }
  83714. if( db->mallocFailed ){
  83715. pParse->rc = SQLITE_NOMEM;
  83716. }
  83717. if( pzTail ){
  83718. *pzTail = pParse->zTail;
  83719. }
  83720. rc = pParse->rc;
  83721. #ifndef SQLITE_OMIT_EXPLAIN
  83722. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  83723. static const char * const azColName[] = {
  83724. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  83725. "selectid", "order", "from", "detail"
  83726. };
  83727. int iFirst, mx;
  83728. if( pParse->explain==2 ){
  83729. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  83730. iFirst = 8;
  83731. mx = 12;
  83732. }else{
  83733. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  83734. iFirst = 0;
  83735. mx = 8;
  83736. }
  83737. for(i=iFirst; i<mx; i++){
  83738. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  83739. azColName[i], SQLITE_STATIC);
  83740. }
  83741. }
  83742. #endif
  83743. assert( db->init.busy==0 || saveSqlFlag==0 );
  83744. if( db->init.busy==0 ){
  83745. Vdbe *pVdbe = pParse->pVdbe;
  83746. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  83747. }
  83748. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  83749. sqlite3VdbeFinalize(pParse->pVdbe);
  83750. assert(!(*ppStmt));
  83751. }else{
  83752. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  83753. }
  83754. if( zErrMsg ){
  83755. sqlite3Error(db, rc, "%s", zErrMsg);
  83756. sqlite3DbFree(db, zErrMsg);
  83757. }else{
  83758. sqlite3Error(db, rc, 0);
  83759. }
  83760. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  83761. while( pParse->pTriggerPrg ){
  83762. TriggerPrg *pT = pParse->pTriggerPrg;
  83763. pParse->pTriggerPrg = pT->pNext;
  83764. sqlite3DbFree(db, pT);
  83765. }
  83766. end_prepare:
  83767. sqlite3StackFree(db, pParse);
  83768. rc = sqlite3ApiExit(db, rc);
  83769. assert( (rc&db->errMask)==rc );
  83770. return rc;
  83771. }
  83772. static int sqlite3LockAndPrepare(
  83773. sqlite3 *db, /* Database handle. */
  83774. const char *zSql, /* UTF-8 encoded SQL statement. */
  83775. int nBytes, /* Length of zSql in bytes. */
  83776. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  83777. Vdbe *pOld, /* VM being reprepared */
  83778. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  83779. const char **pzTail /* OUT: End of parsed string */
  83780. ){
  83781. int rc;
  83782. assert( ppStmt!=0 );
  83783. *ppStmt = 0;
  83784. if( !sqlite3SafetyCheckOk(db) ){
  83785. return SQLITE_MISUSE_BKPT;
  83786. }
  83787. sqlite3_mutex_enter(db->mutex);
  83788. sqlite3BtreeEnterAll(db);
  83789. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  83790. if( rc==SQLITE_SCHEMA ){
  83791. sqlite3_finalize(*ppStmt);
  83792. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  83793. }
  83794. sqlite3BtreeLeaveAll(db);
  83795. sqlite3_mutex_leave(db->mutex);
  83796. return rc;
  83797. }
  83798. /*
  83799. ** Rerun the compilation of a statement after a schema change.
  83800. **
  83801. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  83802. ** if the statement cannot be recompiled because another connection has
  83803. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  83804. ** occurs, return SQLITE_SCHEMA.
  83805. */
  83806. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  83807. int rc;
  83808. sqlite3_stmt *pNew;
  83809. const char *zSql;
  83810. sqlite3 *db;
  83811. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  83812. zSql = sqlite3_sql((sqlite3_stmt *)p);
  83813. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  83814. db = sqlite3VdbeDb(p);
  83815. assert( sqlite3_mutex_held(db->mutex) );
  83816. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  83817. if( rc ){
  83818. if( rc==SQLITE_NOMEM ){
  83819. db->mallocFailed = 1;
  83820. }
  83821. assert( pNew==0 );
  83822. return rc;
  83823. }else{
  83824. assert( pNew!=0 );
  83825. }
  83826. sqlite3VdbeSwap((Vdbe*)pNew, p);
  83827. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  83828. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  83829. sqlite3VdbeFinalize((Vdbe*)pNew);
  83830. return SQLITE_OK;
  83831. }
  83832. /*
  83833. ** Two versions of the official API. Legacy and new use. In the legacy
  83834. ** version, the original SQL text is not saved in the prepared statement
  83835. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  83836. ** sqlite3_step(). In the new version, the original SQL text is retained
  83837. ** and the statement is automatically recompiled if an schema change
  83838. ** occurs.
  83839. */
  83840. SQLITE_API int sqlite3_prepare(
  83841. sqlite3 *db, /* Database handle. */
  83842. const char *zSql, /* UTF-8 encoded SQL statement. */
  83843. int nBytes, /* Length of zSql in bytes. */
  83844. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  83845. const char **pzTail /* OUT: End of parsed string */
  83846. ){
  83847. int rc;
  83848. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  83849. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  83850. return rc;
  83851. }
  83852. SQLITE_API int sqlite3_prepare_v2(
  83853. sqlite3 *db, /* Database handle. */
  83854. const char *zSql, /* UTF-8 encoded SQL statement. */
  83855. int nBytes, /* Length of zSql in bytes. */
  83856. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  83857. const char **pzTail /* OUT: End of parsed string */
  83858. ){
  83859. int rc;
  83860. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  83861. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  83862. return rc;
  83863. }
  83864. #ifndef SQLITE_OMIT_UTF16
  83865. /*
  83866. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  83867. */
  83868. static int sqlite3Prepare16(
  83869. sqlite3 *db, /* Database handle. */
  83870. const void *zSql, /* UTF-16 encoded SQL statement. */
  83871. int nBytes, /* Length of zSql in bytes. */
  83872. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  83873. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  83874. const void **pzTail /* OUT: End of parsed string */
  83875. ){
  83876. /* This function currently works by first transforming the UTF-16
  83877. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  83878. ** tricky bit is figuring out the pointer to return in *pzTail.
  83879. */
  83880. char *zSql8;
  83881. const char *zTail8 = 0;
  83882. int rc = SQLITE_OK;
  83883. assert( ppStmt );
  83884. *ppStmt = 0;
  83885. if( !sqlite3SafetyCheckOk(db) ){
  83886. return SQLITE_MISUSE_BKPT;
  83887. }
  83888. sqlite3_mutex_enter(db->mutex);
  83889. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  83890. if( zSql8 ){
  83891. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  83892. }
  83893. if( zTail8 && pzTail ){
  83894. /* If sqlite3_prepare returns a tail pointer, we calculate the
  83895. ** equivalent pointer into the UTF-16 string by counting the unicode
  83896. ** characters between zSql8 and zTail8, and then returning a pointer
  83897. ** the same number of characters into the UTF-16 string.
  83898. */
  83899. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  83900. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  83901. }
  83902. sqlite3DbFree(db, zSql8);
  83903. rc = sqlite3ApiExit(db, rc);
  83904. sqlite3_mutex_leave(db->mutex);
  83905. return rc;
  83906. }
  83907. /*
  83908. ** Two versions of the official API. Legacy and new use. In the legacy
  83909. ** version, the original SQL text is not saved in the prepared statement
  83910. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  83911. ** sqlite3_step(). In the new version, the original SQL text is retained
  83912. ** and the statement is automatically recompiled if an schema change
  83913. ** occurs.
  83914. */
  83915. SQLITE_API int sqlite3_prepare16(
  83916. sqlite3 *db, /* Database handle. */
  83917. const void *zSql, /* UTF-16 encoded SQL statement. */
  83918. int nBytes, /* Length of zSql in bytes. */
  83919. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  83920. const void **pzTail /* OUT: End of parsed string */
  83921. ){
  83922. int rc;
  83923. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  83924. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  83925. return rc;
  83926. }
  83927. SQLITE_API int sqlite3_prepare16_v2(
  83928. sqlite3 *db, /* Database handle. */
  83929. const void *zSql, /* UTF-16 encoded SQL statement. */
  83930. int nBytes, /* Length of zSql in bytes. */
  83931. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  83932. const void **pzTail /* OUT: End of parsed string */
  83933. ){
  83934. int rc;
  83935. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  83936. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  83937. return rc;
  83938. }
  83939. #endif /* SQLITE_OMIT_UTF16 */
  83940. /************** End of prepare.c *********************************************/
  83941. /************** Begin file select.c ******************************************/
  83942. /*
  83943. ** 2001 September 15
  83944. **
  83945. ** The author disclaims copyright to this source code. In place of
  83946. ** a legal notice, here is a blessing:
  83947. **
  83948. ** May you do good and not evil.
  83949. ** May you find forgiveness for yourself and forgive others.
  83950. ** May you share freely, never taking more than you give.
  83951. **
  83952. *************************************************************************
  83953. ** This file contains C code routines that are called by the parser
  83954. ** to handle SELECT statements in SQLite.
  83955. */
  83956. /*
  83957. ** Delete all the content of a Select structure but do not deallocate
  83958. ** the select structure itself.
  83959. */
  83960. static void clearSelect(sqlite3 *db, Select *p){
  83961. sqlite3ExprListDelete(db, p->pEList);
  83962. sqlite3SrcListDelete(db, p->pSrc);
  83963. sqlite3ExprDelete(db, p->pWhere);
  83964. sqlite3ExprListDelete(db, p->pGroupBy);
  83965. sqlite3ExprDelete(db, p->pHaving);
  83966. sqlite3ExprListDelete(db, p->pOrderBy);
  83967. sqlite3SelectDelete(db, p->pPrior);
  83968. sqlite3ExprDelete(db, p->pLimit);
  83969. sqlite3ExprDelete(db, p->pOffset);
  83970. }
  83971. /*
  83972. ** Initialize a SelectDest structure.
  83973. */
  83974. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  83975. pDest->eDest = (u8)eDest;
  83976. pDest->iParm = iParm;
  83977. pDest->affinity = 0;
  83978. pDest->iMem = 0;
  83979. pDest->nMem = 0;
  83980. }
  83981. /*
  83982. ** Allocate a new Select structure and return a pointer to that
  83983. ** structure.
  83984. */
  83985. SQLITE_PRIVATE Select *sqlite3SelectNew(
  83986. Parse *pParse, /* Parsing context */
  83987. ExprList *pEList, /* which columns to include in the result */
  83988. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  83989. Expr *pWhere, /* the WHERE clause */
  83990. ExprList *pGroupBy, /* the GROUP BY clause */
  83991. Expr *pHaving, /* the HAVING clause */
  83992. ExprList *pOrderBy, /* the ORDER BY clause */
  83993. int isDistinct, /* true if the DISTINCT keyword is present */
  83994. Expr *pLimit, /* LIMIT value. NULL means not used */
  83995. Expr *pOffset /* OFFSET value. NULL means no offset */
  83996. ){
  83997. Select *pNew;
  83998. Select standin;
  83999. sqlite3 *db = pParse->db;
  84000. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  84001. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  84002. if( pNew==0 ){
  84003. pNew = &standin;
  84004. memset(pNew, 0, sizeof(*pNew));
  84005. }
  84006. if( pEList==0 ){
  84007. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  84008. }
  84009. pNew->pEList = pEList;
  84010. pNew->pSrc = pSrc;
  84011. pNew->pWhere = pWhere;
  84012. pNew->pGroupBy = pGroupBy;
  84013. pNew->pHaving = pHaving;
  84014. pNew->pOrderBy = pOrderBy;
  84015. pNew->selFlags = isDistinct ? SF_Distinct : 0;
  84016. pNew->op = TK_SELECT;
  84017. pNew->pLimit = pLimit;
  84018. pNew->pOffset = pOffset;
  84019. assert( pOffset==0 || pLimit!=0 );
  84020. pNew->addrOpenEphm[0] = -1;
  84021. pNew->addrOpenEphm[1] = -1;
  84022. pNew->addrOpenEphm[2] = -1;
  84023. if( db->mallocFailed ) {
  84024. clearSelect(db, pNew);
  84025. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  84026. pNew = 0;
  84027. }
  84028. return pNew;
  84029. }
  84030. /*
  84031. ** Delete the given Select structure and all of its substructures.
  84032. */
  84033. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  84034. if( p ){
  84035. clearSelect(db, p);
  84036. sqlite3DbFree(db, p);
  84037. }
  84038. }
  84039. /*
  84040. ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
  84041. ** type of join. Return an integer constant that expresses that type
  84042. ** in terms of the following bit values:
  84043. **
  84044. ** JT_INNER
  84045. ** JT_CROSS
  84046. ** JT_OUTER
  84047. ** JT_NATURAL
  84048. ** JT_LEFT
  84049. ** JT_RIGHT
  84050. **
  84051. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  84052. **
  84053. ** If an illegal or unsupported join type is seen, then still return
  84054. ** a join type, but put an error in the pParse structure.
  84055. */
  84056. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  84057. int jointype = 0;
  84058. Token *apAll[3];
  84059. Token *p;
  84060. /* 0123456789 123456789 123456789 123 */
  84061. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  84062. static const struct {
  84063. u8 i; /* Beginning of keyword text in zKeyText[] */
  84064. u8 nChar; /* Length of the keyword in characters */
  84065. u8 code; /* Join type mask */
  84066. } aKeyword[] = {
  84067. /* natural */ { 0, 7, JT_NATURAL },
  84068. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  84069. /* outer */ { 10, 5, JT_OUTER },
  84070. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  84071. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  84072. /* inner */ { 23, 5, JT_INNER },
  84073. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  84074. };
  84075. int i, j;
  84076. apAll[0] = pA;
  84077. apAll[1] = pB;
  84078. apAll[2] = pC;
  84079. for(i=0; i<3 && apAll[i]; i++){
  84080. p = apAll[i];
  84081. for(j=0; j<ArraySize(aKeyword); j++){
  84082. if( p->n==aKeyword[j].nChar
  84083. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  84084. jointype |= aKeyword[j].code;
  84085. break;
  84086. }
  84087. }
  84088. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  84089. if( j>=ArraySize(aKeyword) ){
  84090. jointype |= JT_ERROR;
  84091. break;
  84092. }
  84093. }
  84094. if(
  84095. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  84096. (jointype & JT_ERROR)!=0
  84097. ){
  84098. const char *zSp = " ";
  84099. assert( pB!=0 );
  84100. if( pC==0 ){ zSp++; }
  84101. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  84102. "%T %T%s%T", pA, pB, zSp, pC);
  84103. jointype = JT_INNER;
  84104. }else if( (jointype & JT_OUTER)!=0
  84105. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  84106. sqlite3ErrorMsg(pParse,
  84107. "RIGHT and FULL OUTER JOINs are not currently supported");
  84108. jointype = JT_INNER;
  84109. }
  84110. return jointype;
  84111. }
  84112. /*
  84113. ** Return the index of a column in a table. Return -1 if the column
  84114. ** is not contained in the table.
  84115. */
  84116. static int columnIndex(Table *pTab, const char *zCol){
  84117. int i;
  84118. for(i=0; i<pTab->nCol; i++){
  84119. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  84120. }
  84121. return -1;
  84122. }
  84123. /*
  84124. ** Search the first N tables in pSrc, from left to right, looking for a
  84125. ** table that has a column named zCol.
  84126. **
  84127. ** When found, set *piTab and *piCol to the table index and column index
  84128. ** of the matching column and return TRUE.
  84129. **
  84130. ** If not found, return FALSE.
  84131. */
  84132. static int tableAndColumnIndex(
  84133. SrcList *pSrc, /* Array of tables to search */
  84134. int N, /* Number of tables in pSrc->a[] to search */
  84135. const char *zCol, /* Name of the column we are looking for */
  84136. int *piTab, /* Write index of pSrc->a[] here */
  84137. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  84138. ){
  84139. int i; /* For looping over tables in pSrc */
  84140. int iCol; /* Index of column matching zCol */
  84141. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  84142. for(i=0; i<N; i++){
  84143. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  84144. if( iCol>=0 ){
  84145. if( piTab ){
  84146. *piTab = i;
  84147. *piCol = iCol;
  84148. }
  84149. return 1;
  84150. }
  84151. }
  84152. return 0;
  84153. }
  84154. /*
  84155. ** This function is used to add terms implied by JOIN syntax to the
  84156. ** WHERE clause expression of a SELECT statement. The new term, which
  84157. ** is ANDed with the existing WHERE clause, is of the form:
  84158. **
  84159. ** (tab1.col1 = tab2.col2)
  84160. **
  84161. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  84162. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  84163. ** column iColRight of tab2.
  84164. */
  84165. static void addWhereTerm(
  84166. Parse *pParse, /* Parsing context */
  84167. SrcList *pSrc, /* List of tables in FROM clause */
  84168. int iLeft, /* Index of first table to join in pSrc */
  84169. int iColLeft, /* Index of column in first table */
  84170. int iRight, /* Index of second table in pSrc */
  84171. int iColRight, /* Index of column in second table */
  84172. int isOuterJoin, /* True if this is an OUTER join */
  84173. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  84174. ){
  84175. sqlite3 *db = pParse->db;
  84176. Expr *pE1;
  84177. Expr *pE2;
  84178. Expr *pEq;
  84179. assert( iLeft<iRight );
  84180. assert( pSrc->nSrc>iRight );
  84181. assert( pSrc->a[iLeft].pTab );
  84182. assert( pSrc->a[iRight].pTab );
  84183. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  84184. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  84185. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  84186. if( pEq && isOuterJoin ){
  84187. ExprSetProperty(pEq, EP_FromJoin);
  84188. assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
  84189. ExprSetIrreducible(pEq);
  84190. pEq->iRightJoinTable = (i16)pE2->iTable;
  84191. }
  84192. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  84193. }
  84194. /*
  84195. ** Set the EP_FromJoin property on all terms of the given expression.
  84196. ** And set the Expr.iRightJoinTable to iTable for every term in the
  84197. ** expression.
  84198. **
  84199. ** The EP_FromJoin property is used on terms of an expression to tell
  84200. ** the LEFT OUTER JOIN processing logic that this term is part of the
  84201. ** join restriction specified in the ON or USING clause and not a part
  84202. ** of the more general WHERE clause. These terms are moved over to the
  84203. ** WHERE clause during join processing but we need to remember that they
  84204. ** originated in the ON or USING clause.
  84205. **
  84206. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  84207. ** expression depends on table iRightJoinTable even if that table is not
  84208. ** explicitly mentioned in the expression. That information is needed
  84209. ** for cases like this:
  84210. **
  84211. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  84212. **
  84213. ** The where clause needs to defer the handling of the t1.x=5
  84214. ** term until after the t2 loop of the join. In that way, a
  84215. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  84216. ** defer the handling of t1.x=5, it will be processed immediately
  84217. ** after the t1 loop and rows with t1.x!=5 will never appear in
  84218. ** the output, which is incorrect.
  84219. */
  84220. static void setJoinExpr(Expr *p, int iTable){
  84221. while( p ){
  84222. ExprSetProperty(p, EP_FromJoin);
  84223. assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
  84224. ExprSetIrreducible(p);
  84225. p->iRightJoinTable = (i16)iTable;
  84226. setJoinExpr(p->pLeft, iTable);
  84227. p = p->pRight;
  84228. }
  84229. }
  84230. /*
  84231. ** This routine processes the join information for a SELECT statement.
  84232. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  84233. ** NATURAL joins also create extra WHERE clause terms.
  84234. **
  84235. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  84236. ** The left most table is the first entry in Select.pSrc. The right-most
  84237. ** table is the last entry. The join operator is held in the entry to
  84238. ** the left. Thus entry 0 contains the join operator for the join between
  84239. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  84240. ** also attached to the left entry.
  84241. **
  84242. ** This routine returns the number of errors encountered.
  84243. */
  84244. static int sqliteProcessJoin(Parse *pParse, Select *p){
  84245. SrcList *pSrc; /* All tables in the FROM clause */
  84246. int i, j; /* Loop counters */
  84247. struct SrcList_item *pLeft; /* Left table being joined */
  84248. struct SrcList_item *pRight; /* Right table being joined */
  84249. pSrc = p->pSrc;
  84250. pLeft = &pSrc->a[0];
  84251. pRight = &pLeft[1];
  84252. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  84253. Table *pLeftTab = pLeft->pTab;
  84254. Table *pRightTab = pRight->pTab;
  84255. int isOuter;
  84256. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  84257. isOuter = (pRight->jointype & JT_OUTER)!=0;
  84258. /* When the NATURAL keyword is present, add WHERE clause terms for
  84259. ** every column that the two tables have in common.
  84260. */
  84261. if( pRight->jointype & JT_NATURAL ){
  84262. if( pRight->pOn || pRight->pUsing ){
  84263. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  84264. "an ON or USING clause", 0);
  84265. return 1;
  84266. }
  84267. for(j=0; j<pRightTab->nCol; j++){
  84268. char *zName; /* Name of column in the right table */
  84269. int iLeft; /* Matching left table */
  84270. int iLeftCol; /* Matching column in the left table */
  84271. zName = pRightTab->aCol[j].zName;
  84272. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  84273. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  84274. isOuter, &p->pWhere);
  84275. }
  84276. }
  84277. }
  84278. /* Disallow both ON and USING clauses in the same join
  84279. */
  84280. if( pRight->pOn && pRight->pUsing ){
  84281. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  84282. "clauses in the same join");
  84283. return 1;
  84284. }
  84285. /* Add the ON clause to the end of the WHERE clause, connected by
  84286. ** an AND operator.
  84287. */
  84288. if( pRight->pOn ){
  84289. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  84290. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  84291. pRight->pOn = 0;
  84292. }
  84293. /* Create extra terms on the WHERE clause for each column named
  84294. ** in the USING clause. Example: If the two tables to be joined are
  84295. ** A and B and the USING clause names X, Y, and Z, then add this
  84296. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  84297. ** Report an error if any column mentioned in the USING clause is
  84298. ** not contained in both tables to be joined.
  84299. */
  84300. if( pRight->pUsing ){
  84301. IdList *pList = pRight->pUsing;
  84302. for(j=0; j<pList->nId; j++){
  84303. char *zName; /* Name of the term in the USING clause */
  84304. int iLeft; /* Table on the left with matching column name */
  84305. int iLeftCol; /* Column number of matching column on the left */
  84306. int iRightCol; /* Column number of matching column on the right */
  84307. zName = pList->a[j].zName;
  84308. iRightCol = columnIndex(pRightTab, zName);
  84309. if( iRightCol<0
  84310. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  84311. ){
  84312. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  84313. "not present in both tables", zName);
  84314. return 1;
  84315. }
  84316. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  84317. isOuter, &p->pWhere);
  84318. }
  84319. }
  84320. }
  84321. return 0;
  84322. }
  84323. /*
  84324. ** Insert code into "v" that will push the record on the top of the
  84325. ** stack into the sorter.
  84326. */
  84327. static void pushOntoSorter(
  84328. Parse *pParse, /* Parser context */
  84329. ExprList *pOrderBy, /* The ORDER BY clause */
  84330. Select *pSelect, /* The whole SELECT statement */
  84331. int regData /* Register holding data to be sorted */
  84332. ){
  84333. Vdbe *v = pParse->pVdbe;
  84334. int nExpr = pOrderBy->nExpr;
  84335. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  84336. int regRecord = sqlite3GetTempReg(pParse);
  84337. sqlite3ExprCacheClear(pParse);
  84338. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  84339. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  84340. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  84341. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  84342. sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
  84343. sqlite3ReleaseTempReg(pParse, regRecord);
  84344. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  84345. if( pSelect->iLimit ){
  84346. int addr1, addr2;
  84347. int iLimit;
  84348. if( pSelect->iOffset ){
  84349. iLimit = pSelect->iOffset+1;
  84350. }else{
  84351. iLimit = pSelect->iLimit;
  84352. }
  84353. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  84354. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  84355. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  84356. sqlite3VdbeJumpHere(v, addr1);
  84357. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  84358. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  84359. sqlite3VdbeJumpHere(v, addr2);
  84360. }
  84361. }
  84362. /*
  84363. ** Add code to implement the OFFSET
  84364. */
  84365. static void codeOffset(
  84366. Vdbe *v, /* Generate code into this VM */
  84367. Select *p, /* The SELECT statement being coded */
  84368. int iContinue /* Jump here to skip the current record */
  84369. ){
  84370. if( p->iOffset && iContinue!=0 ){
  84371. int addr;
  84372. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  84373. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  84374. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  84375. VdbeComment((v, "skip OFFSET records"));
  84376. sqlite3VdbeJumpHere(v, addr);
  84377. }
  84378. }
  84379. /*
  84380. ** Add code that will check to make sure the N registers starting at iMem
  84381. ** form a distinct entry. iTab is a sorting index that holds previously
  84382. ** seen combinations of the N values. A new entry is made in iTab
  84383. ** if the current N values are new.
  84384. **
  84385. ** A jump to addrRepeat is made and the N+1 values are popped from the
  84386. ** stack if the top N elements are not distinct.
  84387. */
  84388. static void codeDistinct(
  84389. Parse *pParse, /* Parsing and code generating context */
  84390. int iTab, /* A sorting index used to test for distinctness */
  84391. int addrRepeat, /* Jump to here if not distinct */
  84392. int N, /* Number of elements */
  84393. int iMem /* First element */
  84394. ){
  84395. Vdbe *v;
  84396. int r1;
  84397. v = pParse->pVdbe;
  84398. r1 = sqlite3GetTempReg(pParse);
  84399. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
  84400. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  84401. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  84402. sqlite3ReleaseTempReg(pParse, r1);
  84403. }
  84404. #ifndef SQLITE_OMIT_SUBQUERY
  84405. /*
  84406. ** Generate an error message when a SELECT is used within a subexpression
  84407. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  84408. ** column. We do this in a subroutine because the error used to occur
  84409. ** in multiple places. (The error only occurs in one place now, but we
  84410. ** retain the subroutine to minimize code disruption.)
  84411. */
  84412. static int checkForMultiColumnSelectError(
  84413. Parse *pParse, /* Parse context. */
  84414. SelectDest *pDest, /* Destination of SELECT results */
  84415. int nExpr /* Number of result columns returned by SELECT */
  84416. ){
  84417. int eDest = pDest->eDest;
  84418. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  84419. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  84420. "a SELECT that is part of an expression");
  84421. return 1;
  84422. }else{
  84423. return 0;
  84424. }
  84425. }
  84426. #endif
  84427. /*
  84428. ** This routine generates the code for the inside of the inner loop
  84429. ** of a SELECT.
  84430. **
  84431. ** If srcTab and nColumn are both zero, then the pEList expressions
  84432. ** are evaluated in order to get the data for this row. If nColumn>0
  84433. ** then data is pulled from srcTab and pEList is used only to get the
  84434. ** datatypes for each column.
  84435. */
  84436. static void selectInnerLoop(
  84437. Parse *pParse, /* The parser context */
  84438. Select *p, /* The complete select statement being coded */
  84439. ExprList *pEList, /* List of values being extracted */
  84440. int srcTab, /* Pull data from this table */
  84441. int nColumn, /* Number of columns in the source table */
  84442. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  84443. int distinct, /* If >=0, make sure results are distinct */
  84444. SelectDest *pDest, /* How to dispose of the results */
  84445. int iContinue, /* Jump here to continue with next row */
  84446. int iBreak /* Jump here to break out of the inner loop */
  84447. ){
  84448. Vdbe *v = pParse->pVdbe;
  84449. int i;
  84450. int hasDistinct; /* True if the DISTINCT keyword is present */
  84451. int regResult; /* Start of memory holding result set */
  84452. int eDest = pDest->eDest; /* How to dispose of results */
  84453. int iParm = pDest->iParm; /* First argument to disposal method */
  84454. int nResultCol; /* Number of result columns */
  84455. assert( v );
  84456. if( NEVER(v==0) ) return;
  84457. assert( pEList!=0 );
  84458. hasDistinct = distinct>=0;
  84459. if( pOrderBy==0 && !hasDistinct ){
  84460. codeOffset(v, p, iContinue);
  84461. }
  84462. /* Pull the requested columns.
  84463. */
  84464. if( nColumn>0 ){
  84465. nResultCol = nColumn;
  84466. }else{
  84467. nResultCol = pEList->nExpr;
  84468. }
  84469. if( pDest->iMem==0 ){
  84470. pDest->iMem = pParse->nMem+1;
  84471. pDest->nMem = nResultCol;
  84472. pParse->nMem += nResultCol;
  84473. }else{
  84474. assert( pDest->nMem==nResultCol );
  84475. }
  84476. regResult = pDest->iMem;
  84477. if( nColumn>0 ){
  84478. for(i=0; i<nColumn; i++){
  84479. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  84480. }
  84481. }else if( eDest!=SRT_Exists ){
  84482. /* If the destination is an EXISTS(...) expression, the actual
  84483. ** values returned by the SELECT are not required.
  84484. */
  84485. sqlite3ExprCacheClear(pParse);
  84486. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  84487. }
  84488. nColumn = nResultCol;
  84489. /* If the DISTINCT keyword was present on the SELECT statement
  84490. ** and this row has been seen before, then do not make this row
  84491. ** part of the result.
  84492. */
  84493. if( hasDistinct ){
  84494. assert( pEList!=0 );
  84495. assert( pEList->nExpr==nColumn );
  84496. codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
  84497. if( pOrderBy==0 ){
  84498. codeOffset(v, p, iContinue);
  84499. }
  84500. }
  84501. switch( eDest ){
  84502. /* In this mode, write each query result to the key of the temporary
  84503. ** table iParm.
  84504. */
  84505. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  84506. case SRT_Union: {
  84507. int r1;
  84508. r1 = sqlite3GetTempReg(pParse);
  84509. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  84510. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  84511. sqlite3ReleaseTempReg(pParse, r1);
  84512. break;
  84513. }
  84514. /* Construct a record from the query result, but instead of
  84515. ** saving that record, use it as a key to delete elements from
  84516. ** the temporary table iParm.
  84517. */
  84518. case SRT_Except: {
  84519. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  84520. break;
  84521. }
  84522. #endif
  84523. /* Store the result as data using a unique key.
  84524. */
  84525. case SRT_Table:
  84526. case SRT_EphemTab: {
  84527. int r1 = sqlite3GetTempReg(pParse);
  84528. testcase( eDest==SRT_Table );
  84529. testcase( eDest==SRT_EphemTab );
  84530. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  84531. if( pOrderBy ){
  84532. pushOntoSorter(pParse, pOrderBy, p, r1);
  84533. }else{
  84534. int r2 = sqlite3GetTempReg(pParse);
  84535. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  84536. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  84537. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  84538. sqlite3ReleaseTempReg(pParse, r2);
  84539. }
  84540. sqlite3ReleaseTempReg(pParse, r1);
  84541. break;
  84542. }
  84543. #ifndef SQLITE_OMIT_SUBQUERY
  84544. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  84545. ** then there should be a single item on the stack. Write this
  84546. ** item into the set table with bogus data.
  84547. */
  84548. case SRT_Set: {
  84549. assert( nColumn==1 );
  84550. p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
  84551. if( pOrderBy ){
  84552. /* At first glance you would think we could optimize out the
  84553. ** ORDER BY in this case since the order of entries in the set
  84554. ** does not matter. But there might be a LIMIT clause, in which
  84555. ** case the order does matter */
  84556. pushOntoSorter(pParse, pOrderBy, p, regResult);
  84557. }else{
  84558. int r1 = sqlite3GetTempReg(pParse);
  84559. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
  84560. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  84561. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  84562. sqlite3ReleaseTempReg(pParse, r1);
  84563. }
  84564. break;
  84565. }
  84566. /* If any row exist in the result set, record that fact and abort.
  84567. */
  84568. case SRT_Exists: {
  84569. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  84570. /* The LIMIT clause will terminate the loop for us */
  84571. break;
  84572. }
  84573. /* If this is a scalar select that is part of an expression, then
  84574. ** store the results in the appropriate memory cell and break out
  84575. ** of the scan loop.
  84576. */
  84577. case SRT_Mem: {
  84578. assert( nColumn==1 );
  84579. if( pOrderBy ){
  84580. pushOntoSorter(pParse, pOrderBy, p, regResult);
  84581. }else{
  84582. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  84583. /* The LIMIT clause will jump out of the loop for us */
  84584. }
  84585. break;
  84586. }
  84587. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  84588. /* Send the data to the callback function or to a subroutine. In the
  84589. ** case of a subroutine, the subroutine itself is responsible for
  84590. ** popping the data from the stack.
  84591. */
  84592. case SRT_Coroutine:
  84593. case SRT_Output: {
  84594. testcase( eDest==SRT_Coroutine );
  84595. testcase( eDest==SRT_Output );
  84596. if( pOrderBy ){
  84597. int r1 = sqlite3GetTempReg(pParse);
  84598. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  84599. pushOntoSorter(pParse, pOrderBy, p, r1);
  84600. sqlite3ReleaseTempReg(pParse, r1);
  84601. }else if( eDest==SRT_Coroutine ){
  84602. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  84603. }else{
  84604. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  84605. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  84606. }
  84607. break;
  84608. }
  84609. #if !defined(SQLITE_OMIT_TRIGGER)
  84610. /* Discard the results. This is used for SELECT statements inside
  84611. ** the body of a TRIGGER. The purpose of such selects is to call
  84612. ** user-defined functions that have side effects. We do not care
  84613. ** about the actual results of the select.
  84614. */
  84615. default: {
  84616. assert( eDest==SRT_Discard );
  84617. break;
  84618. }
  84619. #endif
  84620. }
  84621. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  84622. ** there is a sorter, in which case the sorter has already limited
  84623. ** the output for us.
  84624. */
  84625. if( pOrderBy==0 && p->iLimit ){
  84626. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  84627. }
  84628. }
  84629. /*
  84630. ** Given an expression list, generate a KeyInfo structure that records
  84631. ** the collating sequence for each expression in that expression list.
  84632. **
  84633. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  84634. ** KeyInfo structure is appropriate for initializing a virtual index to
  84635. ** implement that clause. If the ExprList is the result set of a SELECT
  84636. ** then the KeyInfo structure is appropriate for initializing a virtual
  84637. ** index to implement a DISTINCT test.
  84638. **
  84639. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  84640. ** function is responsible for seeing that this structure is eventually
  84641. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  84642. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  84643. */
  84644. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  84645. sqlite3 *db = pParse->db;
  84646. int nExpr;
  84647. KeyInfo *pInfo;
  84648. struct ExprList_item *pItem;
  84649. int i;
  84650. nExpr = pList->nExpr;
  84651. pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
  84652. if( pInfo ){
  84653. pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
  84654. pInfo->nField = (u16)nExpr;
  84655. pInfo->enc = ENC(db);
  84656. pInfo->db = db;
  84657. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  84658. CollSeq *pColl;
  84659. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  84660. if( !pColl ){
  84661. pColl = db->pDfltColl;
  84662. }
  84663. pInfo->aColl[i] = pColl;
  84664. pInfo->aSortOrder[i] = pItem->sortOrder;
  84665. }
  84666. }
  84667. return pInfo;
  84668. }
  84669. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  84670. /*
  84671. ** Name of the connection operator, used for error messages.
  84672. */
  84673. static const char *selectOpName(int id){
  84674. char *z;
  84675. switch( id ){
  84676. case TK_ALL: z = "UNION ALL"; break;
  84677. case TK_INTERSECT: z = "INTERSECT"; break;
  84678. case TK_EXCEPT: z = "EXCEPT"; break;
  84679. default: z = "UNION"; break;
  84680. }
  84681. return z;
  84682. }
  84683. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  84684. #ifndef SQLITE_OMIT_EXPLAIN
  84685. /*
  84686. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  84687. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  84688. ** where the caption is of the form:
  84689. **
  84690. ** "USE TEMP B-TREE FOR xxx"
  84691. **
  84692. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  84693. ** is determined by the zUsage argument.
  84694. */
  84695. static void explainTempTable(Parse *pParse, const char *zUsage){
  84696. if( pParse->explain==2 ){
  84697. Vdbe *v = pParse->pVdbe;
  84698. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  84699. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  84700. }
  84701. }
  84702. /*
  84703. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  84704. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  84705. ** in sqlite3Select() to assign values to structure member variables that
  84706. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  84707. ** code with #ifndef directives.
  84708. */
  84709. # define explainSetInteger(a, b) a = b
  84710. #else
  84711. /* No-op versions of the explainXXX() functions and macros. */
  84712. # define explainTempTable(y,z)
  84713. # define explainSetInteger(y,z)
  84714. #endif
  84715. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  84716. /*
  84717. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  84718. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  84719. ** where the caption is of one of the two forms:
  84720. **
  84721. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  84722. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  84723. **
  84724. ** where iSub1 and iSub2 are the integers passed as the corresponding
  84725. ** function parameters, and op is the text representation of the parameter
  84726. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  84727. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  84728. ** false, or the second form if it is true.
  84729. */
  84730. static void explainComposite(
  84731. Parse *pParse, /* Parse context */
  84732. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  84733. int iSub1, /* Subquery id 1 */
  84734. int iSub2, /* Subquery id 2 */
  84735. int bUseTmp /* True if a temp table was used */
  84736. ){
  84737. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  84738. if( pParse->explain==2 ){
  84739. Vdbe *v = pParse->pVdbe;
  84740. char *zMsg = sqlite3MPrintf(
  84741. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  84742. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  84743. );
  84744. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  84745. }
  84746. }
  84747. #else
  84748. /* No-op versions of the explainXXX() functions and macros. */
  84749. # define explainComposite(v,w,x,y,z)
  84750. #endif
  84751. /*
  84752. ** If the inner loop was generated using a non-null pOrderBy argument,
  84753. ** then the results were placed in a sorter. After the loop is terminated
  84754. ** we need to run the sorter and output the results. The following
  84755. ** routine generates the code needed to do that.
  84756. */
  84757. static void generateSortTail(
  84758. Parse *pParse, /* Parsing context */
  84759. Select *p, /* The SELECT statement */
  84760. Vdbe *v, /* Generate code into this VDBE */
  84761. int nColumn, /* Number of columns of data */
  84762. SelectDest *pDest /* Write the sorted results here */
  84763. ){
  84764. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  84765. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  84766. int addr;
  84767. int iTab;
  84768. int pseudoTab = 0;
  84769. ExprList *pOrderBy = p->pOrderBy;
  84770. int eDest = pDest->eDest;
  84771. int iParm = pDest->iParm;
  84772. int regRow;
  84773. int regRowid;
  84774. iTab = pOrderBy->iECursor;
  84775. regRow = sqlite3GetTempReg(pParse);
  84776. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  84777. pseudoTab = pParse->nTab++;
  84778. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
  84779. regRowid = 0;
  84780. }else{
  84781. regRowid = sqlite3GetTempReg(pParse);
  84782. }
  84783. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  84784. codeOffset(v, p, addrContinue);
  84785. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
  84786. switch( eDest ){
  84787. case SRT_Table:
  84788. case SRT_EphemTab: {
  84789. testcase( eDest==SRT_Table );
  84790. testcase( eDest==SRT_EphemTab );
  84791. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  84792. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  84793. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  84794. break;
  84795. }
  84796. #ifndef SQLITE_OMIT_SUBQUERY
  84797. case SRT_Set: {
  84798. assert( nColumn==1 );
  84799. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
  84800. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  84801. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  84802. break;
  84803. }
  84804. case SRT_Mem: {
  84805. assert( nColumn==1 );
  84806. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  84807. /* The LIMIT clause will terminate the loop for us */
  84808. break;
  84809. }
  84810. #endif
  84811. default: {
  84812. int i;
  84813. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  84814. testcase( eDest==SRT_Output );
  84815. testcase( eDest==SRT_Coroutine );
  84816. for(i=0; i<nColumn; i++){
  84817. assert( regRow!=pDest->iMem+i );
  84818. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
  84819. if( i==0 ){
  84820. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  84821. }
  84822. }
  84823. if( eDest==SRT_Output ){
  84824. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
  84825. sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
  84826. }else{
  84827. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  84828. }
  84829. break;
  84830. }
  84831. }
  84832. sqlite3ReleaseTempReg(pParse, regRow);
  84833. sqlite3ReleaseTempReg(pParse, regRowid);
  84834. /* The bottom of the loop
  84835. */
  84836. sqlite3VdbeResolveLabel(v, addrContinue);
  84837. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  84838. sqlite3VdbeResolveLabel(v, addrBreak);
  84839. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  84840. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  84841. }
  84842. }
  84843. /*
  84844. ** Return a pointer to a string containing the 'declaration type' of the
  84845. ** expression pExpr. The string may be treated as static by the caller.
  84846. **
  84847. ** The declaration type is the exact datatype definition extracted from the
  84848. ** original CREATE TABLE statement if the expression is a column. The
  84849. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  84850. ** is considered a column can be complex in the presence of subqueries. The
  84851. ** result-set expression in all of the following SELECT statements is
  84852. ** considered a column by this function.
  84853. **
  84854. ** SELECT col FROM tbl;
  84855. ** SELECT (SELECT col FROM tbl;
  84856. ** SELECT (SELECT col FROM tbl);
  84857. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  84858. **
  84859. ** The declaration type for any expression other than a column is NULL.
  84860. */
  84861. static const char *columnType(
  84862. NameContext *pNC,
  84863. Expr *pExpr,
  84864. const char **pzOriginDb,
  84865. const char **pzOriginTab,
  84866. const char **pzOriginCol
  84867. ){
  84868. char const *zType = 0;
  84869. char const *zOriginDb = 0;
  84870. char const *zOriginTab = 0;
  84871. char const *zOriginCol = 0;
  84872. int j;
  84873. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  84874. switch( pExpr->op ){
  84875. case TK_AGG_COLUMN:
  84876. case TK_COLUMN: {
  84877. /* The expression is a column. Locate the table the column is being
  84878. ** extracted from in NameContext.pSrcList. This table may be real
  84879. ** database table or a subquery.
  84880. */
  84881. Table *pTab = 0; /* Table structure column is extracted from */
  84882. Select *pS = 0; /* Select the column is extracted from */
  84883. int iCol = pExpr->iColumn; /* Index of column in pTab */
  84884. testcase( pExpr->op==TK_AGG_COLUMN );
  84885. testcase( pExpr->op==TK_COLUMN );
  84886. while( pNC && !pTab ){
  84887. SrcList *pTabList = pNC->pSrcList;
  84888. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  84889. if( j<pTabList->nSrc ){
  84890. pTab = pTabList->a[j].pTab;
  84891. pS = pTabList->a[j].pSelect;
  84892. }else{
  84893. pNC = pNC->pNext;
  84894. }
  84895. }
  84896. if( pTab==0 ){
  84897. /* At one time, code such as "SELECT new.x" within a trigger would
  84898. ** cause this condition to run. Since then, we have restructured how
  84899. ** trigger code is generated and so this condition is no longer
  84900. ** possible. However, it can still be true for statements like
  84901. ** the following:
  84902. **
  84903. ** CREATE TABLE t1(col INTEGER);
  84904. ** SELECT (SELECT t1.col) FROM FROM t1;
  84905. **
  84906. ** when columnType() is called on the expression "t1.col" in the
  84907. ** sub-select. In this case, set the column type to NULL, even
  84908. ** though it should really be "INTEGER".
  84909. **
  84910. ** This is not a problem, as the column type of "t1.col" is never
  84911. ** used. When columnType() is called on the expression
  84912. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  84913. ** branch below. */
  84914. break;
  84915. }
  84916. assert( pTab && pExpr->pTab==pTab );
  84917. if( pS ){
  84918. /* The "table" is actually a sub-select or a view in the FROM clause
  84919. ** of the SELECT statement. Return the declaration type and origin
  84920. ** data for the result-set column of the sub-select.
  84921. */
  84922. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  84923. /* If iCol is less than zero, then the expression requests the
  84924. ** rowid of the sub-select or view. This expression is legal (see
  84925. ** test case misc2.2.2) - it always evaluates to NULL.
  84926. */
  84927. NameContext sNC;
  84928. Expr *p = pS->pEList->a[iCol].pExpr;
  84929. sNC.pSrcList = pS->pSrc;
  84930. sNC.pNext = pNC;
  84931. sNC.pParse = pNC->pParse;
  84932. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  84933. }
  84934. }else if( ALWAYS(pTab->pSchema) ){
  84935. /* A real table */
  84936. assert( !pS );
  84937. if( iCol<0 ) iCol = pTab->iPKey;
  84938. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  84939. if( iCol<0 ){
  84940. zType = "INTEGER";
  84941. zOriginCol = "rowid";
  84942. }else{
  84943. zType = pTab->aCol[iCol].zType;
  84944. zOriginCol = pTab->aCol[iCol].zName;
  84945. }
  84946. zOriginTab = pTab->zName;
  84947. if( pNC->pParse ){
  84948. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  84949. zOriginDb = pNC->pParse->db->aDb[iDb].zName;
  84950. }
  84951. }
  84952. break;
  84953. }
  84954. #ifndef SQLITE_OMIT_SUBQUERY
  84955. case TK_SELECT: {
  84956. /* The expression is a sub-select. Return the declaration type and
  84957. ** origin info for the single column in the result set of the SELECT
  84958. ** statement.
  84959. */
  84960. NameContext sNC;
  84961. Select *pS = pExpr->x.pSelect;
  84962. Expr *p = pS->pEList->a[0].pExpr;
  84963. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  84964. sNC.pSrcList = pS->pSrc;
  84965. sNC.pNext = pNC;
  84966. sNC.pParse = pNC->pParse;
  84967. zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
  84968. break;
  84969. }
  84970. #endif
  84971. }
  84972. if( pzOriginDb ){
  84973. assert( pzOriginTab && pzOriginCol );
  84974. *pzOriginDb = zOriginDb;
  84975. *pzOriginTab = zOriginTab;
  84976. *pzOriginCol = zOriginCol;
  84977. }
  84978. return zType;
  84979. }
  84980. /*
  84981. ** Generate code that will tell the VDBE the declaration types of columns
  84982. ** in the result set.
  84983. */
  84984. static void generateColumnTypes(
  84985. Parse *pParse, /* Parser context */
  84986. SrcList *pTabList, /* List of tables */
  84987. ExprList *pEList /* Expressions defining the result set */
  84988. ){
  84989. #ifndef SQLITE_OMIT_DECLTYPE
  84990. Vdbe *v = pParse->pVdbe;
  84991. int i;
  84992. NameContext sNC;
  84993. sNC.pSrcList = pTabList;
  84994. sNC.pParse = pParse;
  84995. for(i=0; i<pEList->nExpr; i++){
  84996. Expr *p = pEList->a[i].pExpr;
  84997. const char *zType;
  84998. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  84999. const char *zOrigDb = 0;
  85000. const char *zOrigTab = 0;
  85001. const char *zOrigCol = 0;
  85002. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  85003. /* The vdbe must make its own copy of the column-type and other
  85004. ** column specific strings, in case the schema is reset before this
  85005. ** virtual machine is deleted.
  85006. */
  85007. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  85008. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  85009. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  85010. #else
  85011. zType = columnType(&sNC, p, 0, 0, 0);
  85012. #endif
  85013. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  85014. }
  85015. #endif /* SQLITE_OMIT_DECLTYPE */
  85016. }
  85017. /*
  85018. ** Generate code that will tell the VDBE the names of columns
  85019. ** in the result set. This information is used to provide the
  85020. ** azCol[] values in the callback.
  85021. */
  85022. static void generateColumnNames(
  85023. Parse *pParse, /* Parser context */
  85024. SrcList *pTabList, /* List of tables */
  85025. ExprList *pEList /* Expressions defining the result set */
  85026. ){
  85027. Vdbe *v = pParse->pVdbe;
  85028. int i, j;
  85029. sqlite3 *db = pParse->db;
  85030. int fullNames, shortNames;
  85031. #ifndef SQLITE_OMIT_EXPLAIN
  85032. /* If this is an EXPLAIN, skip this step */
  85033. if( pParse->explain ){
  85034. return;
  85035. }
  85036. #endif
  85037. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  85038. pParse->colNamesSet = 1;
  85039. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  85040. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  85041. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  85042. for(i=0; i<pEList->nExpr; i++){
  85043. Expr *p;
  85044. p = pEList->a[i].pExpr;
  85045. if( NEVER(p==0) ) continue;
  85046. if( pEList->a[i].zName ){
  85047. char *zName = pEList->a[i].zName;
  85048. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  85049. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  85050. Table *pTab;
  85051. char *zCol;
  85052. int iCol = p->iColumn;
  85053. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  85054. if( pTabList->a[j].iCursor==p->iTable ) break;
  85055. }
  85056. assert( j<pTabList->nSrc );
  85057. pTab = pTabList->a[j].pTab;
  85058. if( iCol<0 ) iCol = pTab->iPKey;
  85059. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  85060. if( iCol<0 ){
  85061. zCol = "rowid";
  85062. }else{
  85063. zCol = pTab->aCol[iCol].zName;
  85064. }
  85065. if( !shortNames && !fullNames ){
  85066. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  85067. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  85068. }else if( fullNames ){
  85069. char *zName = 0;
  85070. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  85071. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  85072. }else{
  85073. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  85074. }
  85075. }else{
  85076. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  85077. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  85078. }
  85079. }
  85080. generateColumnTypes(pParse, pTabList, pEList);
  85081. }
  85082. /*
  85083. ** Given a an expression list (which is really the list of expressions
  85084. ** that form the result set of a SELECT statement) compute appropriate
  85085. ** column names for a table that would hold the expression list.
  85086. **
  85087. ** All column names will be unique.
  85088. **
  85089. ** Only the column names are computed. Column.zType, Column.zColl,
  85090. ** and other fields of Column are zeroed.
  85091. **
  85092. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  85093. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  85094. */
  85095. static int selectColumnsFromExprList(
  85096. Parse *pParse, /* Parsing context */
  85097. ExprList *pEList, /* Expr list from which to derive column names */
  85098. int *pnCol, /* Write the number of columns here */
  85099. Column **paCol /* Write the new column list here */
  85100. ){
  85101. sqlite3 *db = pParse->db; /* Database connection */
  85102. int i, j; /* Loop counters */
  85103. int cnt; /* Index added to make the name unique */
  85104. Column *aCol, *pCol; /* For looping over result columns */
  85105. int nCol; /* Number of columns in the result set */
  85106. Expr *p; /* Expression for a single result column */
  85107. char *zName; /* Column name */
  85108. int nName; /* Size of name in zName[] */
  85109. *pnCol = nCol = pEList->nExpr;
  85110. aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  85111. if( aCol==0 ) return SQLITE_NOMEM;
  85112. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  85113. /* Get an appropriate name for the column
  85114. */
  85115. p = pEList->a[i].pExpr;
  85116. assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
  85117. || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
  85118. if( (zName = pEList->a[i].zName)!=0 ){
  85119. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  85120. zName = sqlite3DbStrDup(db, zName);
  85121. }else{
  85122. Expr *pColExpr = p; /* The expression that is the result column name */
  85123. Table *pTab; /* Table associated with this expression */
  85124. while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
  85125. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  85126. /* For columns use the column name name */
  85127. int iCol = pColExpr->iColumn;
  85128. pTab = pColExpr->pTab;
  85129. if( iCol<0 ) iCol = pTab->iPKey;
  85130. zName = sqlite3MPrintf(db, "%s",
  85131. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  85132. }else if( pColExpr->op==TK_ID ){
  85133. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  85134. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  85135. }else{
  85136. /* Use the original text of the column expression as its name */
  85137. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  85138. }
  85139. }
  85140. if( db->mallocFailed ){
  85141. sqlite3DbFree(db, zName);
  85142. break;
  85143. }
  85144. /* Make sure the column name is unique. If the name is not unique,
  85145. ** append a integer to the name so that it becomes unique.
  85146. */
  85147. nName = sqlite3Strlen30(zName);
  85148. for(j=cnt=0; j<i; j++){
  85149. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  85150. char *zNewName;
  85151. zName[nName] = 0;
  85152. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  85153. sqlite3DbFree(db, zName);
  85154. zName = zNewName;
  85155. j = -1;
  85156. if( zName==0 ) break;
  85157. }
  85158. }
  85159. pCol->zName = zName;
  85160. }
  85161. if( db->mallocFailed ){
  85162. for(j=0; j<i; j++){
  85163. sqlite3DbFree(db, aCol[j].zName);
  85164. }
  85165. sqlite3DbFree(db, aCol);
  85166. *paCol = 0;
  85167. *pnCol = 0;
  85168. return SQLITE_NOMEM;
  85169. }
  85170. return SQLITE_OK;
  85171. }
  85172. /*
  85173. ** Add type and collation information to a column list based on
  85174. ** a SELECT statement.
  85175. **
  85176. ** The column list presumably came from selectColumnNamesFromExprList().
  85177. ** The column list has only names, not types or collations. This
  85178. ** routine goes through and adds the types and collations.
  85179. **
  85180. ** This routine requires that all identifiers in the SELECT
  85181. ** statement be resolved.
  85182. */
  85183. static void selectAddColumnTypeAndCollation(
  85184. Parse *pParse, /* Parsing contexts */
  85185. int nCol, /* Number of columns */
  85186. Column *aCol, /* List of columns */
  85187. Select *pSelect /* SELECT used to determine types and collations */
  85188. ){
  85189. sqlite3 *db = pParse->db;
  85190. NameContext sNC;
  85191. Column *pCol;
  85192. CollSeq *pColl;
  85193. int i;
  85194. Expr *p;
  85195. struct ExprList_item *a;
  85196. assert( pSelect!=0 );
  85197. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  85198. assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
  85199. if( db->mallocFailed ) return;
  85200. memset(&sNC, 0, sizeof(sNC));
  85201. sNC.pSrcList = pSelect->pSrc;
  85202. a = pSelect->pEList->a;
  85203. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  85204. p = a[i].pExpr;
  85205. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
  85206. pCol->affinity = sqlite3ExprAffinity(p);
  85207. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  85208. pColl = sqlite3ExprCollSeq(pParse, p);
  85209. if( pColl ){
  85210. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  85211. }
  85212. }
  85213. }
  85214. /*
  85215. ** Given a SELECT statement, generate a Table structure that describes
  85216. ** the result set of that SELECT.
  85217. */
  85218. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  85219. Table *pTab;
  85220. sqlite3 *db = pParse->db;
  85221. int savedFlags;
  85222. savedFlags = db->flags;
  85223. db->flags &= ~SQLITE_FullColNames;
  85224. db->flags |= SQLITE_ShortColNames;
  85225. sqlite3SelectPrep(pParse, pSelect, 0);
  85226. if( pParse->nErr ) return 0;
  85227. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  85228. db->flags = savedFlags;
  85229. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  85230. if( pTab==0 ){
  85231. return 0;
  85232. }
  85233. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  85234. ** is disabled */
  85235. assert( db->lookaside.bEnabled==0 );
  85236. pTab->nRef = 1;
  85237. pTab->zName = 0;
  85238. pTab->nRowEst = 1000000;
  85239. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  85240. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
  85241. pTab->iPKey = -1;
  85242. if( db->mallocFailed ){
  85243. sqlite3DeleteTable(db, pTab);
  85244. return 0;
  85245. }
  85246. return pTab;
  85247. }
  85248. /*
  85249. ** Get a VDBE for the given parser context. Create a new one if necessary.
  85250. ** If an error occurs, return NULL and leave a message in pParse.
  85251. */
  85252. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  85253. Vdbe *v = pParse->pVdbe;
  85254. if( v==0 ){
  85255. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  85256. #ifndef SQLITE_OMIT_TRACE
  85257. if( v ){
  85258. sqlite3VdbeAddOp0(v, OP_Trace);
  85259. }
  85260. #endif
  85261. }
  85262. return v;
  85263. }
  85264. /*
  85265. ** Compute the iLimit and iOffset fields of the SELECT based on the
  85266. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  85267. ** that appear in the original SQL statement after the LIMIT and OFFSET
  85268. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  85269. ** are the integer memory register numbers for counters used to compute
  85270. ** the limit and offset. If there is no limit and/or offset, then
  85271. ** iLimit and iOffset are negative.
  85272. **
  85273. ** This routine changes the values of iLimit and iOffset only if
  85274. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  85275. ** iOffset should have been preset to appropriate default values
  85276. ** (usually but not always -1) prior to calling this routine.
  85277. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  85278. ** redefined. The UNION ALL operator uses this property to force
  85279. ** the reuse of the same limit and offset registers across multiple
  85280. ** SELECT statements.
  85281. */
  85282. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  85283. Vdbe *v = 0;
  85284. int iLimit = 0;
  85285. int iOffset;
  85286. int addr1, n;
  85287. if( p->iLimit ) return;
  85288. /*
  85289. ** "LIMIT -1" always shows all rows. There is some
  85290. ** contraversy about what the correct behavior should be.
  85291. ** The current implementation interprets "LIMIT 0" to mean
  85292. ** no rows.
  85293. */
  85294. sqlite3ExprCacheClear(pParse);
  85295. assert( p->pOffset==0 || p->pLimit!=0 );
  85296. if( p->pLimit ){
  85297. p->iLimit = iLimit = ++pParse->nMem;
  85298. v = sqlite3GetVdbe(pParse);
  85299. if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
  85300. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  85301. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  85302. VdbeComment((v, "LIMIT counter"));
  85303. if( n==0 ){
  85304. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  85305. }else{
  85306. if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
  85307. }
  85308. }else{
  85309. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  85310. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  85311. VdbeComment((v, "LIMIT counter"));
  85312. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  85313. }
  85314. if( p->pOffset ){
  85315. p->iOffset = iOffset = ++pParse->nMem;
  85316. pParse->nMem++; /* Allocate an extra register for limit+offset */
  85317. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  85318. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  85319. VdbeComment((v, "OFFSET counter"));
  85320. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  85321. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  85322. sqlite3VdbeJumpHere(v, addr1);
  85323. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  85324. VdbeComment((v, "LIMIT+OFFSET"));
  85325. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  85326. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  85327. sqlite3VdbeJumpHere(v, addr1);
  85328. }
  85329. }
  85330. }
  85331. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  85332. /*
  85333. ** Return the appropriate collating sequence for the iCol-th column of
  85334. ** the result set for the compound-select statement "p". Return NULL if
  85335. ** the column has no default collating sequence.
  85336. **
  85337. ** The collating sequence for the compound select is taken from the
  85338. ** left-most term of the select that has a collating sequence.
  85339. */
  85340. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  85341. CollSeq *pRet;
  85342. if( p->pPrior ){
  85343. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  85344. }else{
  85345. pRet = 0;
  85346. }
  85347. assert( iCol>=0 );
  85348. if( pRet==0 && iCol<p->pEList->nExpr ){
  85349. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  85350. }
  85351. return pRet;
  85352. }
  85353. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  85354. /* Forward reference */
  85355. static int multiSelectOrderBy(
  85356. Parse *pParse, /* Parsing context */
  85357. Select *p, /* The right-most of SELECTs to be coded */
  85358. SelectDest *pDest /* What to do with query results */
  85359. );
  85360. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  85361. /*
  85362. ** This routine is called to process a compound query form from
  85363. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  85364. ** INTERSECT
  85365. **
  85366. ** "p" points to the right-most of the two queries. the query on the
  85367. ** left is p->pPrior. The left query could also be a compound query
  85368. ** in which case this routine will be called recursively.
  85369. **
  85370. ** The results of the total query are to be written into a destination
  85371. ** of type eDest with parameter iParm.
  85372. **
  85373. ** Example 1: Consider a three-way compound SQL statement.
  85374. **
  85375. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  85376. **
  85377. ** This statement is parsed up as follows:
  85378. **
  85379. ** SELECT c FROM t3
  85380. ** |
  85381. ** `-----> SELECT b FROM t2
  85382. ** |
  85383. ** `------> SELECT a FROM t1
  85384. **
  85385. ** The arrows in the diagram above represent the Select.pPrior pointer.
  85386. ** So if this routine is called with p equal to the t3 query, then
  85387. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  85388. **
  85389. ** Notice that because of the way SQLite parses compound SELECTs, the
  85390. ** individual selects always group from left to right.
  85391. */
  85392. static int multiSelect(
  85393. Parse *pParse, /* Parsing context */
  85394. Select *p, /* The right-most of SELECTs to be coded */
  85395. SelectDest *pDest /* What to do with query results */
  85396. ){
  85397. int rc = SQLITE_OK; /* Success code from a subroutine */
  85398. Select *pPrior; /* Another SELECT immediately to our left */
  85399. Vdbe *v; /* Generate code to this VDBE */
  85400. SelectDest dest; /* Alternative data destination */
  85401. Select *pDelete = 0; /* Chain of simple selects to delete */
  85402. sqlite3 *db; /* Database connection */
  85403. #ifndef SQLITE_OMIT_EXPLAIN
  85404. int iSub1; /* EQP id of left-hand query */
  85405. int iSub2; /* EQP id of right-hand query */
  85406. #endif
  85407. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  85408. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  85409. */
  85410. assert( p && p->pPrior ); /* Calling function guarantees this much */
  85411. db = pParse->db;
  85412. pPrior = p->pPrior;
  85413. assert( pPrior->pRightmost!=pPrior );
  85414. assert( pPrior->pRightmost==p->pRightmost );
  85415. dest = *pDest;
  85416. if( pPrior->pOrderBy ){
  85417. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  85418. selectOpName(p->op));
  85419. rc = 1;
  85420. goto multi_select_end;
  85421. }
  85422. if( pPrior->pLimit ){
  85423. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  85424. selectOpName(p->op));
  85425. rc = 1;
  85426. goto multi_select_end;
  85427. }
  85428. v = sqlite3GetVdbe(pParse);
  85429. assert( v!=0 ); /* The VDBE already created by calling function */
  85430. /* Create the destination temporary table if necessary
  85431. */
  85432. if( dest.eDest==SRT_EphemTab ){
  85433. assert( p->pEList );
  85434. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
  85435. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  85436. dest.eDest = SRT_Table;
  85437. }
  85438. /* Make sure all SELECTs in the statement have the same number of elements
  85439. ** in their result sets.
  85440. */
  85441. assert( p->pEList && pPrior->pEList );
  85442. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  85443. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  85444. " do not have the same number of result columns", selectOpName(p->op));
  85445. rc = 1;
  85446. goto multi_select_end;
  85447. }
  85448. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  85449. */
  85450. if( p->pOrderBy ){
  85451. return multiSelectOrderBy(pParse, p, pDest);
  85452. }
  85453. /* Generate code for the left and right SELECT statements.
  85454. */
  85455. switch( p->op ){
  85456. case TK_ALL: {
  85457. int addr = 0;
  85458. int nLimit;
  85459. assert( !pPrior->pLimit );
  85460. pPrior->pLimit = p->pLimit;
  85461. pPrior->pOffset = p->pOffset;
  85462. explainSetInteger(iSub1, pParse->iNextSelectId);
  85463. rc = sqlite3Select(pParse, pPrior, &dest);
  85464. p->pLimit = 0;
  85465. p->pOffset = 0;
  85466. if( rc ){
  85467. goto multi_select_end;
  85468. }
  85469. p->pPrior = 0;
  85470. p->iLimit = pPrior->iLimit;
  85471. p->iOffset = pPrior->iOffset;
  85472. if( p->iLimit ){
  85473. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  85474. VdbeComment((v, "Jump ahead if LIMIT reached"));
  85475. }
  85476. explainSetInteger(iSub2, pParse->iNextSelectId);
  85477. rc = sqlite3Select(pParse, p, &dest);
  85478. testcase( rc!=SQLITE_OK );
  85479. pDelete = p->pPrior;
  85480. p->pPrior = pPrior;
  85481. p->nSelectRow += pPrior->nSelectRow;
  85482. if( pPrior->pLimit
  85483. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  85484. && p->nSelectRow > (double)nLimit
  85485. ){
  85486. p->nSelectRow = (double)nLimit;
  85487. }
  85488. if( addr ){
  85489. sqlite3VdbeJumpHere(v, addr);
  85490. }
  85491. break;
  85492. }
  85493. case TK_EXCEPT:
  85494. case TK_UNION: {
  85495. int unionTab; /* Cursor number of the temporary table holding result */
  85496. u8 op = 0; /* One of the SRT_ operations to apply to self */
  85497. int priorOp; /* The SRT_ operation to apply to prior selects */
  85498. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  85499. int addr;
  85500. SelectDest uniondest;
  85501. testcase( p->op==TK_EXCEPT );
  85502. testcase( p->op==TK_UNION );
  85503. priorOp = SRT_Union;
  85504. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  85505. /* We can reuse a temporary table generated by a SELECT to our
  85506. ** right.
  85507. */
  85508. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  85509. ** of a 3-way or more compound */
  85510. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  85511. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  85512. unionTab = dest.iParm;
  85513. }else{
  85514. /* We will need to create our own temporary table to hold the
  85515. ** intermediate results.
  85516. */
  85517. unionTab = pParse->nTab++;
  85518. assert( p->pOrderBy==0 );
  85519. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  85520. assert( p->addrOpenEphm[0] == -1 );
  85521. p->addrOpenEphm[0] = addr;
  85522. p->pRightmost->selFlags |= SF_UsesEphemeral;
  85523. assert( p->pEList );
  85524. }
  85525. /* Code the SELECT statements to our left
  85526. */
  85527. assert( !pPrior->pOrderBy );
  85528. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  85529. explainSetInteger(iSub1, pParse->iNextSelectId);
  85530. rc = sqlite3Select(pParse, pPrior, &uniondest);
  85531. if( rc ){
  85532. goto multi_select_end;
  85533. }
  85534. /* Code the current SELECT statement
  85535. */
  85536. if( p->op==TK_EXCEPT ){
  85537. op = SRT_Except;
  85538. }else{
  85539. assert( p->op==TK_UNION );
  85540. op = SRT_Union;
  85541. }
  85542. p->pPrior = 0;
  85543. pLimit = p->pLimit;
  85544. p->pLimit = 0;
  85545. pOffset = p->pOffset;
  85546. p->pOffset = 0;
  85547. uniondest.eDest = op;
  85548. explainSetInteger(iSub2, pParse->iNextSelectId);
  85549. rc = sqlite3Select(pParse, p, &uniondest);
  85550. testcase( rc!=SQLITE_OK );
  85551. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  85552. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  85553. sqlite3ExprListDelete(db, p->pOrderBy);
  85554. pDelete = p->pPrior;
  85555. p->pPrior = pPrior;
  85556. p->pOrderBy = 0;
  85557. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  85558. sqlite3ExprDelete(db, p->pLimit);
  85559. p->pLimit = pLimit;
  85560. p->pOffset = pOffset;
  85561. p->iLimit = 0;
  85562. p->iOffset = 0;
  85563. /* Convert the data in the temporary table into whatever form
  85564. ** it is that we currently need.
  85565. */
  85566. assert( unionTab==dest.iParm || dest.eDest!=priorOp );
  85567. if( dest.eDest!=priorOp ){
  85568. int iCont, iBreak, iStart;
  85569. assert( p->pEList );
  85570. if( dest.eDest==SRT_Output ){
  85571. Select *pFirst = p;
  85572. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  85573. generateColumnNames(pParse, 0, pFirst->pEList);
  85574. }
  85575. iBreak = sqlite3VdbeMakeLabel(v);
  85576. iCont = sqlite3VdbeMakeLabel(v);
  85577. computeLimitRegisters(pParse, p, iBreak);
  85578. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  85579. iStart = sqlite3VdbeCurrentAddr(v);
  85580. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  85581. 0, -1, &dest, iCont, iBreak);
  85582. sqlite3VdbeResolveLabel(v, iCont);
  85583. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  85584. sqlite3VdbeResolveLabel(v, iBreak);
  85585. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  85586. }
  85587. break;
  85588. }
  85589. default: assert( p->op==TK_INTERSECT ); {
  85590. int tab1, tab2;
  85591. int iCont, iBreak, iStart;
  85592. Expr *pLimit, *pOffset;
  85593. int addr;
  85594. SelectDest intersectdest;
  85595. int r1;
  85596. /* INTERSECT is different from the others since it requires
  85597. ** two temporary tables. Hence it has its own case. Begin
  85598. ** by allocating the tables we will need.
  85599. */
  85600. tab1 = pParse->nTab++;
  85601. tab2 = pParse->nTab++;
  85602. assert( p->pOrderBy==0 );
  85603. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  85604. assert( p->addrOpenEphm[0] == -1 );
  85605. p->addrOpenEphm[0] = addr;
  85606. p->pRightmost->selFlags |= SF_UsesEphemeral;
  85607. assert( p->pEList );
  85608. /* Code the SELECTs to our left into temporary table "tab1".
  85609. */
  85610. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  85611. explainSetInteger(iSub1, pParse->iNextSelectId);
  85612. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  85613. if( rc ){
  85614. goto multi_select_end;
  85615. }
  85616. /* Code the current SELECT into temporary table "tab2"
  85617. */
  85618. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  85619. assert( p->addrOpenEphm[1] == -1 );
  85620. p->addrOpenEphm[1] = addr;
  85621. p->pPrior = 0;
  85622. pLimit = p->pLimit;
  85623. p->pLimit = 0;
  85624. pOffset = p->pOffset;
  85625. p->pOffset = 0;
  85626. intersectdest.iParm = tab2;
  85627. explainSetInteger(iSub2, pParse->iNextSelectId);
  85628. rc = sqlite3Select(pParse, p, &intersectdest);
  85629. testcase( rc!=SQLITE_OK );
  85630. pDelete = p->pPrior;
  85631. p->pPrior = pPrior;
  85632. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  85633. sqlite3ExprDelete(db, p->pLimit);
  85634. p->pLimit = pLimit;
  85635. p->pOffset = pOffset;
  85636. /* Generate code to take the intersection of the two temporary
  85637. ** tables.
  85638. */
  85639. assert( p->pEList );
  85640. if( dest.eDest==SRT_Output ){
  85641. Select *pFirst = p;
  85642. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  85643. generateColumnNames(pParse, 0, pFirst->pEList);
  85644. }
  85645. iBreak = sqlite3VdbeMakeLabel(v);
  85646. iCont = sqlite3VdbeMakeLabel(v);
  85647. computeLimitRegisters(pParse, p, iBreak);
  85648. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  85649. r1 = sqlite3GetTempReg(pParse);
  85650. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  85651. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  85652. sqlite3ReleaseTempReg(pParse, r1);
  85653. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  85654. 0, -1, &dest, iCont, iBreak);
  85655. sqlite3VdbeResolveLabel(v, iCont);
  85656. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  85657. sqlite3VdbeResolveLabel(v, iBreak);
  85658. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  85659. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  85660. break;
  85661. }
  85662. }
  85663. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  85664. /* Compute collating sequences used by
  85665. ** temporary tables needed to implement the compound select.
  85666. ** Attach the KeyInfo structure to all temporary tables.
  85667. **
  85668. ** This section is run by the right-most SELECT statement only.
  85669. ** SELECT statements to the left always skip this part. The right-most
  85670. ** SELECT might also skip this part if it has no ORDER BY clause and
  85671. ** no temp tables are required.
  85672. */
  85673. if( p->selFlags & SF_UsesEphemeral ){
  85674. int i; /* Loop counter */
  85675. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  85676. Select *pLoop; /* For looping through SELECT statements */
  85677. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  85678. int nCol; /* Number of columns in result set */
  85679. assert( p->pRightmost==p );
  85680. nCol = p->pEList->nExpr;
  85681. pKeyInfo = sqlite3DbMallocZero(db,
  85682. sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
  85683. if( !pKeyInfo ){
  85684. rc = SQLITE_NOMEM;
  85685. goto multi_select_end;
  85686. }
  85687. pKeyInfo->enc = ENC(db);
  85688. pKeyInfo->nField = (u16)nCol;
  85689. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  85690. *apColl = multiSelectCollSeq(pParse, p, i);
  85691. if( 0==*apColl ){
  85692. *apColl = db->pDfltColl;
  85693. }
  85694. }
  85695. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  85696. for(i=0; i<2; i++){
  85697. int addr = pLoop->addrOpenEphm[i];
  85698. if( addr<0 ){
  85699. /* If [0] is unused then [1] is also unused. So we can
  85700. ** always safely abort as soon as the first unused slot is found */
  85701. assert( pLoop->addrOpenEphm[1]<0 );
  85702. break;
  85703. }
  85704. sqlite3VdbeChangeP2(v, addr, nCol);
  85705. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  85706. pLoop->addrOpenEphm[i] = -1;
  85707. }
  85708. }
  85709. sqlite3DbFree(db, pKeyInfo);
  85710. }
  85711. multi_select_end:
  85712. pDest->iMem = dest.iMem;
  85713. pDest->nMem = dest.nMem;
  85714. sqlite3SelectDelete(db, pDelete);
  85715. return rc;
  85716. }
  85717. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  85718. /*
  85719. ** Code an output subroutine for a coroutine implementation of a
  85720. ** SELECT statment.
  85721. **
  85722. ** The data to be output is contained in pIn->iMem. There are
  85723. ** pIn->nMem columns to be output. pDest is where the output should
  85724. ** be sent.
  85725. **
  85726. ** regReturn is the number of the register holding the subroutine
  85727. ** return address.
  85728. **
  85729. ** If regPrev>0 then it is the first register in a vector that
  85730. ** records the previous output. mem[regPrev] is a flag that is false
  85731. ** if there has been no previous output. If regPrev>0 then code is
  85732. ** generated to suppress duplicates. pKeyInfo is used for comparing
  85733. ** keys.
  85734. **
  85735. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  85736. ** iBreak.
  85737. */
  85738. static int generateOutputSubroutine(
  85739. Parse *pParse, /* Parsing context */
  85740. Select *p, /* The SELECT statement */
  85741. SelectDest *pIn, /* Coroutine supplying data */
  85742. SelectDest *pDest, /* Where to send the data */
  85743. int regReturn, /* The return address register */
  85744. int regPrev, /* Previous result register. No uniqueness if 0 */
  85745. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  85746. int p4type, /* The p4 type for pKeyInfo */
  85747. int iBreak /* Jump here if we hit the LIMIT */
  85748. ){
  85749. Vdbe *v = pParse->pVdbe;
  85750. int iContinue;
  85751. int addr;
  85752. addr = sqlite3VdbeCurrentAddr(v);
  85753. iContinue = sqlite3VdbeMakeLabel(v);
  85754. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  85755. */
  85756. if( regPrev ){
  85757. int j1, j2;
  85758. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  85759. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
  85760. (char*)pKeyInfo, p4type);
  85761. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  85762. sqlite3VdbeJumpHere(v, j1);
  85763. sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
  85764. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  85765. }
  85766. if( pParse->db->mallocFailed ) return 0;
  85767. /* Suppress the the first OFFSET entries if there is an OFFSET clause
  85768. */
  85769. codeOffset(v, p, iContinue);
  85770. switch( pDest->eDest ){
  85771. /* Store the result as data using a unique key.
  85772. */
  85773. case SRT_Table:
  85774. case SRT_EphemTab: {
  85775. int r1 = sqlite3GetTempReg(pParse);
  85776. int r2 = sqlite3GetTempReg(pParse);
  85777. testcase( pDest->eDest==SRT_Table );
  85778. testcase( pDest->eDest==SRT_EphemTab );
  85779. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
  85780. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
  85781. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
  85782. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  85783. sqlite3ReleaseTempReg(pParse, r2);
  85784. sqlite3ReleaseTempReg(pParse, r1);
  85785. break;
  85786. }
  85787. #ifndef SQLITE_OMIT_SUBQUERY
  85788. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  85789. ** then there should be a single item on the stack. Write this
  85790. ** item into the set table with bogus data.
  85791. */
  85792. case SRT_Set: {
  85793. int r1;
  85794. assert( pIn->nMem==1 );
  85795. p->affinity =
  85796. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
  85797. r1 = sqlite3GetTempReg(pParse);
  85798. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
  85799. sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
  85800. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
  85801. sqlite3ReleaseTempReg(pParse, r1);
  85802. break;
  85803. }
  85804. #if 0 /* Never occurs on an ORDER BY query */
  85805. /* If any row exist in the result set, record that fact and abort.
  85806. */
  85807. case SRT_Exists: {
  85808. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
  85809. /* The LIMIT clause will terminate the loop for us */
  85810. break;
  85811. }
  85812. #endif
  85813. /* If this is a scalar select that is part of an expression, then
  85814. ** store the results in the appropriate memory cell and break out
  85815. ** of the scan loop.
  85816. */
  85817. case SRT_Mem: {
  85818. assert( pIn->nMem==1 );
  85819. sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
  85820. /* The LIMIT clause will jump out of the loop for us */
  85821. break;
  85822. }
  85823. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  85824. /* The results are stored in a sequence of registers
  85825. ** starting at pDest->iMem. Then the co-routine yields.
  85826. */
  85827. case SRT_Coroutine: {
  85828. if( pDest->iMem==0 ){
  85829. pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
  85830. pDest->nMem = pIn->nMem;
  85831. }
  85832. sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
  85833. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  85834. break;
  85835. }
  85836. /* If none of the above, then the result destination must be
  85837. ** SRT_Output. This routine is never called with any other
  85838. ** destination other than the ones handled above or SRT_Output.
  85839. **
  85840. ** For SRT_Output, results are stored in a sequence of registers.
  85841. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  85842. ** return the next row of result.
  85843. */
  85844. default: {
  85845. assert( pDest->eDest==SRT_Output );
  85846. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
  85847. sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
  85848. break;
  85849. }
  85850. }
  85851. /* Jump to the end of the loop if the LIMIT is reached.
  85852. */
  85853. if( p->iLimit ){
  85854. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  85855. }
  85856. /* Generate the subroutine return
  85857. */
  85858. sqlite3VdbeResolveLabel(v, iContinue);
  85859. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  85860. return addr;
  85861. }
  85862. /*
  85863. ** Alternative compound select code generator for cases when there
  85864. ** is an ORDER BY clause.
  85865. **
  85866. ** We assume a query of the following form:
  85867. **
  85868. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  85869. **
  85870. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  85871. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  85872. ** co-routines. Then run the co-routines in parallel and merge the results
  85873. ** into the output. In addition to the two coroutines (called selectA and
  85874. ** selectB) there are 7 subroutines:
  85875. **
  85876. ** outA: Move the output of the selectA coroutine into the output
  85877. ** of the compound query.
  85878. **
  85879. ** outB: Move the output of the selectB coroutine into the output
  85880. ** of the compound query. (Only generated for UNION and
  85881. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  85882. ** appears only in B.)
  85883. **
  85884. ** AltB: Called when there is data from both coroutines and A<B.
  85885. **
  85886. ** AeqB: Called when there is data from both coroutines and A==B.
  85887. **
  85888. ** AgtB: Called when there is data from both coroutines and A>B.
  85889. **
  85890. ** EofA: Called when data is exhausted from selectA.
  85891. **
  85892. ** EofB: Called when data is exhausted from selectB.
  85893. **
  85894. ** The implementation of the latter five subroutines depend on which
  85895. ** <operator> is used:
  85896. **
  85897. **
  85898. ** UNION ALL UNION EXCEPT INTERSECT
  85899. ** ------------- ----------------- -------------- -----------------
  85900. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  85901. **
  85902. ** AeqB: outA, nextA nextA nextA outA, nextA
  85903. **
  85904. ** AgtB: outB, nextB outB, nextB nextB nextB
  85905. **
  85906. ** EofA: outB, nextB outB, nextB halt halt
  85907. **
  85908. ** EofB: outA, nextA outA, nextA outA, nextA halt
  85909. **
  85910. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  85911. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  85912. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  85913. ** following nextX causes a jump to the end of the select processing.
  85914. **
  85915. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  85916. ** within the output subroutine. The regPrev register set holds the previously
  85917. ** output value. A comparison is made against this value and the output
  85918. ** is skipped if the next results would be the same as the previous.
  85919. **
  85920. ** The implementation plan is to implement the two coroutines and seven
  85921. ** subroutines first, then put the control logic at the bottom. Like this:
  85922. **
  85923. ** goto Init
  85924. ** coA: coroutine for left query (A)
  85925. ** coB: coroutine for right query (B)
  85926. ** outA: output one row of A
  85927. ** outB: output one row of B (UNION and UNION ALL only)
  85928. ** EofA: ...
  85929. ** EofB: ...
  85930. ** AltB: ...
  85931. ** AeqB: ...
  85932. ** AgtB: ...
  85933. ** Init: initialize coroutine registers
  85934. ** yield coA
  85935. ** if eof(A) goto EofA
  85936. ** yield coB
  85937. ** if eof(B) goto EofB
  85938. ** Cmpr: Compare A, B
  85939. ** Jump AltB, AeqB, AgtB
  85940. ** End: ...
  85941. **
  85942. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  85943. ** actually called using Gosub and they do not Return. EofA and EofB loop
  85944. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  85945. ** and AgtB jump to either L2 or to one of EofA or EofB.
  85946. */
  85947. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  85948. static int multiSelectOrderBy(
  85949. Parse *pParse, /* Parsing context */
  85950. Select *p, /* The right-most of SELECTs to be coded */
  85951. SelectDest *pDest /* What to do with query results */
  85952. ){
  85953. int i, j; /* Loop counters */
  85954. Select *pPrior; /* Another SELECT immediately to our left */
  85955. Vdbe *v; /* Generate code to this VDBE */
  85956. SelectDest destA; /* Destination for coroutine A */
  85957. SelectDest destB; /* Destination for coroutine B */
  85958. int regAddrA; /* Address register for select-A coroutine */
  85959. int regEofA; /* Flag to indicate when select-A is complete */
  85960. int regAddrB; /* Address register for select-B coroutine */
  85961. int regEofB; /* Flag to indicate when select-B is complete */
  85962. int addrSelectA; /* Address of the select-A coroutine */
  85963. int addrSelectB; /* Address of the select-B coroutine */
  85964. int regOutA; /* Address register for the output-A subroutine */
  85965. int regOutB; /* Address register for the output-B subroutine */
  85966. int addrOutA; /* Address of the output-A subroutine */
  85967. int addrOutB = 0; /* Address of the output-B subroutine */
  85968. int addrEofA; /* Address of the select-A-exhausted subroutine */
  85969. int addrEofB; /* Address of the select-B-exhausted subroutine */
  85970. int addrAltB; /* Address of the A<B subroutine */
  85971. int addrAeqB; /* Address of the A==B subroutine */
  85972. int addrAgtB; /* Address of the A>B subroutine */
  85973. int regLimitA; /* Limit register for select-A */
  85974. int regLimitB; /* Limit register for select-A */
  85975. int regPrev; /* A range of registers to hold previous output */
  85976. int savedLimit; /* Saved value of p->iLimit */
  85977. int savedOffset; /* Saved value of p->iOffset */
  85978. int labelCmpr; /* Label for the start of the merge algorithm */
  85979. int labelEnd; /* Label for the end of the overall SELECT stmt */
  85980. int j1; /* Jump instructions that get retargetted */
  85981. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  85982. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  85983. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  85984. sqlite3 *db; /* Database connection */
  85985. ExprList *pOrderBy; /* The ORDER BY clause */
  85986. int nOrderBy; /* Number of terms in the ORDER BY clause */
  85987. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  85988. #ifndef SQLITE_OMIT_EXPLAIN
  85989. int iSub1; /* EQP id of left-hand query */
  85990. int iSub2; /* EQP id of right-hand query */
  85991. #endif
  85992. assert( p->pOrderBy!=0 );
  85993. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  85994. db = pParse->db;
  85995. v = pParse->pVdbe;
  85996. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  85997. labelEnd = sqlite3VdbeMakeLabel(v);
  85998. labelCmpr = sqlite3VdbeMakeLabel(v);
  85999. /* Patch up the ORDER BY clause
  86000. */
  86001. op = p->op;
  86002. pPrior = p->pPrior;
  86003. assert( pPrior->pOrderBy==0 );
  86004. pOrderBy = p->pOrderBy;
  86005. assert( pOrderBy );
  86006. nOrderBy = pOrderBy->nExpr;
  86007. /* For operators other than UNION ALL we have to make sure that
  86008. ** the ORDER BY clause covers every term of the result set. Add
  86009. ** terms to the ORDER BY clause as necessary.
  86010. */
  86011. if( op!=TK_ALL ){
  86012. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  86013. struct ExprList_item *pItem;
  86014. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  86015. assert( pItem->iCol>0 );
  86016. if( pItem->iCol==i ) break;
  86017. }
  86018. if( j==nOrderBy ){
  86019. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  86020. if( pNew==0 ) return SQLITE_NOMEM;
  86021. pNew->flags |= EP_IntValue;
  86022. pNew->u.iValue = i;
  86023. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  86024. pOrderBy->a[nOrderBy++].iCol = (u16)i;
  86025. }
  86026. }
  86027. }
  86028. /* Compute the comparison permutation and keyinfo that is used with
  86029. ** the permutation used to determine if the next
  86030. ** row of results comes from selectA or selectB. Also add explicit
  86031. ** collations to the ORDER BY clause terms so that when the subqueries
  86032. ** to the right and the left are evaluated, they use the correct
  86033. ** collation.
  86034. */
  86035. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  86036. if( aPermute ){
  86037. struct ExprList_item *pItem;
  86038. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  86039. assert( pItem->iCol>0 && pItem->iCol<=p->pEList->nExpr );
  86040. aPermute[i] = pItem->iCol - 1;
  86041. }
  86042. pKeyMerge =
  86043. sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
  86044. if( pKeyMerge ){
  86045. pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
  86046. pKeyMerge->nField = (u16)nOrderBy;
  86047. pKeyMerge->enc = ENC(db);
  86048. for(i=0; i<nOrderBy; i++){
  86049. CollSeq *pColl;
  86050. Expr *pTerm = pOrderBy->a[i].pExpr;
  86051. if( pTerm->flags & EP_ExpCollate ){
  86052. pColl = pTerm->pColl;
  86053. }else{
  86054. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  86055. pTerm->flags |= EP_ExpCollate;
  86056. pTerm->pColl = pColl;
  86057. }
  86058. pKeyMerge->aColl[i] = pColl;
  86059. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  86060. }
  86061. }
  86062. }else{
  86063. pKeyMerge = 0;
  86064. }
  86065. /* Reattach the ORDER BY clause to the query.
  86066. */
  86067. p->pOrderBy = pOrderBy;
  86068. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  86069. /* Allocate a range of temporary registers and the KeyInfo needed
  86070. ** for the logic that removes duplicate result rows when the
  86071. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  86072. */
  86073. if( op==TK_ALL ){
  86074. regPrev = 0;
  86075. }else{
  86076. int nExpr = p->pEList->nExpr;
  86077. assert( nOrderBy>=nExpr || db->mallocFailed );
  86078. regPrev = sqlite3GetTempRange(pParse, nExpr+1);
  86079. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  86080. pKeyDup = sqlite3DbMallocZero(db,
  86081. sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
  86082. if( pKeyDup ){
  86083. pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
  86084. pKeyDup->nField = (u16)nExpr;
  86085. pKeyDup->enc = ENC(db);
  86086. for(i=0; i<nExpr; i++){
  86087. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  86088. pKeyDup->aSortOrder[i] = 0;
  86089. }
  86090. }
  86091. }
  86092. /* Separate the left and the right query from one another
  86093. */
  86094. p->pPrior = 0;
  86095. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  86096. if( pPrior->pPrior==0 ){
  86097. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  86098. }
  86099. /* Compute the limit registers */
  86100. computeLimitRegisters(pParse, p, labelEnd);
  86101. if( p->iLimit && op==TK_ALL ){
  86102. regLimitA = ++pParse->nMem;
  86103. regLimitB = ++pParse->nMem;
  86104. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  86105. regLimitA);
  86106. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  86107. }else{
  86108. regLimitA = regLimitB = 0;
  86109. }
  86110. sqlite3ExprDelete(db, p->pLimit);
  86111. p->pLimit = 0;
  86112. sqlite3ExprDelete(db, p->pOffset);
  86113. p->pOffset = 0;
  86114. regAddrA = ++pParse->nMem;
  86115. regEofA = ++pParse->nMem;
  86116. regAddrB = ++pParse->nMem;
  86117. regEofB = ++pParse->nMem;
  86118. regOutA = ++pParse->nMem;
  86119. regOutB = ++pParse->nMem;
  86120. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  86121. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  86122. /* Jump past the various subroutines and coroutines to the main
  86123. ** merge loop
  86124. */
  86125. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  86126. addrSelectA = sqlite3VdbeCurrentAddr(v);
  86127. /* Generate a coroutine to evaluate the SELECT statement to the
  86128. ** left of the compound operator - the "A" select.
  86129. */
  86130. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  86131. pPrior->iLimit = regLimitA;
  86132. explainSetInteger(iSub1, pParse->iNextSelectId);
  86133. sqlite3Select(pParse, pPrior, &destA);
  86134. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  86135. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  86136. VdbeNoopComment((v, "End coroutine for left SELECT"));
  86137. /* Generate a coroutine to evaluate the SELECT statement on
  86138. ** the right - the "B" select
  86139. */
  86140. addrSelectB = sqlite3VdbeCurrentAddr(v);
  86141. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  86142. savedLimit = p->iLimit;
  86143. savedOffset = p->iOffset;
  86144. p->iLimit = regLimitB;
  86145. p->iOffset = 0;
  86146. explainSetInteger(iSub2, pParse->iNextSelectId);
  86147. sqlite3Select(pParse, p, &destB);
  86148. p->iLimit = savedLimit;
  86149. p->iOffset = savedOffset;
  86150. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  86151. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  86152. VdbeNoopComment((v, "End coroutine for right SELECT"));
  86153. /* Generate a subroutine that outputs the current row of the A
  86154. ** select as the next output row of the compound select.
  86155. */
  86156. VdbeNoopComment((v, "Output routine for A"));
  86157. addrOutA = generateOutputSubroutine(pParse,
  86158. p, &destA, pDest, regOutA,
  86159. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  86160. /* Generate a subroutine that outputs the current row of the B
  86161. ** select as the next output row of the compound select.
  86162. */
  86163. if( op==TK_ALL || op==TK_UNION ){
  86164. VdbeNoopComment((v, "Output routine for B"));
  86165. addrOutB = generateOutputSubroutine(pParse,
  86166. p, &destB, pDest, regOutB,
  86167. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  86168. }
  86169. /* Generate a subroutine to run when the results from select A
  86170. ** are exhausted and only data in select B remains.
  86171. */
  86172. VdbeNoopComment((v, "eof-A subroutine"));
  86173. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  86174. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  86175. }else{
  86176. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  86177. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  86178. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  86179. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  86180. p->nSelectRow += pPrior->nSelectRow;
  86181. }
  86182. /* Generate a subroutine to run when the results from select B
  86183. ** are exhausted and only data in select A remains.
  86184. */
  86185. if( op==TK_INTERSECT ){
  86186. addrEofB = addrEofA;
  86187. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  86188. }else{
  86189. VdbeNoopComment((v, "eof-B subroutine"));
  86190. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  86191. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  86192. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  86193. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  86194. }
  86195. /* Generate code to handle the case of A<B
  86196. */
  86197. VdbeNoopComment((v, "A-lt-B subroutine"));
  86198. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  86199. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  86200. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  86201. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  86202. /* Generate code to handle the case of A==B
  86203. */
  86204. if( op==TK_ALL ){
  86205. addrAeqB = addrAltB;
  86206. }else if( op==TK_INTERSECT ){
  86207. addrAeqB = addrAltB;
  86208. addrAltB++;
  86209. }else{
  86210. VdbeNoopComment((v, "A-eq-B subroutine"));
  86211. addrAeqB =
  86212. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  86213. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  86214. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  86215. }
  86216. /* Generate code to handle the case of A>B
  86217. */
  86218. VdbeNoopComment((v, "A-gt-B subroutine"));
  86219. addrAgtB = sqlite3VdbeCurrentAddr(v);
  86220. if( op==TK_ALL || op==TK_UNION ){
  86221. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  86222. }
  86223. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  86224. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  86225. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  86226. /* This code runs once to initialize everything.
  86227. */
  86228. sqlite3VdbeJumpHere(v, j1);
  86229. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  86230. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  86231. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  86232. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  86233. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  86234. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  86235. /* Implement the main merge loop
  86236. */
  86237. sqlite3VdbeResolveLabel(v, labelCmpr);
  86238. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  86239. sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
  86240. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  86241. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  86242. /* Release temporary registers
  86243. */
  86244. if( regPrev ){
  86245. sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
  86246. }
  86247. /* Jump to the this point in order to terminate the query.
  86248. */
  86249. sqlite3VdbeResolveLabel(v, labelEnd);
  86250. /* Set the number of output columns
  86251. */
  86252. if( pDest->eDest==SRT_Output ){
  86253. Select *pFirst = pPrior;
  86254. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  86255. generateColumnNames(pParse, 0, pFirst->pEList);
  86256. }
  86257. /* Reassembly the compound query so that it will be freed correctly
  86258. ** by the calling function */
  86259. if( p->pPrior ){
  86260. sqlite3SelectDelete(db, p->pPrior);
  86261. }
  86262. p->pPrior = pPrior;
  86263. /*** TBD: Insert subroutine calls to close cursors on incomplete
  86264. **** subqueries ****/
  86265. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  86266. return SQLITE_OK;
  86267. }
  86268. #endif
  86269. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  86270. /* Forward Declarations */
  86271. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  86272. static void substSelect(sqlite3*, Select *, int, ExprList *);
  86273. /*
  86274. ** Scan through the expression pExpr. Replace every reference to
  86275. ** a column in table number iTable with a copy of the iColumn-th
  86276. ** entry in pEList. (But leave references to the ROWID column
  86277. ** unchanged.)
  86278. **
  86279. ** This routine is part of the flattening procedure. A subquery
  86280. ** whose result set is defined by pEList appears as entry in the
  86281. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  86282. ** FORM clause entry is iTable. This routine make the necessary
  86283. ** changes to pExpr so that it refers directly to the source table
  86284. ** of the subquery rather the result set of the subquery.
  86285. */
  86286. static Expr *substExpr(
  86287. sqlite3 *db, /* Report malloc errors to this connection */
  86288. Expr *pExpr, /* Expr in which substitution occurs */
  86289. int iTable, /* Table to be substituted */
  86290. ExprList *pEList /* Substitute expressions */
  86291. ){
  86292. if( pExpr==0 ) return 0;
  86293. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  86294. if( pExpr->iColumn<0 ){
  86295. pExpr->op = TK_NULL;
  86296. }else{
  86297. Expr *pNew;
  86298. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  86299. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  86300. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  86301. if( pNew && pExpr->pColl ){
  86302. pNew->pColl = pExpr->pColl;
  86303. }
  86304. sqlite3ExprDelete(db, pExpr);
  86305. pExpr = pNew;
  86306. }
  86307. }else{
  86308. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  86309. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  86310. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  86311. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  86312. }else{
  86313. substExprList(db, pExpr->x.pList, iTable, pEList);
  86314. }
  86315. }
  86316. return pExpr;
  86317. }
  86318. static void substExprList(
  86319. sqlite3 *db, /* Report malloc errors here */
  86320. ExprList *pList, /* List to scan and in which to make substitutes */
  86321. int iTable, /* Table to be substituted */
  86322. ExprList *pEList /* Substitute values */
  86323. ){
  86324. int i;
  86325. if( pList==0 ) return;
  86326. for(i=0; i<pList->nExpr; i++){
  86327. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  86328. }
  86329. }
  86330. static void substSelect(
  86331. sqlite3 *db, /* Report malloc errors here */
  86332. Select *p, /* SELECT statement in which to make substitutions */
  86333. int iTable, /* Table to be replaced */
  86334. ExprList *pEList /* Substitute values */
  86335. ){
  86336. SrcList *pSrc;
  86337. struct SrcList_item *pItem;
  86338. int i;
  86339. if( !p ) return;
  86340. substExprList(db, p->pEList, iTable, pEList);
  86341. substExprList(db, p->pGroupBy, iTable, pEList);
  86342. substExprList(db, p->pOrderBy, iTable, pEList);
  86343. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  86344. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  86345. substSelect(db, p->pPrior, iTable, pEList);
  86346. pSrc = p->pSrc;
  86347. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  86348. if( ALWAYS(pSrc) ){
  86349. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  86350. substSelect(db, pItem->pSelect, iTable, pEList);
  86351. }
  86352. }
  86353. }
  86354. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  86355. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  86356. /*
  86357. ** This routine attempts to flatten subqueries in order to speed
  86358. ** execution. It returns 1 if it makes changes and 0 if no flattening
  86359. ** occurs.
  86360. **
  86361. ** To understand the concept of flattening, consider the following
  86362. ** query:
  86363. **
  86364. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  86365. **
  86366. ** The default way of implementing this query is to execute the
  86367. ** subquery first and store the results in a temporary table, then
  86368. ** run the outer query on that temporary table. This requires two
  86369. ** passes over the data. Furthermore, because the temporary table
  86370. ** has no indices, the WHERE clause on the outer query cannot be
  86371. ** optimized.
  86372. **
  86373. ** This routine attempts to rewrite queries such as the above into
  86374. ** a single flat select, like this:
  86375. **
  86376. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  86377. **
  86378. ** The code generated for this simpification gives the same result
  86379. ** but only has to scan the data once. And because indices might
  86380. ** exist on the table t1, a complete scan of the data might be
  86381. ** avoided.
  86382. **
  86383. ** Flattening is only attempted if all of the following are true:
  86384. **
  86385. ** (1) The subquery and the outer query do not both use aggregates.
  86386. **
  86387. ** (2) The subquery is not an aggregate or the outer query is not a join.
  86388. **
  86389. ** (3) The subquery is not the right operand of a left outer join
  86390. ** (Originally ticket #306. Strengthened by ticket #3300)
  86391. **
  86392. ** (4) The subquery is not DISTINCT.
  86393. **
  86394. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  86395. ** sub-queries that were excluded from this optimization. Restriction
  86396. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  86397. **
  86398. ** (6) The subquery does not use aggregates or the outer query is not
  86399. ** DISTINCT.
  86400. **
  86401. ** (7) The subquery has a FROM clause.
  86402. **
  86403. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  86404. **
  86405. ** (9) The subquery does not use LIMIT or the outer query does not use
  86406. ** aggregates.
  86407. **
  86408. ** (10) The subquery does not use aggregates or the outer query does not
  86409. ** use LIMIT.
  86410. **
  86411. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  86412. **
  86413. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  86414. ** a separate restriction deriving from ticket #350.
  86415. **
  86416. ** (13) The subquery and outer query do not both use LIMIT.
  86417. **
  86418. ** (14) The subquery does not use OFFSET.
  86419. **
  86420. ** (15) The outer query is not part of a compound select or the
  86421. ** subquery does not have a LIMIT clause.
  86422. ** (See ticket #2339 and ticket [02a8e81d44]).
  86423. **
  86424. ** (16) The outer query is not an aggregate or the subquery does
  86425. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  86426. ** until we introduced the group_concat() function.
  86427. **
  86428. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  86429. ** compound clause made up entirely of non-aggregate queries, and
  86430. ** the parent query:
  86431. **
  86432. ** * is not itself part of a compound select,
  86433. ** * is not an aggregate or DISTINCT query, and
  86434. ** * has no other tables or sub-selects in the FROM clause.
  86435. **
  86436. ** The parent and sub-query may contain WHERE clauses. Subject to
  86437. ** rules (11), (13) and (14), they may also contain ORDER BY,
  86438. ** LIMIT and OFFSET clauses.
  86439. **
  86440. ** (18) If the sub-query is a compound select, then all terms of the
  86441. ** ORDER by clause of the parent must be simple references to
  86442. ** columns of the sub-query.
  86443. **
  86444. ** (19) The subquery does not use LIMIT or the outer query does not
  86445. ** have a WHERE clause.
  86446. **
  86447. ** (20) If the sub-query is a compound select, then it must not use
  86448. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  86449. ** somewhat by saying that the terms of the ORDER BY clause must
  86450. ** appear as unmodified result columns in the outer query. But
  86451. ** have other optimizations in mind to deal with that case.
  86452. **
  86453. ** (21) The subquery does not use LIMIT or the outer query is not
  86454. ** DISTINCT. (See ticket [752e1646fc]).
  86455. **
  86456. ** In this routine, the "p" parameter is a pointer to the outer query.
  86457. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  86458. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  86459. **
  86460. ** If flattening is not attempted, this routine is a no-op and returns 0.
  86461. ** If flattening is attempted this routine returns 1.
  86462. **
  86463. ** All of the expression analysis must occur on both the outer query and
  86464. ** the subquery before this routine runs.
  86465. */
  86466. static int flattenSubquery(
  86467. Parse *pParse, /* Parsing context */
  86468. Select *p, /* The parent or outer SELECT statement */
  86469. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  86470. int isAgg, /* True if outer SELECT uses aggregate functions */
  86471. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  86472. ){
  86473. const char *zSavedAuthContext = pParse->zAuthContext;
  86474. Select *pParent;
  86475. Select *pSub; /* The inner query or "subquery" */
  86476. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  86477. SrcList *pSrc; /* The FROM clause of the outer query */
  86478. SrcList *pSubSrc; /* The FROM clause of the subquery */
  86479. ExprList *pList; /* The result set of the outer query */
  86480. int iParent; /* VDBE cursor number of the pSub result set temp table */
  86481. int i; /* Loop counter */
  86482. Expr *pWhere; /* The WHERE clause */
  86483. struct SrcList_item *pSubitem; /* The subquery */
  86484. sqlite3 *db = pParse->db;
  86485. /* Check to see if flattening is permitted. Return 0 if not.
  86486. */
  86487. assert( p!=0 );
  86488. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  86489. if( db->flags & SQLITE_QueryFlattener ) return 0;
  86490. pSrc = p->pSrc;
  86491. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  86492. pSubitem = &pSrc->a[iFrom];
  86493. iParent = pSubitem->iCursor;
  86494. pSub = pSubitem->pSelect;
  86495. assert( pSub!=0 );
  86496. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  86497. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  86498. pSubSrc = pSub->pSrc;
  86499. assert( pSubSrc );
  86500. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  86501. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  86502. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  86503. ** became arbitrary expressions, we were forced to add restrictions (13)
  86504. ** and (14). */
  86505. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  86506. if( pSub->pOffset ) return 0; /* Restriction (14) */
  86507. if( p->pRightmost && pSub->pLimit ){
  86508. return 0; /* Restriction (15) */
  86509. }
  86510. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  86511. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  86512. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  86513. return 0; /* Restrictions (8)(9) */
  86514. }
  86515. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  86516. return 0; /* Restriction (6) */
  86517. }
  86518. if( p->pOrderBy && pSub->pOrderBy ){
  86519. return 0; /* Restriction (11) */
  86520. }
  86521. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  86522. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  86523. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  86524. return 0; /* Restriction (21) */
  86525. }
  86526. /* OBSOLETE COMMENT 1:
  86527. ** Restriction 3: If the subquery is a join, make sure the subquery is
  86528. ** not used as the right operand of an outer join. Examples of why this
  86529. ** is not allowed:
  86530. **
  86531. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  86532. **
  86533. ** If we flatten the above, we would get
  86534. **
  86535. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  86536. **
  86537. ** which is not at all the same thing.
  86538. **
  86539. ** OBSOLETE COMMENT 2:
  86540. ** Restriction 12: If the subquery is the right operand of a left outer
  86541. ** join, make sure the subquery has no WHERE clause.
  86542. ** An examples of why this is not allowed:
  86543. **
  86544. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  86545. **
  86546. ** If we flatten the above, we would get
  86547. **
  86548. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  86549. **
  86550. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  86551. ** effectively converts the OUTER JOIN into an INNER JOIN.
  86552. **
  86553. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  86554. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  86555. ** is fraught with danger. Best to avoid the whole thing. If the
  86556. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  86557. */
  86558. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  86559. return 0;
  86560. }
  86561. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  86562. ** use only the UNION ALL operator. And none of the simple select queries
  86563. ** that make up the compound SELECT are allowed to be aggregate or distinct
  86564. ** queries.
  86565. */
  86566. if( pSub->pPrior ){
  86567. if( pSub->pOrderBy ){
  86568. return 0; /* Restriction 20 */
  86569. }
  86570. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  86571. return 0;
  86572. }
  86573. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  86574. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  86575. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  86576. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  86577. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  86578. || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
  86579. ){
  86580. return 0;
  86581. }
  86582. }
  86583. /* Restriction 18. */
  86584. if( p->pOrderBy ){
  86585. int ii;
  86586. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  86587. if( p->pOrderBy->a[ii].iCol==0 ) return 0;
  86588. }
  86589. }
  86590. }
  86591. /***** If we reach this point, flattening is permitted. *****/
  86592. /* Authorize the subquery */
  86593. pParse->zAuthContext = pSubitem->zName;
  86594. sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  86595. pParse->zAuthContext = zSavedAuthContext;
  86596. /* If the sub-query is a compound SELECT statement, then (by restrictions
  86597. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  86598. ** be of the form:
  86599. **
  86600. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  86601. **
  86602. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  86603. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  86604. ** OFFSET clauses and joins them to the left-hand-side of the original
  86605. ** using UNION ALL operators. In this case N is the number of simple
  86606. ** select statements in the compound sub-query.
  86607. **
  86608. ** Example:
  86609. **
  86610. ** SELECT a+1 FROM (
  86611. ** SELECT x FROM tab
  86612. ** UNION ALL
  86613. ** SELECT y FROM tab
  86614. ** UNION ALL
  86615. ** SELECT abs(z*2) FROM tab2
  86616. ** ) WHERE a!=5 ORDER BY 1
  86617. **
  86618. ** Transformed into:
  86619. **
  86620. ** SELECT x+1 FROM tab WHERE x+1!=5
  86621. ** UNION ALL
  86622. ** SELECT y+1 FROM tab WHERE y+1!=5
  86623. ** UNION ALL
  86624. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  86625. ** ORDER BY 1
  86626. **
  86627. ** We call this the "compound-subquery flattening".
  86628. */
  86629. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  86630. Select *pNew;
  86631. ExprList *pOrderBy = p->pOrderBy;
  86632. Expr *pLimit = p->pLimit;
  86633. Select *pPrior = p->pPrior;
  86634. p->pOrderBy = 0;
  86635. p->pSrc = 0;
  86636. p->pPrior = 0;
  86637. p->pLimit = 0;
  86638. pNew = sqlite3SelectDup(db, p, 0);
  86639. p->pLimit = pLimit;
  86640. p->pOrderBy = pOrderBy;
  86641. p->pSrc = pSrc;
  86642. p->op = TK_ALL;
  86643. p->pRightmost = 0;
  86644. if( pNew==0 ){
  86645. pNew = pPrior;
  86646. }else{
  86647. pNew->pPrior = pPrior;
  86648. pNew->pRightmost = 0;
  86649. }
  86650. p->pPrior = pNew;
  86651. if( db->mallocFailed ) return 1;
  86652. }
  86653. /* Begin flattening the iFrom-th entry of the FROM clause
  86654. ** in the outer query.
  86655. */
  86656. pSub = pSub1 = pSubitem->pSelect;
  86657. /* Delete the transient table structure associated with the
  86658. ** subquery
  86659. */
  86660. sqlite3DbFree(db, pSubitem->zDatabase);
  86661. sqlite3DbFree(db, pSubitem->zName);
  86662. sqlite3DbFree(db, pSubitem->zAlias);
  86663. pSubitem->zDatabase = 0;
  86664. pSubitem->zName = 0;
  86665. pSubitem->zAlias = 0;
  86666. pSubitem->pSelect = 0;
  86667. /* Defer deleting the Table object associated with the
  86668. ** subquery until code generation is
  86669. ** complete, since there may still exist Expr.pTab entries that
  86670. ** refer to the subquery even after flattening. Ticket #3346.
  86671. **
  86672. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  86673. */
  86674. if( ALWAYS(pSubitem->pTab!=0) ){
  86675. Table *pTabToDel = pSubitem->pTab;
  86676. if( pTabToDel->nRef==1 ){
  86677. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86678. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  86679. pToplevel->pZombieTab = pTabToDel;
  86680. }else{
  86681. pTabToDel->nRef--;
  86682. }
  86683. pSubitem->pTab = 0;
  86684. }
  86685. /* The following loop runs once for each term in a compound-subquery
  86686. ** flattening (as described above). If we are doing a different kind
  86687. ** of flattening - a flattening other than a compound-subquery flattening -
  86688. ** then this loop only runs once.
  86689. **
  86690. ** This loop moves all of the FROM elements of the subquery into the
  86691. ** the FROM clause of the outer query. Before doing this, remember
  86692. ** the cursor number for the original outer query FROM element in
  86693. ** iParent. The iParent cursor will never be used. Subsequent code
  86694. ** will scan expressions looking for iParent references and replace
  86695. ** those references with expressions that resolve to the subquery FROM
  86696. ** elements we are now copying in.
  86697. */
  86698. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  86699. int nSubSrc;
  86700. u8 jointype = 0;
  86701. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  86702. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  86703. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  86704. if( pSrc ){
  86705. assert( pParent==p ); /* First time through the loop */
  86706. jointype = pSubitem->jointype;
  86707. }else{
  86708. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  86709. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  86710. if( pSrc==0 ){
  86711. assert( db->mallocFailed );
  86712. break;
  86713. }
  86714. }
  86715. /* The subquery uses a single slot of the FROM clause of the outer
  86716. ** query. If the subquery has more than one element in its FROM clause,
  86717. ** then expand the outer query to make space for it to hold all elements
  86718. ** of the subquery.
  86719. **
  86720. ** Example:
  86721. **
  86722. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  86723. **
  86724. ** The outer query has 3 slots in its FROM clause. One slot of the
  86725. ** outer query (the middle slot) is used by the subquery. The next
  86726. ** block of code will expand the out query to 4 slots. The middle
  86727. ** slot is expanded to two slots in order to make space for the
  86728. ** two elements in the FROM clause of the subquery.
  86729. */
  86730. if( nSubSrc>1 ){
  86731. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  86732. if( db->mallocFailed ){
  86733. break;
  86734. }
  86735. }
  86736. /* Transfer the FROM clause terms from the subquery into the
  86737. ** outer query.
  86738. */
  86739. for(i=0; i<nSubSrc; i++){
  86740. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  86741. pSrc->a[i+iFrom] = pSubSrc->a[i];
  86742. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  86743. }
  86744. pSrc->a[iFrom].jointype = jointype;
  86745. /* Now begin substituting subquery result set expressions for
  86746. ** references to the iParent in the outer query.
  86747. **
  86748. ** Example:
  86749. **
  86750. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  86751. ** \ \_____________ subquery __________/ /
  86752. ** \_____________________ outer query ______________________________/
  86753. **
  86754. ** We look at every expression in the outer query and every place we see
  86755. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  86756. */
  86757. pList = pParent->pEList;
  86758. for(i=0; i<pList->nExpr; i++){
  86759. if( pList->a[i].zName==0 ){
  86760. const char *zSpan = pList->a[i].zSpan;
  86761. if( ALWAYS(zSpan) ){
  86762. pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
  86763. }
  86764. }
  86765. }
  86766. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  86767. if( isAgg ){
  86768. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  86769. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  86770. }
  86771. if( pSub->pOrderBy ){
  86772. assert( pParent->pOrderBy==0 );
  86773. pParent->pOrderBy = pSub->pOrderBy;
  86774. pSub->pOrderBy = 0;
  86775. }else if( pParent->pOrderBy ){
  86776. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  86777. }
  86778. if( pSub->pWhere ){
  86779. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  86780. }else{
  86781. pWhere = 0;
  86782. }
  86783. if( subqueryIsAgg ){
  86784. assert( pParent->pHaving==0 );
  86785. pParent->pHaving = pParent->pWhere;
  86786. pParent->pWhere = pWhere;
  86787. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  86788. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  86789. sqlite3ExprDup(db, pSub->pHaving, 0));
  86790. assert( pParent->pGroupBy==0 );
  86791. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  86792. }else{
  86793. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  86794. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  86795. }
  86796. /* The flattened query is distinct if either the inner or the
  86797. ** outer query is distinct.
  86798. */
  86799. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  86800. /*
  86801. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  86802. **
  86803. ** One is tempted to try to add a and b to combine the limits. But this
  86804. ** does not work if either limit is negative.
  86805. */
  86806. if( pSub->pLimit ){
  86807. pParent->pLimit = pSub->pLimit;
  86808. pSub->pLimit = 0;
  86809. }
  86810. }
  86811. /* Finially, delete what is left of the subquery and return
  86812. ** success.
  86813. */
  86814. sqlite3SelectDelete(db, pSub1);
  86815. return 1;
  86816. }
  86817. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  86818. /*
  86819. ** Analyze the SELECT statement passed as an argument to see if it
  86820. ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
  86821. ** it is, or 0 otherwise. At present, a query is considered to be
  86822. ** a min()/max() query if:
  86823. **
  86824. ** 1. There is a single object in the FROM clause.
  86825. **
  86826. ** 2. There is a single expression in the result set, and it is
  86827. ** either min(x) or max(x), where x is a column reference.
  86828. */
  86829. static u8 minMaxQuery(Select *p){
  86830. Expr *pExpr;
  86831. ExprList *pEList = p->pEList;
  86832. if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
  86833. pExpr = pEList->a[0].pExpr;
  86834. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  86835. if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
  86836. pEList = pExpr->x.pList;
  86837. if( pEList==0 || pEList->nExpr!=1 ) return 0;
  86838. if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
  86839. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  86840. if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
  86841. return WHERE_ORDERBY_MIN;
  86842. }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
  86843. return WHERE_ORDERBY_MAX;
  86844. }
  86845. return WHERE_ORDERBY_NORMAL;
  86846. }
  86847. /*
  86848. ** The select statement passed as the first argument is an aggregate query.
  86849. ** The second argment is the associated aggregate-info object. This
  86850. ** function tests if the SELECT is of the form:
  86851. **
  86852. ** SELECT count(*) FROM <tbl>
  86853. **
  86854. ** where table is a database table, not a sub-select or view. If the query
  86855. ** does match this pattern, then a pointer to the Table object representing
  86856. ** <tbl> is returned. Otherwise, 0 is returned.
  86857. */
  86858. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  86859. Table *pTab;
  86860. Expr *pExpr;
  86861. assert( !p->pGroupBy );
  86862. if( p->pWhere || p->pEList->nExpr!=1
  86863. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  86864. ){
  86865. return 0;
  86866. }
  86867. pTab = p->pSrc->a[0].pTab;
  86868. pExpr = p->pEList->a[0].pExpr;
  86869. assert( pTab && !pTab->pSelect && pExpr );
  86870. if( IsVirtual(pTab) ) return 0;
  86871. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  86872. if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
  86873. if( pExpr->flags&EP_Distinct ) return 0;
  86874. return pTab;
  86875. }
  86876. /*
  86877. ** If the source-list item passed as an argument was augmented with an
  86878. ** INDEXED BY clause, then try to locate the specified index. If there
  86879. ** was such a clause and the named index cannot be found, return
  86880. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  86881. ** pFrom->pIndex and return SQLITE_OK.
  86882. */
  86883. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  86884. if( pFrom->pTab && pFrom->zIndex ){
  86885. Table *pTab = pFrom->pTab;
  86886. char *zIndex = pFrom->zIndex;
  86887. Index *pIdx;
  86888. for(pIdx=pTab->pIndex;
  86889. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  86890. pIdx=pIdx->pNext
  86891. );
  86892. if( !pIdx ){
  86893. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  86894. pParse->checkSchema = 1;
  86895. return SQLITE_ERROR;
  86896. }
  86897. pFrom->pIndex = pIdx;
  86898. }
  86899. return SQLITE_OK;
  86900. }
  86901. /*
  86902. ** This routine is a Walker callback for "expanding" a SELECT statement.
  86903. ** "Expanding" means to do the following:
  86904. **
  86905. ** (1) Make sure VDBE cursor numbers have been assigned to every
  86906. ** element of the FROM clause.
  86907. **
  86908. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  86909. ** defines FROM clause. When views appear in the FROM clause,
  86910. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  86911. ** that implements the view. A copy is made of the view's SELECT
  86912. ** statement so that we can freely modify or delete that statement
  86913. ** without worrying about messing up the presistent representation
  86914. ** of the view.
  86915. **
  86916. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  86917. ** on joins and the ON and USING clause of joins.
  86918. **
  86919. ** (4) Scan the list of columns in the result set (pEList) looking
  86920. ** for instances of the "*" operator or the TABLE.* operator.
  86921. ** If found, expand each "*" to be every column in every table
  86922. ** and TABLE.* to be every column in TABLE.
  86923. **
  86924. */
  86925. static int selectExpander(Walker *pWalker, Select *p){
  86926. Parse *pParse = pWalker->pParse;
  86927. int i, j, k;
  86928. SrcList *pTabList;
  86929. ExprList *pEList;
  86930. struct SrcList_item *pFrom;
  86931. sqlite3 *db = pParse->db;
  86932. if( db->mallocFailed ){
  86933. return WRC_Abort;
  86934. }
  86935. if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
  86936. return WRC_Prune;
  86937. }
  86938. p->selFlags |= SF_Expanded;
  86939. pTabList = p->pSrc;
  86940. pEList = p->pEList;
  86941. /* Make sure cursor numbers have been assigned to all entries in
  86942. ** the FROM clause of the SELECT statement.
  86943. */
  86944. sqlite3SrcListAssignCursors(pParse, pTabList);
  86945. /* Look up every table named in the FROM clause of the select. If
  86946. ** an entry of the FROM clause is a subquery instead of a table or view,
  86947. ** then create a transient table structure to describe the subquery.
  86948. */
  86949. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  86950. Table *pTab;
  86951. if( pFrom->pTab!=0 ){
  86952. /* This statement has already been prepared. There is no need
  86953. ** to go further. */
  86954. assert( i==0 );
  86955. return WRC_Prune;
  86956. }
  86957. if( pFrom->zName==0 ){
  86958. #ifndef SQLITE_OMIT_SUBQUERY
  86959. Select *pSel = pFrom->pSelect;
  86960. /* A sub-query in the FROM clause of a SELECT */
  86961. assert( pSel!=0 );
  86962. assert( pFrom->pTab==0 );
  86963. sqlite3WalkSelect(pWalker, pSel);
  86964. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  86965. if( pTab==0 ) return WRC_Abort;
  86966. pTab->nRef = 1;
  86967. pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
  86968. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  86969. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  86970. pTab->iPKey = -1;
  86971. pTab->nRowEst = 1000000;
  86972. pTab->tabFlags |= TF_Ephemeral;
  86973. #endif
  86974. }else{
  86975. /* An ordinary table or view name in the FROM clause */
  86976. assert( pFrom->pTab==0 );
  86977. pFrom->pTab = pTab =
  86978. sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
  86979. if( pTab==0 ) return WRC_Abort;
  86980. pTab->nRef++;
  86981. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  86982. if( pTab->pSelect || IsVirtual(pTab) ){
  86983. /* We reach here if the named table is a really a view */
  86984. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  86985. assert( pFrom->pSelect==0 );
  86986. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  86987. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  86988. }
  86989. #endif
  86990. }
  86991. /* Locate the index named by the INDEXED BY clause, if any. */
  86992. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  86993. return WRC_Abort;
  86994. }
  86995. }
  86996. /* Process NATURAL keywords, and ON and USING clauses of joins.
  86997. */
  86998. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  86999. return WRC_Abort;
  87000. }
  87001. /* For every "*" that occurs in the column list, insert the names of
  87002. ** all columns in all tables. And for every TABLE.* insert the names
  87003. ** of all columns in TABLE. The parser inserted a special expression
  87004. ** with the TK_ALL operator for each "*" that it found in the column list.
  87005. ** The following code just has to locate the TK_ALL expressions and expand
  87006. ** each one to the list of all columns in all tables.
  87007. **
  87008. ** The first loop just checks to see if there are any "*" operators
  87009. ** that need expanding.
  87010. */
  87011. for(k=0; k<pEList->nExpr; k++){
  87012. Expr *pE = pEList->a[k].pExpr;
  87013. if( pE->op==TK_ALL ) break;
  87014. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  87015. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  87016. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  87017. }
  87018. if( k<pEList->nExpr ){
  87019. /*
  87020. ** If we get here it means the result set contains one or more "*"
  87021. ** operators that need to be expanded. Loop through each expression
  87022. ** in the result set and expand them one by one.
  87023. */
  87024. struct ExprList_item *a = pEList->a;
  87025. ExprList *pNew = 0;
  87026. int flags = pParse->db->flags;
  87027. int longNames = (flags & SQLITE_FullColNames)!=0
  87028. && (flags & SQLITE_ShortColNames)==0;
  87029. for(k=0; k<pEList->nExpr; k++){
  87030. Expr *pE = a[k].pExpr;
  87031. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  87032. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
  87033. /* This particular expression does not need to be expanded.
  87034. */
  87035. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  87036. if( pNew ){
  87037. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  87038. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  87039. a[k].zName = 0;
  87040. a[k].zSpan = 0;
  87041. }
  87042. a[k].pExpr = 0;
  87043. }else{
  87044. /* This expression is a "*" or a "TABLE.*" and needs to be
  87045. ** expanded. */
  87046. int tableSeen = 0; /* Set to 1 when TABLE matches */
  87047. char *zTName; /* text of name of TABLE */
  87048. if( pE->op==TK_DOT ){
  87049. assert( pE->pLeft!=0 );
  87050. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  87051. zTName = pE->pLeft->u.zToken;
  87052. }else{
  87053. zTName = 0;
  87054. }
  87055. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  87056. Table *pTab = pFrom->pTab;
  87057. char *zTabName = pFrom->zAlias;
  87058. if( zTabName==0 ){
  87059. zTabName = pTab->zName;
  87060. }
  87061. if( db->mallocFailed ) break;
  87062. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  87063. continue;
  87064. }
  87065. tableSeen = 1;
  87066. for(j=0; j<pTab->nCol; j++){
  87067. Expr *pExpr, *pRight;
  87068. char *zName = pTab->aCol[j].zName;
  87069. char *zColname; /* The computed column name */
  87070. char *zToFree; /* Malloced string that needs to be freed */
  87071. Token sColname; /* Computed column name as a token */
  87072. /* If a column is marked as 'hidden' (currently only possible
  87073. ** for virtual tables), do not include it in the expanded
  87074. ** result-set list.
  87075. */
  87076. if( IsHiddenColumn(&pTab->aCol[j]) ){
  87077. assert(IsVirtual(pTab));
  87078. continue;
  87079. }
  87080. if( i>0 && zTName==0 ){
  87081. if( (pFrom->jointype & JT_NATURAL)!=0
  87082. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  87083. ){
  87084. /* In a NATURAL join, omit the join columns from the
  87085. ** table to the right of the join */
  87086. continue;
  87087. }
  87088. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  87089. /* In a join with a USING clause, omit columns in the
  87090. ** using clause from the table on the right. */
  87091. continue;
  87092. }
  87093. }
  87094. pRight = sqlite3Expr(db, TK_ID, zName);
  87095. zColname = zName;
  87096. zToFree = 0;
  87097. if( longNames || pTabList->nSrc>1 ){
  87098. Expr *pLeft;
  87099. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  87100. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  87101. if( longNames ){
  87102. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  87103. zToFree = zColname;
  87104. }
  87105. }else{
  87106. pExpr = pRight;
  87107. }
  87108. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  87109. sColname.z = zColname;
  87110. sColname.n = sqlite3Strlen30(zColname);
  87111. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  87112. sqlite3DbFree(db, zToFree);
  87113. }
  87114. }
  87115. if( !tableSeen ){
  87116. if( zTName ){
  87117. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  87118. }else{
  87119. sqlite3ErrorMsg(pParse, "no tables specified");
  87120. }
  87121. }
  87122. }
  87123. }
  87124. sqlite3ExprListDelete(db, pEList);
  87125. p->pEList = pNew;
  87126. }
  87127. #if SQLITE_MAX_COLUMN
  87128. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  87129. sqlite3ErrorMsg(pParse, "too many columns in result set");
  87130. }
  87131. #endif
  87132. return WRC_Continue;
  87133. }
  87134. /*
  87135. ** No-op routine for the parse-tree walker.
  87136. **
  87137. ** When this routine is the Walker.xExprCallback then expression trees
  87138. ** are walked without any actions being taken at each node. Presumably,
  87139. ** when this routine is used for Walker.xExprCallback then
  87140. ** Walker.xSelectCallback is set to do something useful for every
  87141. ** subquery in the parser tree.
  87142. */
  87143. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  87144. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  87145. return WRC_Continue;
  87146. }
  87147. /*
  87148. ** This routine "expands" a SELECT statement and all of its subqueries.
  87149. ** For additional information on what it means to "expand" a SELECT
  87150. ** statement, see the comment on the selectExpand worker callback above.
  87151. **
  87152. ** Expanding a SELECT statement is the first step in processing a
  87153. ** SELECT statement. The SELECT statement must be expanded before
  87154. ** name resolution is performed.
  87155. **
  87156. ** If anything goes wrong, an error message is written into pParse.
  87157. ** The calling function can detect the problem by looking at pParse->nErr
  87158. ** and/or pParse->db->mallocFailed.
  87159. */
  87160. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  87161. Walker w;
  87162. w.xSelectCallback = selectExpander;
  87163. w.xExprCallback = exprWalkNoop;
  87164. w.pParse = pParse;
  87165. sqlite3WalkSelect(&w, pSelect);
  87166. }
  87167. #ifndef SQLITE_OMIT_SUBQUERY
  87168. /*
  87169. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  87170. ** interface.
  87171. **
  87172. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  87173. ** information to the Table structure that represents the result set
  87174. ** of that subquery.
  87175. **
  87176. ** The Table structure that represents the result set was constructed
  87177. ** by selectExpander() but the type and collation information was omitted
  87178. ** at that point because identifiers had not yet been resolved. This
  87179. ** routine is called after identifier resolution.
  87180. */
  87181. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  87182. Parse *pParse;
  87183. int i;
  87184. SrcList *pTabList;
  87185. struct SrcList_item *pFrom;
  87186. assert( p->selFlags & SF_Resolved );
  87187. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  87188. p->selFlags |= SF_HasTypeInfo;
  87189. pParse = pWalker->pParse;
  87190. pTabList = p->pSrc;
  87191. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  87192. Table *pTab = pFrom->pTab;
  87193. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  87194. /* A sub-query in the FROM clause of a SELECT */
  87195. Select *pSel = pFrom->pSelect;
  87196. assert( pSel );
  87197. while( pSel->pPrior ) pSel = pSel->pPrior;
  87198. selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
  87199. }
  87200. }
  87201. }
  87202. return WRC_Continue;
  87203. }
  87204. #endif
  87205. /*
  87206. ** This routine adds datatype and collating sequence information to
  87207. ** the Table structures of all FROM-clause subqueries in a
  87208. ** SELECT statement.
  87209. **
  87210. ** Use this routine after name resolution.
  87211. */
  87212. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  87213. #ifndef SQLITE_OMIT_SUBQUERY
  87214. Walker w;
  87215. w.xSelectCallback = selectAddSubqueryTypeInfo;
  87216. w.xExprCallback = exprWalkNoop;
  87217. w.pParse = pParse;
  87218. sqlite3WalkSelect(&w, pSelect);
  87219. #endif
  87220. }
  87221. /*
  87222. ** This routine sets of a SELECT statement for processing. The
  87223. ** following is accomplished:
  87224. **
  87225. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  87226. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  87227. ** * ON and USING clauses are shifted into WHERE statements
  87228. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  87229. ** * Identifiers in expression are matched to tables.
  87230. **
  87231. ** This routine acts recursively on all subqueries within the SELECT.
  87232. */
  87233. SQLITE_PRIVATE void sqlite3SelectPrep(
  87234. Parse *pParse, /* The parser context */
  87235. Select *p, /* The SELECT statement being coded. */
  87236. NameContext *pOuterNC /* Name context for container */
  87237. ){
  87238. sqlite3 *db;
  87239. if( NEVER(p==0) ) return;
  87240. db = pParse->db;
  87241. if( p->selFlags & SF_HasTypeInfo ) return;
  87242. sqlite3SelectExpand(pParse, p);
  87243. if( pParse->nErr || db->mallocFailed ) return;
  87244. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  87245. if( pParse->nErr || db->mallocFailed ) return;
  87246. sqlite3SelectAddTypeInfo(pParse, p);
  87247. }
  87248. /*
  87249. ** Reset the aggregate accumulator.
  87250. **
  87251. ** The aggregate accumulator is a set of memory cells that hold
  87252. ** intermediate results while calculating an aggregate. This
  87253. ** routine simply stores NULLs in all of those memory cells.
  87254. */
  87255. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  87256. Vdbe *v = pParse->pVdbe;
  87257. int i;
  87258. struct AggInfo_func *pFunc;
  87259. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  87260. return;
  87261. }
  87262. for(i=0; i<pAggInfo->nColumn; i++){
  87263. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  87264. }
  87265. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  87266. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  87267. if( pFunc->iDistinct>=0 ){
  87268. Expr *pE = pFunc->pExpr;
  87269. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  87270. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  87271. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  87272. "argument");
  87273. pFunc->iDistinct = -1;
  87274. }else{
  87275. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  87276. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  87277. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  87278. }
  87279. }
  87280. }
  87281. }
  87282. /*
  87283. ** Invoke the OP_AggFinalize opcode for every aggregate function
  87284. ** in the AggInfo structure.
  87285. */
  87286. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  87287. Vdbe *v = pParse->pVdbe;
  87288. int i;
  87289. struct AggInfo_func *pF;
  87290. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  87291. ExprList *pList = pF->pExpr->x.pList;
  87292. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  87293. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  87294. (void*)pF->pFunc, P4_FUNCDEF);
  87295. }
  87296. }
  87297. /*
  87298. ** Update the accumulator memory cells for an aggregate based on
  87299. ** the current cursor position.
  87300. */
  87301. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  87302. Vdbe *v = pParse->pVdbe;
  87303. int i;
  87304. struct AggInfo_func *pF;
  87305. struct AggInfo_col *pC;
  87306. pAggInfo->directMode = 1;
  87307. sqlite3ExprCacheClear(pParse);
  87308. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  87309. int nArg;
  87310. int addrNext = 0;
  87311. int regAgg;
  87312. ExprList *pList = pF->pExpr->x.pList;
  87313. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  87314. if( pList ){
  87315. nArg = pList->nExpr;
  87316. regAgg = sqlite3GetTempRange(pParse, nArg);
  87317. sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
  87318. }else{
  87319. nArg = 0;
  87320. regAgg = 0;
  87321. }
  87322. if( pF->iDistinct>=0 ){
  87323. addrNext = sqlite3VdbeMakeLabel(v);
  87324. assert( nArg==1 );
  87325. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  87326. }
  87327. if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  87328. CollSeq *pColl = 0;
  87329. struct ExprList_item *pItem;
  87330. int j;
  87331. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  87332. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  87333. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  87334. }
  87335. if( !pColl ){
  87336. pColl = pParse->db->pDfltColl;
  87337. }
  87338. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  87339. }
  87340. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  87341. (void*)pF->pFunc, P4_FUNCDEF);
  87342. sqlite3VdbeChangeP5(v, (u8)nArg);
  87343. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  87344. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  87345. if( addrNext ){
  87346. sqlite3VdbeResolveLabel(v, addrNext);
  87347. sqlite3ExprCacheClear(pParse);
  87348. }
  87349. }
  87350. /* Before populating the accumulator registers, clear the column cache.
  87351. ** Otherwise, if any of the required column values are already present
  87352. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  87353. ** to pC->iMem. But by the time the value is used, the original register
  87354. ** may have been used, invalidating the underlying buffer holding the
  87355. ** text or blob value. See ticket [883034dcb5].
  87356. **
  87357. ** Another solution would be to change the OP_SCopy used to copy cached
  87358. ** values to an OP_Copy.
  87359. */
  87360. sqlite3ExprCacheClear(pParse);
  87361. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  87362. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  87363. }
  87364. pAggInfo->directMode = 0;
  87365. sqlite3ExprCacheClear(pParse);
  87366. }
  87367. /*
  87368. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  87369. ** count(*) query ("SELECT count(*) FROM pTab").
  87370. */
  87371. #ifndef SQLITE_OMIT_EXPLAIN
  87372. static void explainSimpleCount(
  87373. Parse *pParse, /* Parse context */
  87374. Table *pTab, /* Table being queried */
  87375. Index *pIdx /* Index used to optimize scan, or NULL */
  87376. ){
  87377. if( pParse->explain==2 ){
  87378. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
  87379. pTab->zName,
  87380. pIdx ? "USING COVERING INDEX " : "",
  87381. pIdx ? pIdx->zName : "",
  87382. pTab->nRowEst
  87383. );
  87384. sqlite3VdbeAddOp4(
  87385. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  87386. );
  87387. }
  87388. }
  87389. #else
  87390. # define explainSimpleCount(a,b,c)
  87391. #endif
  87392. /*
  87393. ** Generate code for the SELECT statement given in the p argument.
  87394. **
  87395. ** The results are distributed in various ways depending on the
  87396. ** contents of the SelectDest structure pointed to by argument pDest
  87397. ** as follows:
  87398. **
  87399. ** pDest->eDest Result
  87400. ** ------------ -------------------------------------------
  87401. ** SRT_Output Generate a row of output (using the OP_ResultRow
  87402. ** opcode) for each row in the result set.
  87403. **
  87404. ** SRT_Mem Only valid if the result is a single column.
  87405. ** Store the first column of the first result row
  87406. ** in register pDest->iParm then abandon the rest
  87407. ** of the query. This destination implies "LIMIT 1".
  87408. **
  87409. ** SRT_Set The result must be a single column. Store each
  87410. ** row of result as the key in table pDest->iParm.
  87411. ** Apply the affinity pDest->affinity before storing
  87412. ** results. Used to implement "IN (SELECT ...)".
  87413. **
  87414. ** SRT_Union Store results as a key in a temporary table pDest->iParm.
  87415. **
  87416. ** SRT_Except Remove results from the temporary table pDest->iParm.
  87417. **
  87418. ** SRT_Table Store results in temporary table pDest->iParm.
  87419. ** This is like SRT_EphemTab except that the table
  87420. ** is assumed to already be open.
  87421. **
  87422. ** SRT_EphemTab Create an temporary table pDest->iParm and store
  87423. ** the result there. The cursor is left open after
  87424. ** returning. This is like SRT_Table except that
  87425. ** this destination uses OP_OpenEphemeral to create
  87426. ** the table first.
  87427. **
  87428. ** SRT_Coroutine Generate a co-routine that returns a new row of
  87429. ** results each time it is invoked. The entry point
  87430. ** of the co-routine is stored in register pDest->iParm.
  87431. **
  87432. ** SRT_Exists Store a 1 in memory cell pDest->iParm if the result
  87433. ** set is not empty.
  87434. **
  87435. ** SRT_Discard Throw the results away. This is used by SELECT
  87436. ** statements within triggers whose only purpose is
  87437. ** the side-effects of functions.
  87438. **
  87439. ** This routine returns the number of errors. If any errors are
  87440. ** encountered, then an appropriate error message is left in
  87441. ** pParse->zErrMsg.
  87442. **
  87443. ** This routine does NOT free the Select structure passed in. The
  87444. ** calling function needs to do that.
  87445. */
  87446. SQLITE_PRIVATE int sqlite3Select(
  87447. Parse *pParse, /* The parser context */
  87448. Select *p, /* The SELECT statement being coded. */
  87449. SelectDest *pDest /* What to do with the query results */
  87450. ){
  87451. int i, j; /* Loop counters */
  87452. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  87453. Vdbe *v; /* The virtual machine under construction */
  87454. int isAgg; /* True for select lists like "count(*)" */
  87455. ExprList *pEList; /* List of columns to extract. */
  87456. SrcList *pTabList; /* List of tables to select from */
  87457. Expr *pWhere; /* The WHERE clause. May be NULL */
  87458. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  87459. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  87460. Expr *pHaving; /* The HAVING clause. May be NULL */
  87461. int isDistinct; /* True if the DISTINCT keyword is present */
  87462. int distinct; /* Table to use for the distinct set */
  87463. int rc = 1; /* Value to return from this function */
  87464. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  87465. AggInfo sAggInfo; /* Information used by aggregate queries */
  87466. int iEnd; /* Address of the end of the query */
  87467. sqlite3 *db; /* The database connection */
  87468. #ifndef SQLITE_OMIT_EXPLAIN
  87469. int iRestoreSelectId = pParse->iSelectId;
  87470. pParse->iSelectId = pParse->iNextSelectId++;
  87471. #endif
  87472. db = pParse->db;
  87473. if( p==0 || db->mallocFailed || pParse->nErr ){
  87474. return 1;
  87475. }
  87476. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  87477. memset(&sAggInfo, 0, sizeof(sAggInfo));
  87478. if( IgnorableOrderby(pDest) ){
  87479. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  87480. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  87481. /* If ORDER BY makes no difference in the output then neither does
  87482. ** DISTINCT so it can be removed too. */
  87483. sqlite3ExprListDelete(db, p->pOrderBy);
  87484. p->pOrderBy = 0;
  87485. p->selFlags &= ~SF_Distinct;
  87486. }
  87487. sqlite3SelectPrep(pParse, p, 0);
  87488. pOrderBy = p->pOrderBy;
  87489. pTabList = p->pSrc;
  87490. pEList = p->pEList;
  87491. if( pParse->nErr || db->mallocFailed ){
  87492. goto select_end;
  87493. }
  87494. isAgg = (p->selFlags & SF_Aggregate)!=0;
  87495. assert( pEList!=0 );
  87496. /* Begin generating code.
  87497. */
  87498. v = sqlite3GetVdbe(pParse);
  87499. if( v==0 ) goto select_end;
  87500. /* If writing to memory or generating a set
  87501. ** only a single column may be output.
  87502. */
  87503. #ifndef SQLITE_OMIT_SUBQUERY
  87504. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  87505. goto select_end;
  87506. }
  87507. #endif
  87508. /* Generate code for all sub-queries in the FROM clause
  87509. */
  87510. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  87511. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  87512. struct SrcList_item *pItem = &pTabList->a[i];
  87513. SelectDest dest;
  87514. Select *pSub = pItem->pSelect;
  87515. int isAggSub;
  87516. if( pSub==0 || pItem->isPopulated ) continue;
  87517. /* Increment Parse.nHeight by the height of the largest expression
  87518. ** tree refered to by this, the parent select. The child select
  87519. ** may contain expression trees of at most
  87520. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  87521. ** more conservative than necessary, but much easier than enforcing
  87522. ** an exact limit.
  87523. */
  87524. pParse->nHeight += sqlite3SelectExprHeight(p);
  87525. /* Check to see if the subquery can be absorbed into the parent. */
  87526. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  87527. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  87528. if( isAggSub ){
  87529. isAgg = 1;
  87530. p->selFlags |= SF_Aggregate;
  87531. }
  87532. i = -1;
  87533. }else{
  87534. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  87535. assert( pItem->isPopulated==0 );
  87536. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  87537. sqlite3Select(pParse, pSub, &dest);
  87538. pItem->isPopulated = 1;
  87539. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  87540. }
  87541. if( /*pParse->nErr ||*/ db->mallocFailed ){
  87542. goto select_end;
  87543. }
  87544. pParse->nHeight -= sqlite3SelectExprHeight(p);
  87545. pTabList = p->pSrc;
  87546. if( !IgnorableOrderby(pDest) ){
  87547. pOrderBy = p->pOrderBy;
  87548. }
  87549. }
  87550. pEList = p->pEList;
  87551. #endif
  87552. pWhere = p->pWhere;
  87553. pGroupBy = p->pGroupBy;
  87554. pHaving = p->pHaving;
  87555. isDistinct = (p->selFlags & SF_Distinct)!=0;
  87556. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  87557. /* If there is are a sequence of queries, do the earlier ones first.
  87558. */
  87559. if( p->pPrior ){
  87560. if( p->pRightmost==0 ){
  87561. Select *pLoop, *pRight = 0;
  87562. int cnt = 0;
  87563. int mxSelect;
  87564. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  87565. pLoop->pRightmost = p;
  87566. pLoop->pNext = pRight;
  87567. pRight = pLoop;
  87568. }
  87569. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  87570. if( mxSelect && cnt>mxSelect ){
  87571. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  87572. goto select_end;
  87573. }
  87574. }
  87575. rc = multiSelect(pParse, p, pDest);
  87576. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  87577. return rc;
  87578. }
  87579. #endif
  87580. /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
  87581. ** GROUP BY might use an index, DISTINCT never does.
  87582. */
  87583. assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
  87584. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
  87585. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  87586. pGroupBy = p->pGroupBy;
  87587. p->selFlags &= ~SF_Distinct;
  87588. }
  87589. /* If there is both a GROUP BY and an ORDER BY clause and they are
  87590. ** identical, then disable the ORDER BY clause since the GROUP BY
  87591. ** will cause elements to come out in the correct order. This is
  87592. ** an optimization - the correct answer should result regardless.
  87593. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  87594. ** to disable this optimization for testing purposes.
  87595. */
  87596. if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
  87597. && (db->flags & SQLITE_GroupByOrder)==0 ){
  87598. pOrderBy = 0;
  87599. }
  87600. /* If there is an ORDER BY clause, then this sorting
  87601. ** index might end up being unused if the data can be
  87602. ** extracted in pre-sorted order. If that is the case, then the
  87603. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  87604. ** we figure out that the sorting index is not needed. The addrSortIndex
  87605. ** variable is used to facilitate that change.
  87606. */
  87607. if( pOrderBy ){
  87608. KeyInfo *pKeyInfo;
  87609. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  87610. pOrderBy->iECursor = pParse->nTab++;
  87611. p->addrOpenEphm[2] = addrSortIndex =
  87612. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  87613. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  87614. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  87615. }else{
  87616. addrSortIndex = -1;
  87617. }
  87618. /* If the output is destined for a temporary table, open that table.
  87619. */
  87620. if( pDest->eDest==SRT_EphemTab ){
  87621. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
  87622. }
  87623. /* Set the limiter.
  87624. */
  87625. iEnd = sqlite3VdbeMakeLabel(v);
  87626. p->nSelectRow = (double)LARGEST_INT64;
  87627. computeLimitRegisters(pParse, p, iEnd);
  87628. /* Open a virtual index to use for the distinct set.
  87629. */
  87630. if( p->selFlags & SF_Distinct ){
  87631. KeyInfo *pKeyInfo;
  87632. assert( isAgg || pGroupBy );
  87633. distinct = pParse->nTab++;
  87634. pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
  87635. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
  87636. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  87637. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  87638. }else{
  87639. distinct = -1;
  87640. }
  87641. /* Aggregate and non-aggregate queries are handled differently */
  87642. if( !isAgg && pGroupBy==0 ){
  87643. /* This case is for non-aggregate queries
  87644. ** Begin the database scan
  87645. */
  87646. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
  87647. if( pWInfo==0 ) goto select_end;
  87648. if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
  87649. /* If sorting index that was created by a prior OP_OpenEphemeral
  87650. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  87651. ** into an OP_Noop.
  87652. */
  87653. if( addrSortIndex>=0 && pOrderBy==0 ){
  87654. sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
  87655. p->addrOpenEphm[2] = -1;
  87656. }
  87657. /* Use the standard inner loop
  87658. */
  87659. assert(!isDistinct);
  87660. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
  87661. pWInfo->iContinue, pWInfo->iBreak);
  87662. /* End the database scan loop.
  87663. */
  87664. sqlite3WhereEnd(pWInfo);
  87665. }else{
  87666. /* This is the processing for aggregate queries */
  87667. NameContext sNC; /* Name context for processing aggregate information */
  87668. int iAMem; /* First Mem address for storing current GROUP BY */
  87669. int iBMem; /* First Mem address for previous GROUP BY */
  87670. int iUseFlag; /* Mem address holding flag indicating that at least
  87671. ** one row of the input to the aggregator has been
  87672. ** processed */
  87673. int iAbortFlag; /* Mem address which causes query abort if positive */
  87674. int groupBySort; /* Rows come from source in GROUP BY order */
  87675. int addrEnd; /* End of processing for this SELECT */
  87676. /* Remove any and all aliases between the result set and the
  87677. ** GROUP BY clause.
  87678. */
  87679. if( pGroupBy ){
  87680. int k; /* Loop counter */
  87681. struct ExprList_item *pItem; /* For looping over expression in a list */
  87682. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  87683. pItem->iAlias = 0;
  87684. }
  87685. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  87686. pItem->iAlias = 0;
  87687. }
  87688. if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
  87689. }else{
  87690. p->nSelectRow = (double)1;
  87691. }
  87692. /* Create a label to jump to when we want to abort the query */
  87693. addrEnd = sqlite3VdbeMakeLabel(v);
  87694. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  87695. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  87696. ** SELECT statement.
  87697. */
  87698. memset(&sNC, 0, sizeof(sNC));
  87699. sNC.pParse = pParse;
  87700. sNC.pSrcList = pTabList;
  87701. sNC.pAggInfo = &sAggInfo;
  87702. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  87703. sAggInfo.pGroupBy = pGroupBy;
  87704. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  87705. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  87706. if( pHaving ){
  87707. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  87708. }
  87709. sAggInfo.nAccumulator = sAggInfo.nColumn;
  87710. for(i=0; i<sAggInfo.nFunc; i++){
  87711. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  87712. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  87713. }
  87714. if( db->mallocFailed ) goto select_end;
  87715. /* Processing for aggregates with GROUP BY is very different and
  87716. ** much more complex than aggregates without a GROUP BY.
  87717. */
  87718. if( pGroupBy ){
  87719. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  87720. int j1; /* A-vs-B comparision jump */
  87721. int addrOutputRow; /* Start of subroutine that outputs a result row */
  87722. int regOutputRow; /* Return address register for output subroutine */
  87723. int addrSetAbort; /* Set the abort flag and return */
  87724. int addrTopOfLoop; /* Top of the input loop */
  87725. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  87726. int addrReset; /* Subroutine for resetting the accumulator */
  87727. int regReset; /* Return address register for reset subroutine */
  87728. /* If there is a GROUP BY clause we might need a sorting index to
  87729. ** implement it. Allocate that sorting index now. If it turns out
  87730. ** that we do not need it after all, the OpenEphemeral instruction
  87731. ** will be converted into a Noop.
  87732. */
  87733. sAggInfo.sortingIdx = pParse->nTab++;
  87734. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  87735. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  87736. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  87737. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  87738. /* Initialize memory locations used by GROUP BY aggregate processing
  87739. */
  87740. iUseFlag = ++pParse->nMem;
  87741. iAbortFlag = ++pParse->nMem;
  87742. regOutputRow = ++pParse->nMem;
  87743. addrOutputRow = sqlite3VdbeMakeLabel(v);
  87744. regReset = ++pParse->nMem;
  87745. addrReset = sqlite3VdbeMakeLabel(v);
  87746. iAMem = pParse->nMem + 1;
  87747. pParse->nMem += pGroupBy->nExpr;
  87748. iBMem = pParse->nMem + 1;
  87749. pParse->nMem += pGroupBy->nExpr;
  87750. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  87751. VdbeComment((v, "clear abort flag"));
  87752. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  87753. VdbeComment((v, "indicate accumulator empty"));
  87754. /* Begin a loop that will extract all source rows in GROUP BY order.
  87755. ** This might involve two separate loops with an OP_Sort in between, or
  87756. ** it might be a single loop that uses an index to extract information
  87757. ** in the right order to begin with.
  87758. */
  87759. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  87760. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
  87761. if( pWInfo==0 ) goto select_end;
  87762. if( pGroupBy==0 ){
  87763. /* The optimizer is able to deliver rows in group by order so
  87764. ** we do not have to sort. The OP_OpenEphemeral table will be
  87765. ** cancelled later because we still need to use the pKeyInfo
  87766. */
  87767. pGroupBy = p->pGroupBy;
  87768. groupBySort = 0;
  87769. }else{
  87770. /* Rows are coming out in undetermined order. We have to push
  87771. ** each row into a sorting index, terminate the first loop,
  87772. ** then loop over the sorting index in order to get the output
  87773. ** in sorted order
  87774. */
  87775. int regBase;
  87776. int regRecord;
  87777. int nCol;
  87778. int nGroupBy;
  87779. explainTempTable(pParse,
  87780. isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
  87781. groupBySort = 1;
  87782. nGroupBy = pGroupBy->nExpr;
  87783. nCol = nGroupBy + 1;
  87784. j = nGroupBy+1;
  87785. for(i=0; i<sAggInfo.nColumn; i++){
  87786. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  87787. nCol++;
  87788. j++;
  87789. }
  87790. }
  87791. regBase = sqlite3GetTempRange(pParse, nCol);
  87792. sqlite3ExprCacheClear(pParse);
  87793. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  87794. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  87795. j = nGroupBy+1;
  87796. for(i=0; i<sAggInfo.nColumn; i++){
  87797. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  87798. if( pCol->iSorterColumn>=j ){
  87799. int r1 = j + regBase;
  87800. int r2;
  87801. r2 = sqlite3ExprCodeGetColumn(pParse,
  87802. pCol->pTab, pCol->iColumn, pCol->iTable, r1);
  87803. if( r1!=r2 ){
  87804. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  87805. }
  87806. j++;
  87807. }
  87808. }
  87809. regRecord = sqlite3GetTempReg(pParse);
  87810. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  87811. sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
  87812. sqlite3ReleaseTempReg(pParse, regRecord);
  87813. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  87814. sqlite3WhereEnd(pWInfo);
  87815. sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
  87816. VdbeComment((v, "GROUP BY sort"));
  87817. sAggInfo.useSortingIdx = 1;
  87818. sqlite3ExprCacheClear(pParse);
  87819. }
  87820. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  87821. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  87822. ** Then compare the current GROUP BY terms against the GROUP BY terms
  87823. ** from the previous row currently stored in a0, a1, a2...
  87824. */
  87825. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  87826. sqlite3ExprCacheClear(pParse);
  87827. for(j=0; j<pGroupBy->nExpr; j++){
  87828. if( groupBySort ){
  87829. sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
  87830. }else{
  87831. sAggInfo.directMode = 1;
  87832. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  87833. }
  87834. }
  87835. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  87836. (char*)pKeyInfo, P4_KEYINFO);
  87837. j1 = sqlite3VdbeCurrentAddr(v);
  87838. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  87839. /* Generate code that runs whenever the GROUP BY changes.
  87840. ** Changes in the GROUP BY are detected by the previous code
  87841. ** block. If there were no changes, this block is skipped.
  87842. **
  87843. ** This code copies current group by terms in b0,b1,b2,...
  87844. ** over to a0,a1,a2. It then calls the output subroutine
  87845. ** and resets the aggregate accumulator registers in preparation
  87846. ** for the next GROUP BY batch.
  87847. */
  87848. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  87849. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  87850. VdbeComment((v, "output one row"));
  87851. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  87852. VdbeComment((v, "check abort flag"));
  87853. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  87854. VdbeComment((v, "reset accumulator"));
  87855. /* Update the aggregate accumulators based on the content of
  87856. ** the current row
  87857. */
  87858. sqlite3VdbeJumpHere(v, j1);
  87859. updateAccumulator(pParse, &sAggInfo);
  87860. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  87861. VdbeComment((v, "indicate data in accumulator"));
  87862. /* End of the loop
  87863. */
  87864. if( groupBySort ){
  87865. sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
  87866. }else{
  87867. sqlite3WhereEnd(pWInfo);
  87868. sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
  87869. }
  87870. /* Output the final row of result
  87871. */
  87872. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  87873. VdbeComment((v, "output final row"));
  87874. /* Jump over the subroutines
  87875. */
  87876. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  87877. /* Generate a subroutine that outputs a single row of the result
  87878. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  87879. ** is less than or equal to zero, the subroutine is a no-op. If
  87880. ** the processing calls for the query to abort, this subroutine
  87881. ** increments the iAbortFlag memory location before returning in
  87882. ** order to signal the caller to abort.
  87883. */
  87884. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  87885. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  87886. VdbeComment((v, "set abort flag"));
  87887. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  87888. sqlite3VdbeResolveLabel(v, addrOutputRow);
  87889. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  87890. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  87891. VdbeComment((v, "Groupby result generator entry point"));
  87892. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  87893. finalizeAggFunctions(pParse, &sAggInfo);
  87894. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  87895. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  87896. distinct, pDest,
  87897. addrOutputRow+1, addrSetAbort);
  87898. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  87899. VdbeComment((v, "end groupby result generator"));
  87900. /* Generate a subroutine that will reset the group-by accumulator
  87901. */
  87902. sqlite3VdbeResolveLabel(v, addrReset);
  87903. resetAccumulator(pParse, &sAggInfo);
  87904. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  87905. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  87906. else {
  87907. ExprList *pDel = 0;
  87908. #ifndef SQLITE_OMIT_BTREECOUNT
  87909. Table *pTab;
  87910. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  87911. /* If isSimpleCount() returns a pointer to a Table structure, then
  87912. ** the SQL statement is of the form:
  87913. **
  87914. ** SELECT count(*) FROM <tbl>
  87915. **
  87916. ** where the Table structure returned represents table <tbl>.
  87917. **
  87918. ** This statement is so common that it is optimized specially. The
  87919. ** OP_Count instruction is executed either on the intkey table that
  87920. ** contains the data for table <tbl> or on one of its indexes. It
  87921. ** is better to execute the op on an index, as indexes are almost
  87922. ** always spread across less pages than their corresponding tables.
  87923. */
  87924. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  87925. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  87926. Index *pIdx; /* Iterator variable */
  87927. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  87928. Index *pBest = 0; /* Best index found so far */
  87929. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  87930. sqlite3CodeVerifySchema(pParse, iDb);
  87931. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  87932. /* Search for the index that has the least amount of columns. If
  87933. ** there is such an index, and it has less columns than the table
  87934. ** does, then we can assume that it consumes less space on disk and
  87935. ** will therefore be cheaper to scan to determine the query result.
  87936. ** In this case set iRoot to the root page number of the index b-tree
  87937. ** and pKeyInfo to the KeyInfo structure required to navigate the
  87938. ** index.
  87939. **
  87940. ** In practice the KeyInfo structure will not be used. It is only
  87941. ** passed to keep OP_OpenRead happy.
  87942. */
  87943. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  87944. if( !pBest || pIdx->nColumn<pBest->nColumn ){
  87945. pBest = pIdx;
  87946. }
  87947. }
  87948. if( pBest && pBest->nColumn<pTab->nCol ){
  87949. iRoot = pBest->tnum;
  87950. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  87951. }
  87952. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  87953. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  87954. if( pKeyInfo ){
  87955. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  87956. }
  87957. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  87958. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  87959. explainSimpleCount(pParse, pTab, pBest);
  87960. }else
  87961. #endif /* SQLITE_OMIT_BTREECOUNT */
  87962. {
  87963. /* Check if the query is of one of the following forms:
  87964. **
  87965. ** SELECT min(x) FROM ...
  87966. ** SELECT max(x) FROM ...
  87967. **
  87968. ** If it is, then ask the code in where.c to attempt to sort results
  87969. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  87970. ** If where.c is able to produce results sorted in this order, then
  87971. ** add vdbe code to break out of the processing loop after the
  87972. ** first iteration (since the first iteration of the loop is
  87973. ** guaranteed to operate on the row with the minimum or maximum
  87974. ** value of x, the only row required).
  87975. **
  87976. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  87977. ** modify behaviour as follows:
  87978. **
  87979. ** + If the query is a "SELECT min(x)", then the loop coded by
  87980. ** where.c should not iterate over any values with a NULL value
  87981. ** for x.
  87982. **
  87983. ** + The optimizer code in where.c (the thing that decides which
  87984. ** index or indices to use) should place a different priority on
  87985. ** satisfying the 'ORDER BY' clause than it does in other cases.
  87986. ** Refer to code and comments in where.c for details.
  87987. */
  87988. ExprList *pMinMax = 0;
  87989. u8 flag = minMaxQuery(p);
  87990. if( flag ){
  87991. assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
  87992. pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
  87993. pDel = pMinMax;
  87994. if( pMinMax && !db->mallocFailed ){
  87995. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  87996. pMinMax->a[0].pExpr->op = TK_COLUMN;
  87997. }
  87998. }
  87999. /* This case runs if the aggregate has no GROUP BY clause. The
  88000. ** processing is much simpler since there is only a single row
  88001. ** of output.
  88002. */
  88003. resetAccumulator(pParse, &sAggInfo);
  88004. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
  88005. if( pWInfo==0 ){
  88006. sqlite3ExprListDelete(db, pDel);
  88007. goto select_end;
  88008. }
  88009. updateAccumulator(pParse, &sAggInfo);
  88010. if( !pMinMax && flag ){
  88011. sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
  88012. VdbeComment((v, "%s() by index",
  88013. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  88014. }
  88015. sqlite3WhereEnd(pWInfo);
  88016. finalizeAggFunctions(pParse, &sAggInfo);
  88017. }
  88018. pOrderBy = 0;
  88019. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  88020. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
  88021. pDest, addrEnd, addrEnd);
  88022. sqlite3ExprListDelete(db, pDel);
  88023. }
  88024. sqlite3VdbeResolveLabel(v, addrEnd);
  88025. } /* endif aggregate query */
  88026. if( distinct>=0 ){
  88027. explainTempTable(pParse, "DISTINCT");
  88028. }
  88029. /* If there is an ORDER BY clause, then we need to sort the results
  88030. ** and send them to the callback one by one.
  88031. */
  88032. if( pOrderBy ){
  88033. explainTempTable(pParse, "ORDER BY");
  88034. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  88035. }
  88036. /* Jump here to skip this query
  88037. */
  88038. sqlite3VdbeResolveLabel(v, iEnd);
  88039. /* The SELECT was successfully coded. Set the return code to 0
  88040. ** to indicate no errors.
  88041. */
  88042. rc = 0;
  88043. /* Control jumps to here if an error is encountered above, or upon
  88044. ** successful coding of the SELECT.
  88045. */
  88046. select_end:
  88047. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  88048. /* Identify column names if results of the SELECT are to be output.
  88049. */
  88050. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  88051. generateColumnNames(pParse, pTabList, pEList);
  88052. }
  88053. sqlite3DbFree(db, sAggInfo.aCol);
  88054. sqlite3DbFree(db, sAggInfo.aFunc);
  88055. return rc;
  88056. }
  88057. #if defined(SQLITE_DEBUG)
  88058. /*
  88059. *******************************************************************************
  88060. ** The following code is used for testing and debugging only. The code
  88061. ** that follows does not appear in normal builds.
  88062. **
  88063. ** These routines are used to print out the content of all or part of a
  88064. ** parse structures such as Select or Expr. Such printouts are useful
  88065. ** for helping to understand what is happening inside the code generator
  88066. ** during the execution of complex SELECT statements.
  88067. **
  88068. ** These routine are not called anywhere from within the normal
  88069. ** code base. Then are intended to be called from within the debugger
  88070. ** or from temporary "printf" statements inserted for debugging.
  88071. */
  88072. SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
  88073. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  88074. sqlite3DebugPrintf("(%s", p->u.zToken);
  88075. }else{
  88076. sqlite3DebugPrintf("(%d", p->op);
  88077. }
  88078. if( p->pLeft ){
  88079. sqlite3DebugPrintf(" ");
  88080. sqlite3PrintExpr(p->pLeft);
  88081. }
  88082. if( p->pRight ){
  88083. sqlite3DebugPrintf(" ");
  88084. sqlite3PrintExpr(p->pRight);
  88085. }
  88086. sqlite3DebugPrintf(")");
  88087. }
  88088. SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
  88089. int i;
  88090. for(i=0; i<pList->nExpr; i++){
  88091. sqlite3PrintExpr(pList->a[i].pExpr);
  88092. if( i<pList->nExpr-1 ){
  88093. sqlite3DebugPrintf(", ");
  88094. }
  88095. }
  88096. }
  88097. SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
  88098. sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  88099. sqlite3PrintExprList(p->pEList);
  88100. sqlite3DebugPrintf("\n");
  88101. if( p->pSrc ){
  88102. char *zPrefix;
  88103. int i;
  88104. zPrefix = "FROM";
  88105. for(i=0; i<p->pSrc->nSrc; i++){
  88106. struct SrcList_item *pItem = &p->pSrc->a[i];
  88107. sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
  88108. zPrefix = "";
  88109. if( pItem->pSelect ){
  88110. sqlite3DebugPrintf("(\n");
  88111. sqlite3PrintSelect(pItem->pSelect, indent+10);
  88112. sqlite3DebugPrintf("%*s)", indent+8, "");
  88113. }else if( pItem->zName ){
  88114. sqlite3DebugPrintf("%s", pItem->zName);
  88115. }
  88116. if( pItem->pTab ){
  88117. sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
  88118. }
  88119. if( pItem->zAlias ){
  88120. sqlite3DebugPrintf(" AS %s", pItem->zAlias);
  88121. }
  88122. if( i<p->pSrc->nSrc-1 ){
  88123. sqlite3DebugPrintf(",");
  88124. }
  88125. sqlite3DebugPrintf("\n");
  88126. }
  88127. }
  88128. if( p->pWhere ){
  88129. sqlite3DebugPrintf("%*s WHERE ", indent, "");
  88130. sqlite3PrintExpr(p->pWhere);
  88131. sqlite3DebugPrintf("\n");
  88132. }
  88133. if( p->pGroupBy ){
  88134. sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
  88135. sqlite3PrintExprList(p->pGroupBy);
  88136. sqlite3DebugPrintf("\n");
  88137. }
  88138. if( p->pHaving ){
  88139. sqlite3DebugPrintf("%*s HAVING ", indent, "");
  88140. sqlite3PrintExpr(p->pHaving);
  88141. sqlite3DebugPrintf("\n");
  88142. }
  88143. if( p->pOrderBy ){
  88144. sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
  88145. sqlite3PrintExprList(p->pOrderBy);
  88146. sqlite3DebugPrintf("\n");
  88147. }
  88148. }
  88149. /* End of the structure debug printing code
  88150. *****************************************************************************/
  88151. #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  88152. /************** End of select.c **********************************************/
  88153. /************** Begin file table.c *******************************************/
  88154. /*
  88155. ** 2001 September 15
  88156. **
  88157. ** The author disclaims copyright to this source code. In place of
  88158. ** a legal notice, here is a blessing:
  88159. **
  88160. ** May you do good and not evil.
  88161. ** May you find forgiveness for yourself and forgive others.
  88162. ** May you share freely, never taking more than you give.
  88163. **
  88164. *************************************************************************
  88165. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  88166. ** interface routines. These are just wrappers around the main
  88167. ** interface routine of sqlite3_exec().
  88168. **
  88169. ** These routines are in a separate files so that they will not be linked
  88170. ** if they are not used.
  88171. */
  88172. #ifndef SQLITE_OMIT_GET_TABLE
  88173. /*
  88174. ** This structure is used to pass data from sqlite3_get_table() through
  88175. ** to the callback function is uses to build the result.
  88176. */
  88177. typedef struct TabResult {
  88178. char **azResult; /* Accumulated output */
  88179. char *zErrMsg; /* Error message text, if an error occurs */
  88180. int nAlloc; /* Slots allocated for azResult[] */
  88181. int nRow; /* Number of rows in the result */
  88182. int nColumn; /* Number of columns in the result */
  88183. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  88184. int rc; /* Return code from sqlite3_exec() */
  88185. } TabResult;
  88186. /*
  88187. ** This routine is called once for each row in the result table. Its job
  88188. ** is to fill in the TabResult structure appropriately, allocating new
  88189. ** memory as necessary.
  88190. */
  88191. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  88192. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  88193. int need; /* Slots needed in p->azResult[] */
  88194. int i; /* Loop counter */
  88195. char *z; /* A single column of result */
  88196. /* Make sure there is enough space in p->azResult to hold everything
  88197. ** we need to remember from this invocation of the callback.
  88198. */
  88199. if( p->nRow==0 && argv!=0 ){
  88200. need = nCol*2;
  88201. }else{
  88202. need = nCol;
  88203. }
  88204. if( p->nData + need > p->nAlloc ){
  88205. char **azNew;
  88206. p->nAlloc = p->nAlloc*2 + need;
  88207. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  88208. if( azNew==0 ) goto malloc_failed;
  88209. p->azResult = azNew;
  88210. }
  88211. /* If this is the first row, then generate an extra row containing
  88212. ** the names of all columns.
  88213. */
  88214. if( p->nRow==0 ){
  88215. p->nColumn = nCol;
  88216. for(i=0; i<nCol; i++){
  88217. z = sqlite3_mprintf("%s", colv[i]);
  88218. if( z==0 ) goto malloc_failed;
  88219. p->azResult[p->nData++] = z;
  88220. }
  88221. }else if( p->nColumn!=nCol ){
  88222. sqlite3_free(p->zErrMsg);
  88223. p->zErrMsg = sqlite3_mprintf(
  88224. "sqlite3_get_table() called with two or more incompatible queries"
  88225. );
  88226. p->rc = SQLITE_ERROR;
  88227. return 1;
  88228. }
  88229. /* Copy over the row data
  88230. */
  88231. if( argv!=0 ){
  88232. for(i=0; i<nCol; i++){
  88233. if( argv[i]==0 ){
  88234. z = 0;
  88235. }else{
  88236. int n = sqlite3Strlen30(argv[i])+1;
  88237. z = sqlite3_malloc( n );
  88238. if( z==0 ) goto malloc_failed;
  88239. memcpy(z, argv[i], n);
  88240. }
  88241. p->azResult[p->nData++] = z;
  88242. }
  88243. p->nRow++;
  88244. }
  88245. return 0;
  88246. malloc_failed:
  88247. p->rc = SQLITE_NOMEM;
  88248. return 1;
  88249. }
  88250. /*
  88251. ** Query the database. But instead of invoking a callback for each row,
  88252. ** malloc() for space to hold the result and return the entire results
  88253. ** at the conclusion of the call.
  88254. **
  88255. ** The result that is written to ***pazResult is held in memory obtained
  88256. ** from malloc(). But the caller cannot free this memory directly.
  88257. ** Instead, the entire table should be passed to sqlite3_free_table() when
  88258. ** the calling procedure is finished using it.
  88259. */
  88260. SQLITE_API int sqlite3_get_table(
  88261. sqlite3 *db, /* The database on which the SQL executes */
  88262. const char *zSql, /* The SQL to be executed */
  88263. char ***pazResult, /* Write the result table here */
  88264. int *pnRow, /* Write the number of rows in the result here */
  88265. int *pnColumn, /* Write the number of columns of result here */
  88266. char **pzErrMsg /* Write error messages here */
  88267. ){
  88268. int rc;
  88269. TabResult res;
  88270. *pazResult = 0;
  88271. if( pnColumn ) *pnColumn = 0;
  88272. if( pnRow ) *pnRow = 0;
  88273. if( pzErrMsg ) *pzErrMsg = 0;
  88274. res.zErrMsg = 0;
  88275. res.nRow = 0;
  88276. res.nColumn = 0;
  88277. res.nData = 1;
  88278. res.nAlloc = 20;
  88279. res.rc = SQLITE_OK;
  88280. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  88281. if( res.azResult==0 ){
  88282. db->errCode = SQLITE_NOMEM;
  88283. return SQLITE_NOMEM;
  88284. }
  88285. res.azResult[0] = 0;
  88286. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  88287. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  88288. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  88289. if( (rc&0xff)==SQLITE_ABORT ){
  88290. sqlite3_free_table(&res.azResult[1]);
  88291. if( res.zErrMsg ){
  88292. if( pzErrMsg ){
  88293. sqlite3_free(*pzErrMsg);
  88294. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  88295. }
  88296. sqlite3_free(res.zErrMsg);
  88297. }
  88298. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  88299. return res.rc;
  88300. }
  88301. sqlite3_free(res.zErrMsg);
  88302. if( rc!=SQLITE_OK ){
  88303. sqlite3_free_table(&res.azResult[1]);
  88304. return rc;
  88305. }
  88306. if( res.nAlloc>res.nData ){
  88307. char **azNew;
  88308. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  88309. if( azNew==0 ){
  88310. sqlite3_free_table(&res.azResult[1]);
  88311. db->errCode = SQLITE_NOMEM;
  88312. return SQLITE_NOMEM;
  88313. }
  88314. res.azResult = azNew;
  88315. }
  88316. *pazResult = &res.azResult[1];
  88317. if( pnColumn ) *pnColumn = res.nColumn;
  88318. if( pnRow ) *pnRow = res.nRow;
  88319. return rc;
  88320. }
  88321. /*
  88322. ** This routine frees the space the sqlite3_get_table() malloced.
  88323. */
  88324. SQLITE_API void sqlite3_free_table(
  88325. char **azResult /* Result returned from from sqlite3_get_table() */
  88326. ){
  88327. if( azResult ){
  88328. int i, n;
  88329. azResult--;
  88330. assert( azResult!=0 );
  88331. n = SQLITE_PTR_TO_INT(azResult[0]);
  88332. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  88333. sqlite3_free(azResult);
  88334. }
  88335. }
  88336. #endif /* SQLITE_OMIT_GET_TABLE */
  88337. /************** End of table.c ***********************************************/
  88338. /************** Begin file trigger.c *****************************************/
  88339. /*
  88340. **
  88341. ** The author disclaims copyright to this source code. In place of
  88342. ** a legal notice, here is a blessing:
  88343. **
  88344. ** May you do good and not evil.
  88345. ** May you find forgiveness for yourself and forgive others.
  88346. ** May you share freely, never taking more than you give.
  88347. **
  88348. *************************************************************************
  88349. ** This file contains the implementation for TRIGGERs
  88350. */
  88351. #ifndef SQLITE_OMIT_TRIGGER
  88352. /*
  88353. ** Delete a linked list of TriggerStep structures.
  88354. */
  88355. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  88356. while( pTriggerStep ){
  88357. TriggerStep * pTmp = pTriggerStep;
  88358. pTriggerStep = pTriggerStep->pNext;
  88359. sqlite3ExprDelete(db, pTmp->pWhere);
  88360. sqlite3ExprListDelete(db, pTmp->pExprList);
  88361. sqlite3SelectDelete(db, pTmp->pSelect);
  88362. sqlite3IdListDelete(db, pTmp->pIdList);
  88363. sqlite3DbFree(db, pTmp);
  88364. }
  88365. }
  88366. /*
  88367. ** Given table pTab, return a list of all the triggers attached to
  88368. ** the table. The list is connected by Trigger.pNext pointers.
  88369. **
  88370. ** All of the triggers on pTab that are in the same database as pTab
  88371. ** are already attached to pTab->pTrigger. But there might be additional
  88372. ** triggers on pTab in the TEMP schema. This routine prepends all
  88373. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  88374. ** and returns the combined list.
  88375. **
  88376. ** To state it another way: This routine returns a list of all triggers
  88377. ** that fire off of pTab. The list will include any TEMP triggers on
  88378. ** pTab as well as the triggers lised in pTab->pTrigger.
  88379. */
  88380. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  88381. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  88382. Trigger *pList = 0; /* List of triggers to return */
  88383. if( pParse->disableTriggers ){
  88384. return 0;
  88385. }
  88386. if( pTmpSchema!=pTab->pSchema ){
  88387. HashElem *p;
  88388. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  88389. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  88390. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  88391. if( pTrig->pTabSchema==pTab->pSchema
  88392. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  88393. ){
  88394. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  88395. pList = pTrig;
  88396. }
  88397. }
  88398. }
  88399. return (pList ? pList : pTab->pTrigger);
  88400. }
  88401. /*
  88402. ** This is called by the parser when it sees a CREATE TRIGGER statement
  88403. ** up to the point of the BEGIN before the trigger actions. A Trigger
  88404. ** structure is generated based on the information available and stored
  88405. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  88406. ** sqlite3FinishTrigger() function is called to complete the trigger
  88407. ** construction process.
  88408. */
  88409. SQLITE_PRIVATE void sqlite3BeginTrigger(
  88410. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  88411. Token *pName1, /* The name of the trigger */
  88412. Token *pName2, /* The name of the trigger */
  88413. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  88414. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  88415. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  88416. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  88417. Expr *pWhen, /* WHEN clause */
  88418. int isTemp, /* True if the TEMPORARY keyword is present */
  88419. int noErr /* Suppress errors if the trigger already exists */
  88420. ){
  88421. Trigger *pTrigger = 0; /* The new trigger */
  88422. Table *pTab; /* Table that the trigger fires off of */
  88423. char *zName = 0; /* Name of the trigger */
  88424. sqlite3 *db = pParse->db; /* The database connection */
  88425. int iDb; /* The database to store the trigger in */
  88426. Token *pName; /* The unqualified db name */
  88427. DbFixer sFix; /* State vector for the DB fixer */
  88428. int iTabDb; /* Index of the database holding pTab */
  88429. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  88430. assert( pName2!=0 );
  88431. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  88432. assert( op>0 && op<0xff );
  88433. if( isTemp ){
  88434. /* If TEMP was specified, then the trigger name may not be qualified. */
  88435. if( pName2->n>0 ){
  88436. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  88437. goto trigger_cleanup;
  88438. }
  88439. iDb = 1;
  88440. pName = pName1;
  88441. }else{
  88442. /* Figure out the db that the the trigger will be created in */
  88443. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  88444. if( iDb<0 ){
  88445. goto trigger_cleanup;
  88446. }
  88447. }
  88448. /* If the trigger name was unqualified, and the table is a temp table,
  88449. ** then set iDb to 1 to create the trigger in the temporary database.
  88450. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  88451. ** exist, the error is caught by the block below.
  88452. */
  88453. if( !pTableName || db->mallocFailed ){
  88454. goto trigger_cleanup;
  88455. }
  88456. pTab = sqlite3SrcListLookup(pParse, pTableName);
  88457. if( db->init.busy==0 && pName2->n==0 && pTab
  88458. && pTab->pSchema==db->aDb[1].pSchema ){
  88459. iDb = 1;
  88460. }
  88461. /* Ensure the table name matches database name and that the table exists */
  88462. if( db->mallocFailed ) goto trigger_cleanup;
  88463. assert( pTableName->nSrc==1 );
  88464. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
  88465. sqlite3FixSrcList(&sFix, pTableName) ){
  88466. goto trigger_cleanup;
  88467. }
  88468. pTab = sqlite3SrcListLookup(pParse, pTableName);
  88469. if( !pTab ){
  88470. /* The table does not exist. */
  88471. if( db->init.iDb==1 ){
  88472. /* Ticket #3810.
  88473. ** Normally, whenever a table is dropped, all associated triggers are
  88474. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  88475. ** and the table is dropped by a different database connection, the
  88476. ** trigger is not visible to the database connection that does the
  88477. ** drop so the trigger cannot be dropped. This results in an
  88478. ** "orphaned trigger" - a trigger whose associated table is missing.
  88479. */
  88480. db->init.orphanTrigger = 1;
  88481. }
  88482. goto trigger_cleanup;
  88483. }
  88484. if( IsVirtual(pTab) ){
  88485. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  88486. goto trigger_cleanup;
  88487. }
  88488. /* Check that the trigger name is not reserved and that no trigger of the
  88489. ** specified name exists */
  88490. zName = sqlite3NameFromToken(db, pName);
  88491. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  88492. goto trigger_cleanup;
  88493. }
  88494. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88495. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  88496. zName, sqlite3Strlen30(zName)) ){
  88497. if( !noErr ){
  88498. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  88499. }else{
  88500. assert( !db->init.busy );
  88501. sqlite3CodeVerifySchema(pParse, iDb);
  88502. }
  88503. goto trigger_cleanup;
  88504. }
  88505. /* Do not create a trigger on a system table */
  88506. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  88507. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  88508. pParse->nErr++;
  88509. goto trigger_cleanup;
  88510. }
  88511. /* INSTEAD of triggers are only for views and views only support INSTEAD
  88512. ** of triggers.
  88513. */
  88514. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  88515. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  88516. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  88517. goto trigger_cleanup;
  88518. }
  88519. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  88520. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  88521. " trigger on table: %S", pTableName, 0);
  88522. goto trigger_cleanup;
  88523. }
  88524. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  88525. #ifndef SQLITE_OMIT_AUTHORIZATION
  88526. {
  88527. int code = SQLITE_CREATE_TRIGGER;
  88528. const char *zDb = db->aDb[iTabDb].zName;
  88529. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  88530. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  88531. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  88532. goto trigger_cleanup;
  88533. }
  88534. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  88535. goto trigger_cleanup;
  88536. }
  88537. }
  88538. #endif
  88539. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  88540. ** cannot appear on views. So we might as well translate every
  88541. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  88542. ** elsewhere.
  88543. */
  88544. if (tr_tm == TK_INSTEAD){
  88545. tr_tm = TK_BEFORE;
  88546. }
  88547. /* Build the Trigger object */
  88548. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  88549. if( pTrigger==0 ) goto trigger_cleanup;
  88550. pTrigger->zName = zName;
  88551. zName = 0;
  88552. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  88553. pTrigger->pSchema = db->aDb[iDb].pSchema;
  88554. pTrigger->pTabSchema = pTab->pSchema;
  88555. pTrigger->op = (u8)op;
  88556. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  88557. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  88558. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  88559. assert( pParse->pNewTrigger==0 );
  88560. pParse->pNewTrigger = pTrigger;
  88561. trigger_cleanup:
  88562. sqlite3DbFree(db, zName);
  88563. sqlite3SrcListDelete(db, pTableName);
  88564. sqlite3IdListDelete(db, pColumns);
  88565. sqlite3ExprDelete(db, pWhen);
  88566. if( !pParse->pNewTrigger ){
  88567. sqlite3DeleteTrigger(db, pTrigger);
  88568. }else{
  88569. assert( pParse->pNewTrigger==pTrigger );
  88570. }
  88571. }
  88572. /*
  88573. ** This routine is called after all of the trigger actions have been parsed
  88574. ** in order to complete the process of building the trigger.
  88575. */
  88576. SQLITE_PRIVATE void sqlite3FinishTrigger(
  88577. Parse *pParse, /* Parser context */
  88578. TriggerStep *pStepList, /* The triggered program */
  88579. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  88580. ){
  88581. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  88582. char *zName; /* Name of trigger */
  88583. sqlite3 *db = pParse->db; /* The database */
  88584. DbFixer sFix; /* Fixer object */
  88585. int iDb; /* Database containing the trigger */
  88586. Token nameToken; /* Trigger name for error reporting */
  88587. pParse->pNewTrigger = 0;
  88588. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  88589. zName = pTrig->zName;
  88590. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  88591. pTrig->step_list = pStepList;
  88592. while( pStepList ){
  88593. pStepList->pTrig = pTrig;
  88594. pStepList = pStepList->pNext;
  88595. }
  88596. nameToken.z = pTrig->zName;
  88597. nameToken.n = sqlite3Strlen30(nameToken.z);
  88598. if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
  88599. && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
  88600. goto triggerfinish_cleanup;
  88601. }
  88602. /* if we are not initializing,
  88603. ** build the sqlite_master entry
  88604. */
  88605. if( !db->init.busy ){
  88606. Vdbe *v;
  88607. char *z;
  88608. /* Make an entry in the sqlite_master table */
  88609. v = sqlite3GetVdbe(pParse);
  88610. if( v==0 ) goto triggerfinish_cleanup;
  88611. sqlite3BeginWriteOperation(pParse, 0, iDb);
  88612. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  88613. sqlite3NestedParse(pParse,
  88614. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  88615. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  88616. pTrig->table, z);
  88617. sqlite3DbFree(db, z);
  88618. sqlite3ChangeCookie(pParse, iDb);
  88619. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
  88620. db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
  88621. );
  88622. }
  88623. if( db->init.busy ){
  88624. Trigger *pLink = pTrig;
  88625. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  88626. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88627. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  88628. if( pTrig ){
  88629. db->mallocFailed = 1;
  88630. }else if( pLink->pSchema==pLink->pTabSchema ){
  88631. Table *pTab;
  88632. int n = sqlite3Strlen30(pLink->table);
  88633. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  88634. assert( pTab!=0 );
  88635. pLink->pNext = pTab->pTrigger;
  88636. pTab->pTrigger = pLink;
  88637. }
  88638. }
  88639. triggerfinish_cleanup:
  88640. sqlite3DeleteTrigger(db, pTrig);
  88641. assert( !pParse->pNewTrigger );
  88642. sqlite3DeleteTriggerStep(db, pStepList);
  88643. }
  88644. /*
  88645. ** Turn a SELECT statement (that the pSelect parameter points to) into
  88646. ** a trigger step. Return a pointer to a TriggerStep structure.
  88647. **
  88648. ** The parser calls this routine when it finds a SELECT statement in
  88649. ** body of a TRIGGER.
  88650. */
  88651. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  88652. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  88653. if( pTriggerStep==0 ) {
  88654. sqlite3SelectDelete(db, pSelect);
  88655. return 0;
  88656. }
  88657. pTriggerStep->op = TK_SELECT;
  88658. pTriggerStep->pSelect = pSelect;
  88659. pTriggerStep->orconf = OE_Default;
  88660. return pTriggerStep;
  88661. }
  88662. /*
  88663. ** Allocate space to hold a new trigger step. The allocated space
  88664. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  88665. **
  88666. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  88667. */
  88668. static TriggerStep *triggerStepAllocate(
  88669. sqlite3 *db, /* Database connection */
  88670. u8 op, /* Trigger opcode */
  88671. Token *pName /* The target name */
  88672. ){
  88673. TriggerStep *pTriggerStep;
  88674. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  88675. if( pTriggerStep ){
  88676. char *z = (char*)&pTriggerStep[1];
  88677. memcpy(z, pName->z, pName->n);
  88678. pTriggerStep->target.z = z;
  88679. pTriggerStep->target.n = pName->n;
  88680. pTriggerStep->op = op;
  88681. }
  88682. return pTriggerStep;
  88683. }
  88684. /*
  88685. ** Build a trigger step out of an INSERT statement. Return a pointer
  88686. ** to the new trigger step.
  88687. **
  88688. ** The parser calls this routine when it sees an INSERT inside the
  88689. ** body of a trigger.
  88690. */
  88691. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  88692. sqlite3 *db, /* The database connection */
  88693. Token *pTableName, /* Name of the table into which we insert */
  88694. IdList *pColumn, /* List of columns in pTableName to insert into */
  88695. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  88696. Select *pSelect, /* A SELECT statement that supplies values */
  88697. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  88698. ){
  88699. TriggerStep *pTriggerStep;
  88700. assert(pEList == 0 || pSelect == 0);
  88701. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  88702. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  88703. if( pTriggerStep ){
  88704. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  88705. pTriggerStep->pIdList = pColumn;
  88706. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  88707. pTriggerStep->orconf = orconf;
  88708. }else{
  88709. sqlite3IdListDelete(db, pColumn);
  88710. }
  88711. sqlite3ExprListDelete(db, pEList);
  88712. sqlite3SelectDelete(db, pSelect);
  88713. return pTriggerStep;
  88714. }
  88715. /*
  88716. ** Construct a trigger step that implements an UPDATE statement and return
  88717. ** a pointer to that trigger step. The parser calls this routine when it
  88718. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  88719. */
  88720. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  88721. sqlite3 *db, /* The database connection */
  88722. Token *pTableName, /* Name of the table to be updated */
  88723. ExprList *pEList, /* The SET clause: list of column and new values */
  88724. Expr *pWhere, /* The WHERE clause */
  88725. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  88726. ){
  88727. TriggerStep *pTriggerStep;
  88728. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  88729. if( pTriggerStep ){
  88730. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  88731. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  88732. pTriggerStep->orconf = orconf;
  88733. }
  88734. sqlite3ExprListDelete(db, pEList);
  88735. sqlite3ExprDelete(db, pWhere);
  88736. return pTriggerStep;
  88737. }
  88738. /*
  88739. ** Construct a trigger step that implements a DELETE statement and return
  88740. ** a pointer to that trigger step. The parser calls this routine when it
  88741. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  88742. */
  88743. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  88744. sqlite3 *db, /* Database connection */
  88745. Token *pTableName, /* The table from which rows are deleted */
  88746. Expr *pWhere /* The WHERE clause */
  88747. ){
  88748. TriggerStep *pTriggerStep;
  88749. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  88750. if( pTriggerStep ){
  88751. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  88752. pTriggerStep->orconf = OE_Default;
  88753. }
  88754. sqlite3ExprDelete(db, pWhere);
  88755. return pTriggerStep;
  88756. }
  88757. /*
  88758. ** Recursively delete a Trigger structure
  88759. */
  88760. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  88761. if( pTrigger==0 ) return;
  88762. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  88763. sqlite3DbFree(db, pTrigger->zName);
  88764. sqlite3DbFree(db, pTrigger->table);
  88765. sqlite3ExprDelete(db, pTrigger->pWhen);
  88766. sqlite3IdListDelete(db, pTrigger->pColumns);
  88767. sqlite3DbFree(db, pTrigger);
  88768. }
  88769. /*
  88770. ** This function is called to drop a trigger from the database schema.
  88771. **
  88772. ** This may be called directly from the parser and therefore identifies
  88773. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  88774. ** same job as this routine except it takes a pointer to the trigger
  88775. ** instead of the trigger name.
  88776. **/
  88777. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  88778. Trigger *pTrigger = 0;
  88779. int i;
  88780. const char *zDb;
  88781. const char *zName;
  88782. int nName;
  88783. sqlite3 *db = pParse->db;
  88784. if( db->mallocFailed ) goto drop_trigger_cleanup;
  88785. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  88786. goto drop_trigger_cleanup;
  88787. }
  88788. assert( pName->nSrc==1 );
  88789. zDb = pName->a[0].zDatabase;
  88790. zName = pName->a[0].zName;
  88791. nName = sqlite3Strlen30(zName);
  88792. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  88793. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  88794. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  88795. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  88796. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  88797. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  88798. if( pTrigger ) break;
  88799. }
  88800. if( !pTrigger ){
  88801. if( !noErr ){
  88802. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  88803. }else{
  88804. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  88805. }
  88806. pParse->checkSchema = 1;
  88807. goto drop_trigger_cleanup;
  88808. }
  88809. sqlite3DropTriggerPtr(pParse, pTrigger);
  88810. drop_trigger_cleanup:
  88811. sqlite3SrcListDelete(db, pName);
  88812. }
  88813. /*
  88814. ** Return a pointer to the Table structure for the table that a trigger
  88815. ** is set on.
  88816. */
  88817. static Table *tableOfTrigger(Trigger *pTrigger){
  88818. int n = sqlite3Strlen30(pTrigger->table);
  88819. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  88820. }
  88821. /*
  88822. ** Drop a trigger given a pointer to that trigger.
  88823. */
  88824. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  88825. Table *pTable;
  88826. Vdbe *v;
  88827. sqlite3 *db = pParse->db;
  88828. int iDb;
  88829. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  88830. assert( iDb>=0 && iDb<db->nDb );
  88831. pTable = tableOfTrigger(pTrigger);
  88832. assert( pTable );
  88833. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  88834. #ifndef SQLITE_OMIT_AUTHORIZATION
  88835. {
  88836. int code = SQLITE_DROP_TRIGGER;
  88837. const char *zDb = db->aDb[iDb].zName;
  88838. const char *zTab = SCHEMA_TABLE(iDb);
  88839. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  88840. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  88841. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  88842. return;
  88843. }
  88844. }
  88845. #endif
  88846. /* Generate code to destroy the database record of the trigger.
  88847. */
  88848. assert( pTable!=0 );
  88849. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  88850. int base;
  88851. static const VdbeOpList dropTrigger[] = {
  88852. { OP_Rewind, 0, ADDR(9), 0},
  88853. { OP_String8, 0, 1, 0}, /* 1 */
  88854. { OP_Column, 0, 1, 2},
  88855. { OP_Ne, 2, ADDR(8), 1},
  88856. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  88857. { OP_Column, 0, 0, 2},
  88858. { OP_Ne, 2, ADDR(8), 1},
  88859. { OP_Delete, 0, 0, 0},
  88860. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  88861. };
  88862. sqlite3BeginWriteOperation(pParse, 0, iDb);
  88863. sqlite3OpenMasterTable(pParse, iDb);
  88864. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  88865. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  88866. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  88867. sqlite3ChangeCookie(pParse, iDb);
  88868. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  88869. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  88870. if( pParse->nMem<3 ){
  88871. pParse->nMem = 3;
  88872. }
  88873. }
  88874. }
  88875. /*
  88876. ** Remove a trigger from the hash tables of the sqlite* pointer.
  88877. */
  88878. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  88879. Trigger *pTrigger;
  88880. Hash *pHash;
  88881. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88882. pHash = &(db->aDb[iDb].pSchema->trigHash);
  88883. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  88884. if( ALWAYS(pTrigger) ){
  88885. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  88886. Table *pTab = tableOfTrigger(pTrigger);
  88887. Trigger **pp;
  88888. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  88889. *pp = (*pp)->pNext;
  88890. }
  88891. sqlite3DeleteTrigger(db, pTrigger);
  88892. db->flags |= SQLITE_InternChanges;
  88893. }
  88894. }
  88895. /*
  88896. ** pEList is the SET clause of an UPDATE statement. Each entry
  88897. ** in pEList is of the format <id>=<expr>. If any of the entries
  88898. ** in pEList have an <id> which matches an identifier in pIdList,
  88899. ** then return TRUE. If pIdList==NULL, then it is considered a
  88900. ** wildcard that matches anything. Likewise if pEList==NULL then
  88901. ** it matches anything so always return true. Return false only
  88902. ** if there is no match.
  88903. */
  88904. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  88905. int e;
  88906. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  88907. for(e=0; e<pEList->nExpr; e++){
  88908. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  88909. }
  88910. return 0;
  88911. }
  88912. /*
  88913. ** Return a list of all triggers on table pTab if there exists at least
  88914. ** one trigger that must be fired when an operation of type 'op' is
  88915. ** performed on the table, and, if that operation is an UPDATE, if at
  88916. ** least one of the columns in pChanges is being modified.
  88917. */
  88918. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  88919. Parse *pParse, /* Parse context */
  88920. Table *pTab, /* The table the contains the triggers */
  88921. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  88922. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  88923. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  88924. ){
  88925. int mask = 0;
  88926. Trigger *pList = 0;
  88927. Trigger *p;
  88928. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  88929. pList = sqlite3TriggerList(pParse, pTab);
  88930. }
  88931. assert( pList==0 || IsVirtual(pTab)==0 );
  88932. for(p=pList; p; p=p->pNext){
  88933. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  88934. mask |= p->tr_tm;
  88935. }
  88936. }
  88937. if( pMask ){
  88938. *pMask = mask;
  88939. }
  88940. return (mask ? pList : 0);
  88941. }
  88942. /*
  88943. ** Convert the pStep->target token into a SrcList and return a pointer
  88944. ** to that SrcList.
  88945. **
  88946. ** This routine adds a specific database name, if needed, to the target when
  88947. ** forming the SrcList. This prevents a trigger in one database from
  88948. ** referring to a target in another database. An exception is when the
  88949. ** trigger is in TEMP in which case it can refer to any other database it
  88950. ** wants.
  88951. */
  88952. static SrcList *targetSrcList(
  88953. Parse *pParse, /* The parsing context */
  88954. TriggerStep *pStep /* The trigger containing the target token */
  88955. ){
  88956. int iDb; /* Index of the database to use */
  88957. SrcList *pSrc; /* SrcList to be returned */
  88958. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  88959. if( pSrc ){
  88960. assert( pSrc->nSrc>0 );
  88961. assert( pSrc->a!=0 );
  88962. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  88963. if( iDb==0 || iDb>=2 ){
  88964. sqlite3 *db = pParse->db;
  88965. assert( iDb<pParse->db->nDb );
  88966. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  88967. }
  88968. }
  88969. return pSrc;
  88970. }
  88971. /*
  88972. ** Generate VDBE code for the statements inside the body of a single
  88973. ** trigger.
  88974. */
  88975. static int codeTriggerProgram(
  88976. Parse *pParse, /* The parser context */
  88977. TriggerStep *pStepList, /* List of statements inside the trigger body */
  88978. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  88979. ){
  88980. TriggerStep *pStep;
  88981. Vdbe *v = pParse->pVdbe;
  88982. sqlite3 *db = pParse->db;
  88983. assert( pParse->pTriggerTab && pParse->pToplevel );
  88984. assert( pStepList );
  88985. assert( v!=0 );
  88986. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  88987. /* Figure out the ON CONFLICT policy that will be used for this step
  88988. ** of the trigger program. If the statement that caused this trigger
  88989. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  88990. ** the ON CONFLICT policy that was specified as part of the trigger
  88991. ** step statement. Example:
  88992. **
  88993. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  88994. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  88995. ** END;
  88996. **
  88997. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  88998. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  88999. */
  89000. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  89001. switch( pStep->op ){
  89002. case TK_UPDATE: {
  89003. sqlite3Update(pParse,
  89004. targetSrcList(pParse, pStep),
  89005. sqlite3ExprListDup(db, pStep->pExprList, 0),
  89006. sqlite3ExprDup(db, pStep->pWhere, 0),
  89007. pParse->eOrconf
  89008. );
  89009. break;
  89010. }
  89011. case TK_INSERT: {
  89012. sqlite3Insert(pParse,
  89013. targetSrcList(pParse, pStep),
  89014. sqlite3ExprListDup(db, pStep->pExprList, 0),
  89015. sqlite3SelectDup(db, pStep->pSelect, 0),
  89016. sqlite3IdListDup(db, pStep->pIdList),
  89017. pParse->eOrconf
  89018. );
  89019. break;
  89020. }
  89021. case TK_DELETE: {
  89022. sqlite3DeleteFrom(pParse,
  89023. targetSrcList(pParse, pStep),
  89024. sqlite3ExprDup(db, pStep->pWhere, 0)
  89025. );
  89026. break;
  89027. }
  89028. default: assert( pStep->op==TK_SELECT ); {
  89029. SelectDest sDest;
  89030. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  89031. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  89032. sqlite3Select(pParse, pSelect, &sDest);
  89033. sqlite3SelectDelete(db, pSelect);
  89034. break;
  89035. }
  89036. }
  89037. if( pStep->op!=TK_SELECT ){
  89038. sqlite3VdbeAddOp0(v, OP_ResetCount);
  89039. }
  89040. }
  89041. return 0;
  89042. }
  89043. #ifdef SQLITE_DEBUG
  89044. /*
  89045. ** This function is used to add VdbeComment() annotations to a VDBE
  89046. ** program. It is not used in production code, only for debugging.
  89047. */
  89048. static const char *onErrorText(int onError){
  89049. switch( onError ){
  89050. case OE_Abort: return "abort";
  89051. case OE_Rollback: return "rollback";
  89052. case OE_Fail: return "fail";
  89053. case OE_Replace: return "replace";
  89054. case OE_Ignore: return "ignore";
  89055. case OE_Default: return "default";
  89056. }
  89057. return "n/a";
  89058. }
  89059. #endif
  89060. /*
  89061. ** Parse context structure pFrom has just been used to create a sub-vdbe
  89062. ** (trigger program). If an error has occurred, transfer error information
  89063. ** from pFrom to pTo.
  89064. */
  89065. static void transferParseError(Parse *pTo, Parse *pFrom){
  89066. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  89067. assert( pTo->zErrMsg==0 || pTo->nErr );
  89068. if( pTo->nErr==0 ){
  89069. pTo->zErrMsg = pFrom->zErrMsg;
  89070. pTo->nErr = pFrom->nErr;
  89071. }else{
  89072. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  89073. }
  89074. }
  89075. /*
  89076. ** Create and populate a new TriggerPrg object with a sub-program
  89077. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  89078. */
  89079. static TriggerPrg *codeRowTrigger(
  89080. Parse *pParse, /* Current parse context */
  89081. Trigger *pTrigger, /* Trigger to code */
  89082. Table *pTab, /* The table pTrigger is attached to */
  89083. int orconf /* ON CONFLICT policy to code trigger program with */
  89084. ){
  89085. Parse *pTop = sqlite3ParseToplevel(pParse);
  89086. sqlite3 *db = pParse->db; /* Database handle */
  89087. TriggerPrg *pPrg; /* Value to return */
  89088. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  89089. Vdbe *v; /* Temporary VM */
  89090. NameContext sNC; /* Name context for sub-vdbe */
  89091. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  89092. Parse *pSubParse; /* Parse context for sub-vdbe */
  89093. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  89094. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  89095. assert( pTop->pVdbe );
  89096. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  89097. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  89098. ** list of the top-level Parse object sooner rather than later. */
  89099. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  89100. if( !pPrg ) return 0;
  89101. pPrg->pNext = pTop->pTriggerPrg;
  89102. pTop->pTriggerPrg = pPrg;
  89103. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  89104. if( !pProgram ) return 0;
  89105. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  89106. pPrg->pTrigger = pTrigger;
  89107. pPrg->orconf = orconf;
  89108. pPrg->aColmask[0] = 0xffffffff;
  89109. pPrg->aColmask[1] = 0xffffffff;
  89110. /* Allocate and populate a new Parse context to use for coding the
  89111. ** trigger sub-program. */
  89112. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  89113. if( !pSubParse ) return 0;
  89114. memset(&sNC, 0, sizeof(sNC));
  89115. sNC.pParse = pSubParse;
  89116. pSubParse->db = db;
  89117. pSubParse->pTriggerTab = pTab;
  89118. pSubParse->pToplevel = pTop;
  89119. pSubParse->zAuthContext = pTrigger->zName;
  89120. pSubParse->eTriggerOp = pTrigger->op;
  89121. pSubParse->nQueryLoop = pParse->nQueryLoop;
  89122. v = sqlite3GetVdbe(pSubParse);
  89123. if( v ){
  89124. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  89125. pTrigger->zName, onErrorText(orconf),
  89126. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  89127. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  89128. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  89129. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  89130. pTab->zName
  89131. ));
  89132. #ifndef SQLITE_OMIT_TRACE
  89133. sqlite3VdbeChangeP4(v, -1,
  89134. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  89135. );
  89136. #endif
  89137. /* If one was specified, code the WHEN clause. If it evaluates to false
  89138. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  89139. ** OP_Halt inserted at the end of the program. */
  89140. if( pTrigger->pWhen ){
  89141. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  89142. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  89143. && db->mallocFailed==0
  89144. ){
  89145. iEndTrigger = sqlite3VdbeMakeLabel(v);
  89146. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  89147. }
  89148. sqlite3ExprDelete(db, pWhen);
  89149. }
  89150. /* Code the trigger program into the sub-vdbe. */
  89151. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  89152. /* Insert an OP_Halt at the end of the sub-program. */
  89153. if( iEndTrigger ){
  89154. sqlite3VdbeResolveLabel(v, iEndTrigger);
  89155. }
  89156. sqlite3VdbeAddOp0(v, OP_Halt);
  89157. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  89158. transferParseError(pParse, pSubParse);
  89159. if( db->mallocFailed==0 ){
  89160. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  89161. }
  89162. pProgram->nMem = pSubParse->nMem;
  89163. pProgram->nCsr = pSubParse->nTab;
  89164. pProgram->token = (void *)pTrigger;
  89165. pPrg->aColmask[0] = pSubParse->oldmask;
  89166. pPrg->aColmask[1] = pSubParse->newmask;
  89167. sqlite3VdbeDelete(v);
  89168. }
  89169. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  89170. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  89171. sqlite3StackFree(db, pSubParse);
  89172. return pPrg;
  89173. }
  89174. /*
  89175. ** Return a pointer to a TriggerPrg object containing the sub-program for
  89176. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  89177. ** TriggerPrg object exists, a new object is allocated and populated before
  89178. ** being returned.
  89179. */
  89180. static TriggerPrg *getRowTrigger(
  89181. Parse *pParse, /* Current parse context */
  89182. Trigger *pTrigger, /* Trigger to code */
  89183. Table *pTab, /* The table trigger pTrigger is attached to */
  89184. int orconf /* ON CONFLICT algorithm. */
  89185. ){
  89186. Parse *pRoot = sqlite3ParseToplevel(pParse);
  89187. TriggerPrg *pPrg;
  89188. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  89189. /* It may be that this trigger has already been coded (or is in the
  89190. ** process of being coded). If this is the case, then an entry with
  89191. ** a matching TriggerPrg.pTrigger field will be present somewhere
  89192. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  89193. for(pPrg=pRoot->pTriggerPrg;
  89194. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  89195. pPrg=pPrg->pNext
  89196. );
  89197. /* If an existing TriggerPrg could not be located, create a new one. */
  89198. if( !pPrg ){
  89199. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  89200. }
  89201. return pPrg;
  89202. }
  89203. /*
  89204. ** Generate code for the trigger program associated with trigger p on
  89205. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  89206. ** function are the same as those described in the header function for
  89207. ** sqlite3CodeRowTrigger()
  89208. */
  89209. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  89210. Parse *pParse, /* Parse context */
  89211. Trigger *p, /* Trigger to code */
  89212. Table *pTab, /* The table to code triggers from */
  89213. int reg, /* Reg array containing OLD.* and NEW.* values */
  89214. int orconf, /* ON CONFLICT policy */
  89215. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  89216. ){
  89217. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  89218. TriggerPrg *pPrg;
  89219. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  89220. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  89221. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  89222. ** is a pointer to the sub-vdbe containing the trigger program. */
  89223. if( pPrg ){
  89224. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  89225. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  89226. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  89227. VdbeComment(
  89228. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  89229. /* Set the P5 operand of the OP_Program instruction to non-zero if
  89230. ** recursive invocation of this trigger program is disallowed. Recursive
  89231. ** invocation is disallowed if (a) the sub-program is really a trigger,
  89232. ** not a foreign key action, and (b) the flag to enable recursive triggers
  89233. ** is clear. */
  89234. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  89235. }
  89236. }
  89237. /*
  89238. ** This is called to code the required FOR EACH ROW triggers for an operation
  89239. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  89240. ** is given by the op paramater. The tr_tm parameter determines whether the
  89241. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  89242. ** parameter pChanges is passed the list of columns being modified.
  89243. **
  89244. ** If there are no triggers that fire at the specified time for the specified
  89245. ** operation on pTab, this function is a no-op.
  89246. **
  89247. ** The reg argument is the address of the first in an array of registers
  89248. ** that contain the values substituted for the new.* and old.* references
  89249. ** in the trigger program. If N is the number of columns in table pTab
  89250. ** (a copy of pTab->nCol), then registers are populated as follows:
  89251. **
  89252. ** Register Contains
  89253. ** ------------------------------------------------------
  89254. ** reg+0 OLD.rowid
  89255. ** reg+1 OLD.* value of left-most column of pTab
  89256. ** ... ...
  89257. ** reg+N OLD.* value of right-most column of pTab
  89258. ** reg+N+1 NEW.rowid
  89259. ** reg+N+2 OLD.* value of left-most column of pTab
  89260. ** ... ...
  89261. ** reg+N+N+1 NEW.* value of right-most column of pTab
  89262. **
  89263. ** For ON DELETE triggers, the registers containing the NEW.* values will
  89264. ** never be accessed by the trigger program, so they are not allocated or
  89265. ** populated by the caller (there is no data to populate them with anyway).
  89266. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  89267. ** are never accessed, and so are not allocated by the caller. So, for an
  89268. ** ON INSERT trigger, the value passed to this function as parameter reg
  89269. ** is not a readable register, although registers (reg+N) through
  89270. ** (reg+N+N+1) are.
  89271. **
  89272. ** Parameter orconf is the default conflict resolution algorithm for the
  89273. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  89274. ** is the instruction that control should jump to if a trigger program
  89275. ** raises an IGNORE exception.
  89276. */
  89277. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  89278. Parse *pParse, /* Parse context */
  89279. Trigger *pTrigger, /* List of triggers on table pTab */
  89280. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  89281. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  89282. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  89283. Table *pTab, /* The table to code triggers from */
  89284. int reg, /* The first in an array of registers (see above) */
  89285. int orconf, /* ON CONFLICT policy */
  89286. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  89287. ){
  89288. Trigger *p; /* Used to iterate through pTrigger list */
  89289. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  89290. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  89291. assert( (op==TK_UPDATE)==(pChanges!=0) );
  89292. for(p=pTrigger; p; p=p->pNext){
  89293. /* Sanity checking: The schema for the trigger and for the table are
  89294. ** always defined. The trigger must be in the same schema as the table
  89295. ** or else it must be a TEMP trigger. */
  89296. assert( p->pSchema!=0 );
  89297. assert( p->pTabSchema!=0 );
  89298. assert( p->pSchema==p->pTabSchema
  89299. || p->pSchema==pParse->db->aDb[1].pSchema );
  89300. /* Determine whether we should code this trigger */
  89301. if( p->op==op
  89302. && p->tr_tm==tr_tm
  89303. && checkColumnOverlap(p->pColumns, pChanges)
  89304. ){
  89305. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  89306. }
  89307. }
  89308. }
  89309. /*
  89310. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  89311. ** This function returns a 32-bit bitmask indicating which columns of the
  89312. ** old.* or new.* tables actually are used by triggers. This information
  89313. ** may be used by the caller, for example, to avoid having to load the entire
  89314. ** old.* record into memory when executing an UPDATE or DELETE command.
  89315. **
  89316. ** Bit 0 of the returned mask is set if the left-most column of the
  89317. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  89318. ** the second leftmost column value is required, and so on. If there
  89319. ** are more than 32 columns in the table, and at least one of the columns
  89320. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  89321. **
  89322. ** It is not possible to determine if the old.rowid or new.rowid column is
  89323. ** accessed by triggers. The caller must always assume that it is.
  89324. **
  89325. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  89326. ** applies to the old.* table. If 1, the new.* table.
  89327. **
  89328. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  89329. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  89330. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  89331. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  89332. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  89333. */
  89334. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  89335. Parse *pParse, /* Parse context */
  89336. Trigger *pTrigger, /* List of triggers on table pTab */
  89337. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  89338. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  89339. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  89340. Table *pTab, /* The table to code triggers from */
  89341. int orconf /* Default ON CONFLICT policy for trigger steps */
  89342. ){
  89343. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  89344. u32 mask = 0;
  89345. Trigger *p;
  89346. assert( isNew==1 || isNew==0 );
  89347. for(p=pTrigger; p; p=p->pNext){
  89348. if( p->op==op && (tr_tm&p->tr_tm)
  89349. && checkColumnOverlap(p->pColumns,pChanges)
  89350. ){
  89351. TriggerPrg *pPrg;
  89352. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  89353. if( pPrg ){
  89354. mask |= pPrg->aColmask[isNew];
  89355. }
  89356. }
  89357. }
  89358. return mask;
  89359. }
  89360. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  89361. /************** End of trigger.c *********************************************/
  89362. /************** Begin file update.c ******************************************/
  89363. /*
  89364. ** 2001 September 15
  89365. **
  89366. ** The author disclaims copyright to this source code. In place of
  89367. ** a legal notice, here is a blessing:
  89368. **
  89369. ** May you do good and not evil.
  89370. ** May you find forgiveness for yourself and forgive others.
  89371. ** May you share freely, never taking more than you give.
  89372. **
  89373. *************************************************************************
  89374. ** This file contains C code routines that are called by the parser
  89375. ** to handle UPDATE statements.
  89376. */
  89377. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89378. /* Forward declaration */
  89379. static void updateVirtualTable(
  89380. Parse *pParse, /* The parsing context */
  89381. SrcList *pSrc, /* The virtual table to be modified */
  89382. Table *pTab, /* The virtual table */
  89383. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  89384. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  89385. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  89386. Expr *pWhere /* WHERE clause of the UPDATE statement */
  89387. );
  89388. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  89389. /*
  89390. ** The most recently coded instruction was an OP_Column to retrieve the
  89391. ** i-th column of table pTab. This routine sets the P4 parameter of the
  89392. ** OP_Column to the default value, if any.
  89393. **
  89394. ** The default value of a column is specified by a DEFAULT clause in the
  89395. ** column definition. This was either supplied by the user when the table
  89396. ** was created, or added later to the table definition by an ALTER TABLE
  89397. ** command. If the latter, then the row-records in the table btree on disk
  89398. ** may not contain a value for the column and the default value, taken
  89399. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  89400. ** If the former, then all row-records are guaranteed to include a value
  89401. ** for the column and the P4 value is not required.
  89402. **
  89403. ** Column definitions created by an ALTER TABLE command may only have
  89404. ** literal default values specified: a number, null or a string. (If a more
  89405. ** complicated default expression value was provided, it is evaluated
  89406. ** when the ALTER TABLE is executed and one of the literal values written
  89407. ** into the sqlite_master table.)
  89408. **
  89409. ** Therefore, the P4 parameter is only required if the default value for
  89410. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  89411. ** function is capable of transforming these types of expressions into
  89412. ** sqlite3_value objects.
  89413. **
  89414. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  89415. ** on register iReg. This is used when an equivalent integer value is
  89416. ** stored in place of an 8-byte floating point value in order to save
  89417. ** space.
  89418. */
  89419. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  89420. assert( pTab!=0 );
  89421. if( !pTab->pSelect ){
  89422. sqlite3_value *pValue;
  89423. u8 enc = ENC(sqlite3VdbeDb(v));
  89424. Column *pCol = &pTab->aCol[i];
  89425. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  89426. assert( i<pTab->nCol );
  89427. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  89428. pCol->affinity, &pValue);
  89429. if( pValue ){
  89430. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  89431. }
  89432. #ifndef SQLITE_OMIT_FLOATING_POINT
  89433. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  89434. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  89435. }
  89436. #endif
  89437. }
  89438. }
  89439. /*
  89440. ** Process an UPDATE statement.
  89441. **
  89442. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  89443. ** \_______/ \________/ \______/ \________________/
  89444. * onError pTabList pChanges pWhere
  89445. */
  89446. SQLITE_PRIVATE void sqlite3Update(
  89447. Parse *pParse, /* The parser context */
  89448. SrcList *pTabList, /* The table in which we should change things */
  89449. ExprList *pChanges, /* Things to be changed */
  89450. Expr *pWhere, /* The WHERE clause. May be null */
  89451. int onError /* How to handle constraint errors */
  89452. ){
  89453. int i, j; /* Loop counters */
  89454. Table *pTab; /* The table to be updated */
  89455. int addr = 0; /* VDBE instruction address of the start of the loop */
  89456. WhereInfo *pWInfo; /* Information about the WHERE clause */
  89457. Vdbe *v; /* The virtual database engine */
  89458. Index *pIdx; /* For looping over indices */
  89459. int nIdx; /* Number of indices that need updating */
  89460. int iCur; /* VDBE Cursor number of pTab */
  89461. sqlite3 *db; /* The database structure */
  89462. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  89463. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  89464. ** an expression for the i-th column of the table.
  89465. ** aXRef[i]==-1 if the i-th column is not changed. */
  89466. int chngRowid; /* True if the record number is being changed */
  89467. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  89468. int openAll = 0; /* True if all indices need to be opened */
  89469. AuthContext sContext; /* The authorization context */
  89470. NameContext sNC; /* The name-context to resolve expressions in */
  89471. int iDb; /* Database containing the table being updated */
  89472. int okOnePass; /* True for one-pass algorithm without the FIFO */
  89473. int hasFK; /* True if foreign key processing is required */
  89474. #ifndef SQLITE_OMIT_TRIGGER
  89475. int isView; /* True when updating a view (INSTEAD OF trigger) */
  89476. Trigger *pTrigger; /* List of triggers on pTab, if required */
  89477. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  89478. #endif
  89479. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  89480. /* Register Allocations */
  89481. int regRowCount = 0; /* A count of rows changed */
  89482. int regOldRowid; /* The old rowid */
  89483. int regNewRowid; /* The new rowid */
  89484. int regNew;
  89485. int regOld = 0;
  89486. int regRowSet = 0; /* Rowset of rows to be updated */
  89487. memset(&sContext, 0, sizeof(sContext));
  89488. db = pParse->db;
  89489. if( pParse->nErr || db->mallocFailed ){
  89490. goto update_cleanup;
  89491. }
  89492. assert( pTabList->nSrc==1 );
  89493. /* Locate the table which we want to update.
  89494. */
  89495. pTab = sqlite3SrcListLookup(pParse, pTabList);
  89496. if( pTab==0 ) goto update_cleanup;
  89497. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  89498. /* Figure out if we have any triggers and if the table being
  89499. ** updated is a view.
  89500. */
  89501. #ifndef SQLITE_OMIT_TRIGGER
  89502. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  89503. isView = pTab->pSelect!=0;
  89504. assert( pTrigger || tmask==0 );
  89505. #else
  89506. # define pTrigger 0
  89507. # define isView 0
  89508. # define tmask 0
  89509. #endif
  89510. #ifdef SQLITE_OMIT_VIEW
  89511. # undef isView
  89512. # define isView 0
  89513. #endif
  89514. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  89515. goto update_cleanup;
  89516. }
  89517. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  89518. goto update_cleanup;
  89519. }
  89520. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  89521. if( aXRef==0 ) goto update_cleanup;
  89522. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  89523. /* Allocate a cursors for the main database table and for all indices.
  89524. ** The index cursors might not be used, but if they are used they
  89525. ** need to occur right after the database cursor. So go ahead and
  89526. ** allocate enough space, just in case.
  89527. */
  89528. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  89529. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  89530. pParse->nTab++;
  89531. }
  89532. /* Initialize the name-context */
  89533. memset(&sNC, 0, sizeof(sNC));
  89534. sNC.pParse = pParse;
  89535. sNC.pSrcList = pTabList;
  89536. /* Resolve the column names in all the expressions of the
  89537. ** of the UPDATE statement. Also find the column index
  89538. ** for each column to be updated in the pChanges array. For each
  89539. ** column to be updated, make sure we have authorization to change
  89540. ** that column.
  89541. */
  89542. chngRowid = 0;
  89543. for(i=0; i<pChanges->nExpr; i++){
  89544. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  89545. goto update_cleanup;
  89546. }
  89547. for(j=0; j<pTab->nCol; j++){
  89548. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  89549. if( j==pTab->iPKey ){
  89550. chngRowid = 1;
  89551. pRowidExpr = pChanges->a[i].pExpr;
  89552. }
  89553. aXRef[j] = i;
  89554. break;
  89555. }
  89556. }
  89557. if( j>=pTab->nCol ){
  89558. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  89559. chngRowid = 1;
  89560. pRowidExpr = pChanges->a[i].pExpr;
  89561. }else{
  89562. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  89563. pParse->checkSchema = 1;
  89564. goto update_cleanup;
  89565. }
  89566. }
  89567. #ifndef SQLITE_OMIT_AUTHORIZATION
  89568. {
  89569. int rc;
  89570. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  89571. pTab->aCol[j].zName, db->aDb[iDb].zName);
  89572. if( rc==SQLITE_DENY ){
  89573. goto update_cleanup;
  89574. }else if( rc==SQLITE_IGNORE ){
  89575. aXRef[j] = -1;
  89576. }
  89577. }
  89578. #endif
  89579. }
  89580. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  89581. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  89582. ** array for each index associated with table being updated. Fill in
  89583. ** the value with a register number for indices that are to be used
  89584. ** and with zero for unused indices.
  89585. */
  89586. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  89587. if( nIdx>0 ){
  89588. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  89589. if( aRegIdx==0 ) goto update_cleanup;
  89590. }
  89591. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  89592. int reg;
  89593. if( chngRowid ){
  89594. reg = ++pParse->nMem;
  89595. }else{
  89596. reg = 0;
  89597. for(i=0; i<pIdx->nColumn; i++){
  89598. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  89599. reg = ++pParse->nMem;
  89600. break;
  89601. }
  89602. }
  89603. }
  89604. aRegIdx[j] = reg;
  89605. }
  89606. /* Begin generating code. */
  89607. v = sqlite3GetVdbe(pParse);
  89608. if( v==0 ) goto update_cleanup;
  89609. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  89610. sqlite3BeginWriteOperation(pParse, 1, iDb);
  89611. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89612. /* Virtual tables must be handled separately */
  89613. if( IsVirtual(pTab) ){
  89614. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  89615. pWhere);
  89616. pWhere = 0;
  89617. pTabList = 0;
  89618. goto update_cleanup;
  89619. }
  89620. #endif
  89621. /* Allocate required registers. */
  89622. regOldRowid = regNewRowid = ++pParse->nMem;
  89623. if( pTrigger || hasFK ){
  89624. regOld = pParse->nMem + 1;
  89625. pParse->nMem += pTab->nCol;
  89626. }
  89627. if( chngRowid || pTrigger || hasFK ){
  89628. regNewRowid = ++pParse->nMem;
  89629. }
  89630. regNew = pParse->nMem + 1;
  89631. pParse->nMem += pTab->nCol;
  89632. /* Start the view context. */
  89633. if( isView ){
  89634. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  89635. }
  89636. /* If we are trying to update a view, realize that view into
  89637. ** a ephemeral table.
  89638. */
  89639. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  89640. if( isView ){
  89641. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  89642. }
  89643. #endif
  89644. /* Resolve the column names in all the expressions in the
  89645. ** WHERE clause.
  89646. */
  89647. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  89648. goto update_cleanup;
  89649. }
  89650. /* Begin the database scan
  89651. */
  89652. sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
  89653. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
  89654. if( pWInfo==0 ) goto update_cleanup;
  89655. okOnePass = pWInfo->okOnePass;
  89656. /* Remember the rowid of every item to be updated.
  89657. */
  89658. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  89659. if( !okOnePass ){
  89660. regRowSet = ++pParse->nMem;
  89661. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  89662. }
  89663. /* End the database scan loop.
  89664. */
  89665. sqlite3WhereEnd(pWInfo);
  89666. /* Initialize the count of updated rows
  89667. */
  89668. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  89669. regRowCount = ++pParse->nMem;
  89670. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  89671. }
  89672. if( !isView ){
  89673. /*
  89674. ** Open every index that needs updating. Note that if any
  89675. ** index could potentially invoke a REPLACE conflict resolution
  89676. ** action, then we need to open all indices because we might need
  89677. ** to be deleting some records.
  89678. */
  89679. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  89680. if( onError==OE_Replace ){
  89681. openAll = 1;
  89682. }else{
  89683. openAll = 0;
  89684. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  89685. if( pIdx->onError==OE_Replace ){
  89686. openAll = 1;
  89687. break;
  89688. }
  89689. }
  89690. }
  89691. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  89692. if( openAll || aRegIdx[i]>0 ){
  89693. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  89694. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  89695. (char*)pKey, P4_KEYINFO_HANDOFF);
  89696. assert( pParse->nTab>iCur+i+1 );
  89697. }
  89698. }
  89699. }
  89700. /* Top of the update loop */
  89701. if( okOnePass ){
  89702. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  89703. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  89704. sqlite3VdbeJumpHere(v, a1);
  89705. }else{
  89706. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  89707. }
  89708. /* Make cursor iCur point to the record that is being updated. If
  89709. ** this record does not exist for some reason (deleted by a trigger,
  89710. ** for example, then jump to the next iteration of the RowSet loop. */
  89711. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  89712. /* If the record number will change, set register regNewRowid to
  89713. ** contain the new value. If the record number is not being modified,
  89714. ** then regNewRowid is the same register as regOldRowid, which is
  89715. ** already populated. */
  89716. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  89717. if( chngRowid ){
  89718. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  89719. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  89720. }
  89721. /* If there are triggers on this table, populate an array of registers
  89722. ** with the required old.* column data. */
  89723. if( hasFK || pTrigger ){
  89724. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  89725. oldmask |= sqlite3TriggerColmask(pParse,
  89726. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  89727. );
  89728. for(i=0; i<pTab->nCol; i++){
  89729. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  89730. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  89731. }else{
  89732. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  89733. }
  89734. }
  89735. if( chngRowid==0 ){
  89736. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  89737. }
  89738. }
  89739. /* Populate the array of registers beginning at regNew with the new
  89740. ** row data. This array is used to check constaints, create the new
  89741. ** table and index records, and as the values for any new.* references
  89742. ** made by triggers.
  89743. **
  89744. ** If there are one or more BEFORE triggers, then do not populate the
  89745. ** registers associated with columns that are (a) not modified by
  89746. ** this UPDATE statement and (b) not accessed by new.* references. The
  89747. ** values for registers not modified by the UPDATE must be reloaded from
  89748. ** the database after the BEFORE triggers are fired anyway (as the trigger
  89749. ** may have modified them). So not loading those that are not going to
  89750. ** be used eliminates some redundant opcodes.
  89751. */
  89752. newmask = sqlite3TriggerColmask(
  89753. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  89754. );
  89755. for(i=0; i<pTab->nCol; i++){
  89756. if( i==pTab->iPKey ){
  89757. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  89758. }else{
  89759. j = aXRef[i];
  89760. if( j>=0 ){
  89761. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  89762. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  89763. /* This branch loads the value of a column that will not be changed
  89764. ** into a register. This is done if there are no BEFORE triggers, or
  89765. ** if there are one or more BEFORE triggers that use this value via
  89766. ** a new.* reference in a trigger program.
  89767. */
  89768. testcase( i==31 );
  89769. testcase( i==32 );
  89770. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  89771. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  89772. }
  89773. }
  89774. }
  89775. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  89776. ** verified. One could argue that this is wrong.
  89777. */
  89778. if( tmask&TRIGGER_BEFORE ){
  89779. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  89780. sqlite3TableAffinityStr(v, pTab);
  89781. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  89782. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  89783. /* The row-trigger may have deleted the row being updated. In this
  89784. ** case, jump to the next row. No updates or AFTER triggers are
  89785. ** required. This behaviour - what happens when the row being updated
  89786. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  89787. ** documentation.
  89788. */
  89789. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  89790. /* If it did not delete it, the row-trigger may still have modified
  89791. ** some of the columns of the row being updated. Load the values for
  89792. ** all columns not modified by the update statement into their
  89793. ** registers in case this has happened.
  89794. */
  89795. for(i=0; i<pTab->nCol; i++){
  89796. if( aXRef[i]<0 && i!=pTab->iPKey ){
  89797. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  89798. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  89799. }
  89800. }
  89801. }
  89802. if( !isView ){
  89803. int j1; /* Address of jump instruction */
  89804. /* Do constraint checks. */
  89805. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  89806. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  89807. /* Do FK constraint checks. */
  89808. if( hasFK ){
  89809. sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
  89810. }
  89811. /* Delete the index entries associated with the current record. */
  89812. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  89813. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  89814. /* If changing the record number, delete the old record. */
  89815. if( hasFK || chngRowid ){
  89816. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  89817. }
  89818. sqlite3VdbeJumpHere(v, j1);
  89819. if( hasFK ){
  89820. sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
  89821. }
  89822. /* Insert the new index entries and the new record. */
  89823. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  89824. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  89825. ** handle rows (possibly in other tables) that refer via a foreign key
  89826. ** to the row just updated. */
  89827. if( hasFK ){
  89828. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
  89829. }
  89830. }
  89831. /* Increment the row counter
  89832. */
  89833. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  89834. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  89835. }
  89836. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  89837. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  89838. /* Repeat the above with the next record to be updated, until
  89839. ** all record selected by the WHERE clause have been updated.
  89840. */
  89841. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  89842. sqlite3VdbeJumpHere(v, addr);
  89843. /* Close all tables */
  89844. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  89845. if( openAll || aRegIdx[i]>0 ){
  89846. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  89847. }
  89848. }
  89849. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  89850. /* Update the sqlite_sequence table by storing the content of the
  89851. ** maximum rowid counter values recorded while inserting into
  89852. ** autoincrement tables.
  89853. */
  89854. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  89855. sqlite3AutoincrementEnd(pParse);
  89856. }
  89857. /*
  89858. ** Return the number of rows that were changed. If this routine is
  89859. ** generating code because of a call to sqlite3NestedParse(), do not
  89860. ** invoke the callback function.
  89861. */
  89862. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  89863. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  89864. sqlite3VdbeSetNumCols(v, 1);
  89865. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  89866. }
  89867. update_cleanup:
  89868. sqlite3AuthContextPop(&sContext);
  89869. sqlite3DbFree(db, aRegIdx);
  89870. sqlite3DbFree(db, aXRef);
  89871. sqlite3SrcListDelete(db, pTabList);
  89872. sqlite3ExprListDelete(db, pChanges);
  89873. sqlite3ExprDelete(db, pWhere);
  89874. return;
  89875. }
  89876. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  89877. ** thely may interfere with compilation of other functions in this file
  89878. ** (or in another file, if this file becomes part of the amalgamation). */
  89879. #ifdef isView
  89880. #undef isView
  89881. #endif
  89882. #ifdef pTrigger
  89883. #undef pTrigger
  89884. #endif
  89885. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89886. /*
  89887. ** Generate code for an UPDATE of a virtual table.
  89888. **
  89889. ** The strategy is that we create an ephemerial table that contains
  89890. ** for each row to be changed:
  89891. **
  89892. ** (A) The original rowid of that row.
  89893. ** (B) The revised rowid for the row. (note1)
  89894. ** (C) The content of every column in the row.
  89895. **
  89896. ** Then we loop over this ephemeral table and for each row in
  89897. ** the ephermeral table call VUpdate.
  89898. **
  89899. ** When finished, drop the ephemeral table.
  89900. **
  89901. ** (note1) Actually, if we know in advance that (A) is always the same
  89902. ** as (B) we only store (A), then duplicate (A) when pulling
  89903. ** it out of the ephemeral table before calling VUpdate.
  89904. */
  89905. static void updateVirtualTable(
  89906. Parse *pParse, /* The parsing context */
  89907. SrcList *pSrc, /* The virtual table to be modified */
  89908. Table *pTab, /* The virtual table */
  89909. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  89910. Expr *pRowid, /* Expression used to recompute the rowid */
  89911. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  89912. Expr *pWhere /* WHERE clause of the UPDATE statement */
  89913. ){
  89914. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  89915. ExprList *pEList = 0; /* The result set of the SELECT statement */
  89916. Select *pSelect = 0; /* The SELECT statement */
  89917. Expr *pExpr; /* Temporary expression */
  89918. int ephemTab; /* Table holding the result of the SELECT */
  89919. int i; /* Loop counter */
  89920. int addr; /* Address of top of loop */
  89921. int iReg; /* First register in set passed to OP_VUpdate */
  89922. sqlite3 *db = pParse->db; /* Database connection */
  89923. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  89924. SelectDest dest;
  89925. /* Construct the SELECT statement that will find the new values for
  89926. ** all updated rows.
  89927. */
  89928. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  89929. if( pRowid ){
  89930. pEList = sqlite3ExprListAppend(pParse, pEList,
  89931. sqlite3ExprDup(db, pRowid, 0));
  89932. }
  89933. assert( pTab->iPKey<0 );
  89934. for(i=0; i<pTab->nCol; i++){
  89935. if( aXRef[i]>=0 ){
  89936. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  89937. }else{
  89938. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  89939. }
  89940. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  89941. }
  89942. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  89943. /* Create the ephemeral table into which the update results will
  89944. ** be stored.
  89945. */
  89946. assert( v );
  89947. ephemTab = pParse->nTab++;
  89948. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  89949. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  89950. /* fill the ephemeral table
  89951. */
  89952. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  89953. sqlite3Select(pParse, pSelect, &dest);
  89954. /* Generate code to scan the ephemeral table and call VUpdate. */
  89955. iReg = ++pParse->nMem;
  89956. pParse->nMem += pTab->nCol+1;
  89957. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  89958. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  89959. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  89960. for(i=0; i<pTab->nCol; i++){
  89961. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  89962. }
  89963. sqlite3VtabMakeWritable(pParse, pTab);
  89964. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  89965. sqlite3MayAbort(pParse);
  89966. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  89967. sqlite3VdbeJumpHere(v, addr);
  89968. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  89969. /* Cleanup */
  89970. sqlite3SelectDelete(db, pSelect);
  89971. }
  89972. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  89973. /************** End of update.c **********************************************/
  89974. /************** Begin file vacuum.c ******************************************/
  89975. /*
  89976. ** 2003 April 6
  89977. **
  89978. ** The author disclaims copyright to this source code. In place of
  89979. ** a legal notice, here is a blessing:
  89980. **
  89981. ** May you do good and not evil.
  89982. ** May you find forgiveness for yourself and forgive others.
  89983. ** May you share freely, never taking more than you give.
  89984. **
  89985. *************************************************************************
  89986. ** This file contains code used to implement the VACUUM command.
  89987. **
  89988. ** Most of the code in this file may be omitted by defining the
  89989. ** SQLITE_OMIT_VACUUM macro.
  89990. */
  89991. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  89992. /*
  89993. ** Finalize a prepared statement. If there was an error, store the
  89994. ** text of the error message in *pzErrMsg. Return the result code.
  89995. */
  89996. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  89997. int rc;
  89998. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  89999. if( rc ){
  90000. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  90001. }
  90002. return rc;
  90003. }
  90004. /*
  90005. ** Execute zSql on database db. Return an error code.
  90006. */
  90007. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  90008. sqlite3_stmt *pStmt;
  90009. VVA_ONLY( int rc; )
  90010. if( !zSql ){
  90011. return SQLITE_NOMEM;
  90012. }
  90013. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  90014. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  90015. return sqlite3_errcode(db);
  90016. }
  90017. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  90018. assert( rc!=SQLITE_ROW );
  90019. return vacuumFinalize(db, pStmt, pzErrMsg);
  90020. }
  90021. /*
  90022. ** Execute zSql on database db. The statement returns exactly
  90023. ** one column. Execute this as SQL on the same database.
  90024. */
  90025. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  90026. sqlite3_stmt *pStmt;
  90027. int rc;
  90028. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  90029. if( rc!=SQLITE_OK ) return rc;
  90030. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  90031. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  90032. if( rc!=SQLITE_OK ){
  90033. vacuumFinalize(db, pStmt, pzErrMsg);
  90034. return rc;
  90035. }
  90036. }
  90037. return vacuumFinalize(db, pStmt, pzErrMsg);
  90038. }
  90039. /*
  90040. ** The non-standard VACUUM command is used to clean up the database,
  90041. ** collapse free space, etc. It is modelled after the VACUUM command
  90042. ** in PostgreSQL.
  90043. **
  90044. ** In version 1.0.x of SQLite, the VACUUM command would call
  90045. ** gdbm_reorganize() on all the database tables. But beginning
  90046. ** with 2.0.0, SQLite no longer uses GDBM so this command has
  90047. ** become a no-op.
  90048. */
  90049. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  90050. Vdbe *v = sqlite3GetVdbe(pParse);
  90051. if( v ){
  90052. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  90053. }
  90054. return;
  90055. }
  90056. /*
  90057. ** This routine implements the OP_Vacuum opcode of the VDBE.
  90058. */
  90059. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  90060. int rc = SQLITE_OK; /* Return code from service routines */
  90061. Btree *pMain; /* The database being vacuumed */
  90062. Btree *pTemp; /* The temporary database we vacuum into */
  90063. char *zSql = 0; /* SQL statements */
  90064. int saved_flags; /* Saved value of the db->flags */
  90065. int saved_nChange; /* Saved value of db->nChange */
  90066. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  90067. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  90068. Db *pDb = 0; /* Database to detach at end of vacuum */
  90069. int isMemDb; /* True if vacuuming a :memory: database */
  90070. int nRes; /* Bytes of reserved space at the end of each page */
  90071. int nDb; /* Number of attached databases */
  90072. if( !db->autoCommit ){
  90073. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  90074. return SQLITE_ERROR;
  90075. }
  90076. if( db->activeVdbeCnt>1 ){
  90077. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  90078. return SQLITE_ERROR;
  90079. }
  90080. /* Save the current value of the database flags so that it can be
  90081. ** restored before returning. Then set the writable-schema flag, and
  90082. ** disable CHECK and foreign key constraints. */
  90083. saved_flags = db->flags;
  90084. saved_nChange = db->nChange;
  90085. saved_nTotalChange = db->nTotalChange;
  90086. saved_xTrace = db->xTrace;
  90087. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  90088. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  90089. db->xTrace = 0;
  90090. pMain = db->aDb[0].pBt;
  90091. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  90092. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  90093. ** can be set to 'off' for this file, as it is not recovered if a crash
  90094. ** occurs anyway. The integrity of the database is maintained by a
  90095. ** (possibly synchronous) transaction opened on the main database before
  90096. ** sqlite3BtreeCopyFile() is called.
  90097. **
  90098. ** An optimisation would be to use a non-journaled pager.
  90099. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  90100. ** that actually made the VACUUM run slower. Very little journalling
  90101. ** actually occurs when doing a vacuum since the vacuum_db is initially
  90102. ** empty. Only the journal header is written. Apparently it takes more
  90103. ** time to parse and run the PRAGMA to turn journalling off than it does
  90104. ** to write the journal header file.
  90105. */
  90106. nDb = db->nDb;
  90107. if( sqlite3TempInMemory(db) ){
  90108. zSql = "ATTACH ':memory:' AS vacuum_db;";
  90109. }else{
  90110. zSql = "ATTACH '' AS vacuum_db;";
  90111. }
  90112. rc = execSql(db, pzErrMsg, zSql);
  90113. if( db->nDb>nDb ){
  90114. pDb = &db->aDb[db->nDb-1];
  90115. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  90116. }
  90117. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90118. pTemp = db->aDb[db->nDb-1].pBt;
  90119. /* The call to execSql() to attach the temp database has left the file
  90120. ** locked (as there was more than one active statement when the transaction
  90121. ** to read the schema was concluded. Unlock it here so that this doesn't
  90122. ** cause problems for the call to BtreeSetPageSize() below. */
  90123. sqlite3BtreeCommit(pTemp);
  90124. nRes = sqlite3BtreeGetReserve(pMain);
  90125. /* A VACUUM cannot change the pagesize of an encrypted database. */
  90126. #ifdef SQLITE_HAS_CODEC
  90127. if( db->nextPagesize ){
  90128. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  90129. int nKey;
  90130. char *zKey;
  90131. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  90132. if( nKey ) db->nextPagesize = 0;
  90133. }
  90134. #endif
  90135. /* Do not attempt to change the page size for a WAL database */
  90136. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  90137. ==PAGER_JOURNALMODE_WAL ){
  90138. db->nextPagesize = 0;
  90139. }
  90140. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  90141. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  90142. || NEVER(db->mallocFailed)
  90143. ){
  90144. rc = SQLITE_NOMEM;
  90145. goto end_of_vacuum;
  90146. }
  90147. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  90148. if( rc!=SQLITE_OK ){
  90149. goto end_of_vacuum;
  90150. }
  90151. #ifndef SQLITE_OMIT_AUTOVACUUM
  90152. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  90153. sqlite3BtreeGetAutoVacuum(pMain));
  90154. #endif
  90155. /* Begin a transaction */
  90156. rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
  90157. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90158. /* Query the schema of the main database. Create a mirror schema
  90159. ** in the temporary database.
  90160. */
  90161. rc = execExecSql(db, pzErrMsg,
  90162. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  90163. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  90164. " AND rootpage>0"
  90165. );
  90166. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90167. rc = execExecSql(db, pzErrMsg,
  90168. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  90169. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  90170. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90171. rc = execExecSql(db, pzErrMsg,
  90172. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  90173. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  90174. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90175. /* Loop through the tables in the main database. For each, do
  90176. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  90177. ** the contents to the temporary database.
  90178. */
  90179. rc = execExecSql(db, pzErrMsg,
  90180. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  90181. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  90182. "FROM main.sqlite_master "
  90183. "WHERE type = 'table' AND name!='sqlite_sequence' "
  90184. " AND rootpage>0"
  90185. );
  90186. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90187. /* Copy over the sequence table
  90188. */
  90189. rc = execExecSql(db, pzErrMsg,
  90190. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  90191. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  90192. );
  90193. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90194. rc = execExecSql(db, pzErrMsg,
  90195. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  90196. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  90197. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  90198. );
  90199. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90200. /* Copy the triggers, views, and virtual tables from the main database
  90201. ** over to the temporary database. None of these objects has any
  90202. ** associated storage, so all we have to do is copy their entries
  90203. ** from the SQLITE_MASTER table.
  90204. */
  90205. rc = execSql(db, pzErrMsg,
  90206. "INSERT INTO vacuum_db.sqlite_master "
  90207. " SELECT type, name, tbl_name, rootpage, sql"
  90208. " FROM main.sqlite_master"
  90209. " WHERE type='view' OR type='trigger'"
  90210. " OR (type='table' AND rootpage=0)"
  90211. );
  90212. if( rc ) goto end_of_vacuum;
  90213. /* At this point, unless the main db was completely empty, there is now a
  90214. ** transaction open on the vacuum database, but not on the main database.
  90215. ** Open a btree level transaction on the main database. This allows a
  90216. ** call to sqlite3BtreeCopyFile(). The main database btree level
  90217. ** transaction is then committed, so the SQL level never knows it was
  90218. ** opened for writing. This way, the SQL transaction used to create the
  90219. ** temporary database never needs to be committed.
  90220. */
  90221. {
  90222. u32 meta;
  90223. int i;
  90224. /* This array determines which meta meta values are preserved in the
  90225. ** vacuum. Even entries are the meta value number and odd entries
  90226. ** are an increment to apply to the meta value after the vacuum.
  90227. ** The increment is used to increase the schema cookie so that other
  90228. ** connections to the same database will know to reread the schema.
  90229. */
  90230. static const unsigned char aCopy[] = {
  90231. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  90232. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  90233. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  90234. BTREE_USER_VERSION, 0, /* Preserve the user version */
  90235. };
  90236. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  90237. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  90238. /* Copy Btree meta values */
  90239. for(i=0; i<ArraySize(aCopy); i+=2){
  90240. /* GetMeta() and UpdateMeta() cannot fail in this context because
  90241. ** we already have page 1 loaded into cache and marked dirty. */
  90242. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  90243. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  90244. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  90245. }
  90246. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  90247. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90248. rc = sqlite3BtreeCommit(pTemp);
  90249. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  90250. #ifndef SQLITE_OMIT_AUTOVACUUM
  90251. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  90252. #endif
  90253. }
  90254. assert( rc==SQLITE_OK );
  90255. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  90256. end_of_vacuum:
  90257. /* Restore the original value of db->flags */
  90258. db->flags = saved_flags;
  90259. db->nChange = saved_nChange;
  90260. db->nTotalChange = saved_nTotalChange;
  90261. db->xTrace = saved_xTrace;
  90262. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  90263. /* Currently there is an SQL level transaction open on the vacuum
  90264. ** database. No locks are held on any other files (since the main file
  90265. ** was committed at the btree level). So it safe to end the transaction
  90266. ** by manually setting the autoCommit flag to true and detaching the
  90267. ** vacuum database. The vacuum_db journal file is deleted when the pager
  90268. ** is closed by the DETACH.
  90269. */
  90270. db->autoCommit = 1;
  90271. if( pDb ){
  90272. sqlite3BtreeClose(pDb->pBt);
  90273. pDb->pBt = 0;
  90274. pDb->pSchema = 0;
  90275. }
  90276. /* This both clears the schemas and reduces the size of the db->aDb[]
  90277. ** array. */
  90278. sqlite3ResetInternalSchema(db, -1);
  90279. return rc;
  90280. }
  90281. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  90282. /************** End of vacuum.c **********************************************/
  90283. /************** Begin file vtab.c ********************************************/
  90284. /*
  90285. ** 2006 June 10
  90286. **
  90287. ** The author disclaims copyright to this source code. In place of
  90288. ** a legal notice, here is a blessing:
  90289. **
  90290. ** May you do good and not evil.
  90291. ** May you find forgiveness for yourself and forgive others.
  90292. ** May you share freely, never taking more than you give.
  90293. **
  90294. *************************************************************************
  90295. ** This file contains code used to help implement virtual tables.
  90296. */
  90297. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90298. /*
  90299. ** The actual function that does the work of creating a new module.
  90300. ** This function implements the sqlite3_create_module() and
  90301. ** sqlite3_create_module_v2() interfaces.
  90302. */
  90303. static int createModule(
  90304. sqlite3 *db, /* Database in which module is registered */
  90305. const char *zName, /* Name assigned to this module */
  90306. const sqlite3_module *pModule, /* The definition of the module */
  90307. void *pAux, /* Context pointer for xCreate/xConnect */
  90308. void (*xDestroy)(void *) /* Module destructor function */
  90309. ){
  90310. int rc, nName;
  90311. Module *pMod;
  90312. sqlite3_mutex_enter(db->mutex);
  90313. nName = sqlite3Strlen30(zName);
  90314. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  90315. if( pMod ){
  90316. Module *pDel;
  90317. char *zCopy = (char *)(&pMod[1]);
  90318. memcpy(zCopy, zName, nName+1);
  90319. pMod->zName = zCopy;
  90320. pMod->pModule = pModule;
  90321. pMod->pAux = pAux;
  90322. pMod->xDestroy = xDestroy;
  90323. pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
  90324. if( pDel && pDel->xDestroy ){
  90325. pDel->xDestroy(pDel->pAux);
  90326. }
  90327. sqlite3DbFree(db, pDel);
  90328. if( pDel==pMod ){
  90329. db->mallocFailed = 1;
  90330. }
  90331. sqlite3ResetInternalSchema(db, -1);
  90332. }else if( xDestroy ){
  90333. xDestroy(pAux);
  90334. }
  90335. rc = sqlite3ApiExit(db, SQLITE_OK);
  90336. sqlite3_mutex_leave(db->mutex);
  90337. return rc;
  90338. }
  90339. /*
  90340. ** External API function used to create a new virtual-table module.
  90341. */
  90342. SQLITE_API int sqlite3_create_module(
  90343. sqlite3 *db, /* Database in which module is registered */
  90344. const char *zName, /* Name assigned to this module */
  90345. const sqlite3_module *pModule, /* The definition of the module */
  90346. void *pAux /* Context pointer for xCreate/xConnect */
  90347. ){
  90348. return createModule(db, zName, pModule, pAux, 0);
  90349. }
  90350. /*
  90351. ** External API function used to create a new virtual-table module.
  90352. */
  90353. SQLITE_API int sqlite3_create_module_v2(
  90354. sqlite3 *db, /* Database in which module is registered */
  90355. const char *zName, /* Name assigned to this module */
  90356. const sqlite3_module *pModule, /* The definition of the module */
  90357. void *pAux, /* Context pointer for xCreate/xConnect */
  90358. void (*xDestroy)(void *) /* Module destructor function */
  90359. ){
  90360. return createModule(db, zName, pModule, pAux, xDestroy);
  90361. }
  90362. /*
  90363. ** Lock the virtual table so that it cannot be disconnected.
  90364. ** Locks nest. Every lock should have a corresponding unlock.
  90365. ** If an unlock is omitted, resources leaks will occur.
  90366. **
  90367. ** If a disconnect is attempted while a virtual table is locked,
  90368. ** the disconnect is deferred until all locks have been removed.
  90369. */
  90370. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  90371. pVTab->nRef++;
  90372. }
  90373. /*
  90374. ** pTab is a pointer to a Table structure representing a virtual-table.
  90375. ** Return a pointer to the VTable object used by connection db to access
  90376. ** this virtual-table, if one has been created, or NULL otherwise.
  90377. */
  90378. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  90379. VTable *pVtab;
  90380. assert( IsVirtual(pTab) );
  90381. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  90382. return pVtab;
  90383. }
  90384. /*
  90385. ** Decrement the ref-count on a virtual table object. When the ref-count
  90386. ** reaches zero, call the xDisconnect() method to delete the object.
  90387. */
  90388. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  90389. sqlite3 *db = pVTab->db;
  90390. assert( db );
  90391. assert( pVTab->nRef>0 );
  90392. assert( sqlite3SafetyCheckOk(db) );
  90393. pVTab->nRef--;
  90394. if( pVTab->nRef==0 ){
  90395. sqlite3_vtab *p = pVTab->pVtab;
  90396. if( p ){
  90397. p->pModule->xDisconnect(p);
  90398. }
  90399. sqlite3DbFree(db, pVTab);
  90400. }
  90401. }
  90402. /*
  90403. ** Table p is a virtual table. This function moves all elements in the
  90404. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  90405. ** database connections to be disconnected at the next opportunity.
  90406. ** Except, if argument db is not NULL, then the entry associated with
  90407. ** connection db is left in the p->pVTable list.
  90408. */
  90409. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  90410. VTable *pRet = 0;
  90411. VTable *pVTable = p->pVTable;
  90412. p->pVTable = 0;
  90413. /* Assert that the mutex (if any) associated with the BtShared database
  90414. ** that contains table p is held by the caller. See header comments
  90415. ** above function sqlite3VtabUnlockList() for an explanation of why
  90416. ** this makes it safe to access the sqlite3.pDisconnect list of any
  90417. ** database connection that may have an entry in the p->pVTable list.
  90418. */
  90419. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  90420. while( pVTable ){
  90421. sqlite3 *db2 = pVTable->db;
  90422. VTable *pNext = pVTable->pNext;
  90423. assert( db2 );
  90424. if( db2==db ){
  90425. pRet = pVTable;
  90426. p->pVTable = pRet;
  90427. pRet->pNext = 0;
  90428. }else{
  90429. pVTable->pNext = db2->pDisconnect;
  90430. db2->pDisconnect = pVTable;
  90431. }
  90432. pVTable = pNext;
  90433. }
  90434. assert( !db || pRet );
  90435. return pRet;
  90436. }
  90437. /*
  90438. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  90439. **
  90440. ** This function may only be called when the mutexes associated with all
  90441. ** shared b-tree databases opened using connection db are held by the
  90442. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  90443. ** sqlite3.pDisconnect list is accessed only as follows:
  90444. **
  90445. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  90446. ** associated with the database handle itself must be held.
  90447. **
  90448. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  90449. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  90450. ** associated with the database the virtual table is stored in is held
  90451. ** or, if the virtual table is stored in a non-sharable database, then
  90452. ** the database handle mutex is held.
  90453. **
  90454. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  90455. ** by multiple threads. It is thread-safe.
  90456. */
  90457. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  90458. VTable *p = db->pDisconnect;
  90459. db->pDisconnect = 0;
  90460. assert( sqlite3BtreeHoldsAllMutexes(db) );
  90461. assert( sqlite3_mutex_held(db->mutex) );
  90462. if( p ){
  90463. sqlite3ExpirePreparedStatements(db);
  90464. do {
  90465. VTable *pNext = p->pNext;
  90466. sqlite3VtabUnlock(p);
  90467. p = pNext;
  90468. }while( p );
  90469. }
  90470. }
  90471. /*
  90472. ** Clear any and all virtual-table information from the Table record.
  90473. ** This routine is called, for example, just before deleting the Table
  90474. ** record.
  90475. **
  90476. ** Since it is a virtual-table, the Table structure contains a pointer
  90477. ** to the head of a linked list of VTable structures. Each VTable
  90478. ** structure is associated with a single sqlite3* user of the schema.
  90479. ** The reference count of the VTable structure associated with database
  90480. ** connection db is decremented immediately (which may lead to the
  90481. ** structure being xDisconnected and free). Any other VTable structures
  90482. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  90483. ** database connection.
  90484. */
  90485. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  90486. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  90487. if( p->azModuleArg ){
  90488. int i;
  90489. for(i=0; i<p->nModuleArg; i++){
  90490. sqlite3DbFree(db, p->azModuleArg[i]);
  90491. }
  90492. sqlite3DbFree(db, p->azModuleArg);
  90493. }
  90494. }
  90495. /*
  90496. ** Add a new module argument to pTable->azModuleArg[].
  90497. ** The string is not copied - the pointer is stored. The
  90498. ** string will be freed automatically when the table is
  90499. ** deleted.
  90500. */
  90501. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  90502. int i = pTable->nModuleArg++;
  90503. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  90504. char **azModuleArg;
  90505. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  90506. if( azModuleArg==0 ){
  90507. int j;
  90508. for(j=0; j<i; j++){
  90509. sqlite3DbFree(db, pTable->azModuleArg[j]);
  90510. }
  90511. sqlite3DbFree(db, zArg);
  90512. sqlite3DbFree(db, pTable->azModuleArg);
  90513. pTable->nModuleArg = 0;
  90514. }else{
  90515. azModuleArg[i] = zArg;
  90516. azModuleArg[i+1] = 0;
  90517. }
  90518. pTable->azModuleArg = azModuleArg;
  90519. }
  90520. /*
  90521. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  90522. ** statement. The module name has been parsed, but the optional list
  90523. ** of parameters that follow the module name are still pending.
  90524. */
  90525. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  90526. Parse *pParse, /* Parsing context */
  90527. Token *pName1, /* Name of new table, or database name */
  90528. Token *pName2, /* Name of new table or NULL */
  90529. Token *pModuleName /* Name of the module for the virtual table */
  90530. ){
  90531. int iDb; /* The database the table is being created in */
  90532. Table *pTable; /* The new virtual table */
  90533. sqlite3 *db; /* Database connection */
  90534. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
  90535. pTable = pParse->pNewTable;
  90536. if( pTable==0 ) return;
  90537. assert( 0==pTable->pIndex );
  90538. db = pParse->db;
  90539. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  90540. assert( iDb>=0 );
  90541. pTable->tabFlags |= TF_Virtual;
  90542. pTable->nModuleArg = 0;
  90543. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  90544. addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
  90545. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  90546. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  90547. #ifndef SQLITE_OMIT_AUTHORIZATION
  90548. /* Creating a virtual table invokes the authorization callback twice.
  90549. ** The first invocation, to obtain permission to INSERT a row into the
  90550. ** sqlite_master table, has already been made by sqlite3StartTable().
  90551. ** The second call, to obtain permission to create the table, is made now.
  90552. */
  90553. if( pTable->azModuleArg ){
  90554. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  90555. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  90556. }
  90557. #endif
  90558. }
  90559. /*
  90560. ** This routine takes the module argument that has been accumulating
  90561. ** in pParse->zArg[] and appends it to the list of arguments on the
  90562. ** virtual table currently under construction in pParse->pTable.
  90563. */
  90564. static void addArgumentToVtab(Parse *pParse){
  90565. if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
  90566. const char *z = (const char*)pParse->sArg.z;
  90567. int n = pParse->sArg.n;
  90568. sqlite3 *db = pParse->db;
  90569. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  90570. }
  90571. }
  90572. /*
  90573. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  90574. ** has been completely parsed.
  90575. */
  90576. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  90577. Table *pTab = pParse->pNewTable; /* The table being constructed */
  90578. sqlite3 *db = pParse->db; /* The database connection */
  90579. if( pTab==0 ) return;
  90580. addArgumentToVtab(pParse);
  90581. pParse->sArg.z = 0;
  90582. if( pTab->nModuleArg<1 ) return;
  90583. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  90584. ** first time (in other words if the virtual table is actually being
  90585. ** created now instead of just being read out of sqlite_master) then
  90586. ** do additional initialization work and store the statement text
  90587. ** in the sqlite_master table.
  90588. */
  90589. if( !db->init.busy ){
  90590. char *zStmt;
  90591. char *zWhere;
  90592. int iDb;
  90593. Vdbe *v;
  90594. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  90595. if( pEnd ){
  90596. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  90597. }
  90598. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  90599. /* A slot for the record has already been allocated in the
  90600. ** SQLITE_MASTER table. We just need to update that slot with all
  90601. ** the information we've collected.
  90602. **
  90603. ** The VM register number pParse->regRowid holds the rowid of an
  90604. ** entry in the sqlite_master table tht was created for this vtab
  90605. ** by sqlite3StartTable().
  90606. */
  90607. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90608. sqlite3NestedParse(pParse,
  90609. "UPDATE %Q.%s "
  90610. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  90611. "WHERE rowid=#%d",
  90612. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  90613. pTab->zName,
  90614. pTab->zName,
  90615. zStmt,
  90616. pParse->regRowid
  90617. );
  90618. sqlite3DbFree(db, zStmt);
  90619. v = sqlite3GetVdbe(pParse);
  90620. sqlite3ChangeCookie(pParse, iDb);
  90621. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  90622. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  90623. sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  90624. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  90625. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  90626. }
  90627. /* If we are rereading the sqlite_master table create the in-memory
  90628. ** record of the table. The xConnect() method is not called until
  90629. ** the first time the virtual table is used in an SQL statement. This
  90630. ** allows a schema that contains virtual tables to be loaded before
  90631. ** the required virtual table implementations are registered. */
  90632. else {
  90633. Table *pOld;
  90634. Schema *pSchema = pTab->pSchema;
  90635. const char *zName = pTab->zName;
  90636. int nName = sqlite3Strlen30(zName);
  90637. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  90638. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  90639. if( pOld ){
  90640. db->mallocFailed = 1;
  90641. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  90642. return;
  90643. }
  90644. pParse->pNewTable = 0;
  90645. }
  90646. }
  90647. /*
  90648. ** The parser calls this routine when it sees the first token
  90649. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  90650. */
  90651. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  90652. addArgumentToVtab(pParse);
  90653. pParse->sArg.z = 0;
  90654. pParse->sArg.n = 0;
  90655. }
  90656. /*
  90657. ** The parser calls this routine for each token after the first token
  90658. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  90659. */
  90660. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  90661. Token *pArg = &pParse->sArg;
  90662. if( pArg->z==0 ){
  90663. pArg->z = p->z;
  90664. pArg->n = p->n;
  90665. }else{
  90666. assert(pArg->z < p->z);
  90667. pArg->n = (int)(&p->z[p->n] - pArg->z);
  90668. }
  90669. }
  90670. /*
  90671. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  90672. ** pointer to the function to invoke is passed as the fourth parameter
  90673. ** to this procedure.
  90674. */
  90675. static int vtabCallConstructor(
  90676. sqlite3 *db,
  90677. Table *pTab,
  90678. Module *pMod,
  90679. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  90680. char **pzErr
  90681. ){
  90682. VTable *pVTable;
  90683. int rc;
  90684. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  90685. int nArg = pTab->nModuleArg;
  90686. char *zErr = 0;
  90687. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  90688. if( !zModuleName ){
  90689. return SQLITE_NOMEM;
  90690. }
  90691. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  90692. if( !pVTable ){
  90693. sqlite3DbFree(db, zModuleName);
  90694. return SQLITE_NOMEM;
  90695. }
  90696. pVTable->db = db;
  90697. pVTable->pMod = pMod;
  90698. assert( !db->pVTab );
  90699. assert( xConstruct );
  90700. db->pVTab = pTab;
  90701. /* Invoke the virtual table constructor */
  90702. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  90703. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  90704. if( SQLITE_OK!=rc ){
  90705. if( zErr==0 ){
  90706. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  90707. }else {
  90708. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  90709. sqlite3_free(zErr);
  90710. }
  90711. sqlite3DbFree(db, pVTable);
  90712. }else if( ALWAYS(pVTable->pVtab) ){
  90713. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  90714. ** the sqlite3_vtab object if successful. */
  90715. pVTable->pVtab->pModule = pMod->pModule;
  90716. pVTable->nRef = 1;
  90717. if( db->pVTab ){
  90718. const char *zFormat = "vtable constructor did not declare schema: %s";
  90719. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  90720. sqlite3VtabUnlock(pVTable);
  90721. rc = SQLITE_ERROR;
  90722. }else{
  90723. int iCol;
  90724. /* If everything went according to plan, link the new VTable structure
  90725. ** into the linked list headed by pTab->pVTable. Then loop through the
  90726. ** columns of the table to see if any of them contain the token "hidden".
  90727. ** If so, set the Column.isHidden flag and remove the token from
  90728. ** the type string. */
  90729. pVTable->pNext = pTab->pVTable;
  90730. pTab->pVTable = pVTable;
  90731. for(iCol=0; iCol<pTab->nCol; iCol++){
  90732. char *zType = pTab->aCol[iCol].zType;
  90733. int nType;
  90734. int i = 0;
  90735. if( !zType ) continue;
  90736. nType = sqlite3Strlen30(zType);
  90737. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  90738. for(i=0; i<nType; i++){
  90739. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  90740. && (zType[i+7]=='\0' || zType[i+7]==' ')
  90741. ){
  90742. i++;
  90743. break;
  90744. }
  90745. }
  90746. }
  90747. if( i<nType ){
  90748. int j;
  90749. int nDel = 6 + (zType[i+6] ? 1 : 0);
  90750. for(j=i; (j+nDel)<=nType; j++){
  90751. zType[j] = zType[j+nDel];
  90752. }
  90753. if( zType[i]=='\0' && i>0 ){
  90754. assert(zType[i-1]==' ');
  90755. zType[i-1] = '\0';
  90756. }
  90757. pTab->aCol[iCol].isHidden = 1;
  90758. }
  90759. }
  90760. }
  90761. }
  90762. sqlite3DbFree(db, zModuleName);
  90763. db->pVTab = 0;
  90764. return rc;
  90765. }
  90766. /*
  90767. ** This function is invoked by the parser to call the xConnect() method
  90768. ** of the virtual table pTab. If an error occurs, an error code is returned
  90769. ** and an error left in pParse.
  90770. **
  90771. ** This call is a no-op if table pTab is not a virtual table.
  90772. */
  90773. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  90774. sqlite3 *db = pParse->db;
  90775. const char *zMod;
  90776. Module *pMod;
  90777. int rc;
  90778. assert( pTab );
  90779. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  90780. return SQLITE_OK;
  90781. }
  90782. /* Locate the required virtual table module */
  90783. zMod = pTab->azModuleArg[0];
  90784. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  90785. if( !pMod ){
  90786. const char *zModule = pTab->azModuleArg[0];
  90787. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  90788. rc = SQLITE_ERROR;
  90789. }else{
  90790. char *zErr = 0;
  90791. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  90792. if( rc!=SQLITE_OK ){
  90793. sqlite3ErrorMsg(pParse, "%s", zErr);
  90794. }
  90795. sqlite3DbFree(db, zErr);
  90796. }
  90797. return rc;
  90798. }
  90799. /*
  90800. ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
  90801. */
  90802. static int addToVTrans(sqlite3 *db, VTable *pVTab){
  90803. const int ARRAY_INCR = 5;
  90804. /* Grow the sqlite3.aVTrans array if required */
  90805. if( (db->nVTrans%ARRAY_INCR)==0 ){
  90806. VTable **aVTrans;
  90807. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  90808. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  90809. if( !aVTrans ){
  90810. return SQLITE_NOMEM;
  90811. }
  90812. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  90813. db->aVTrans = aVTrans;
  90814. }
  90815. /* Add pVtab to the end of sqlite3.aVTrans */
  90816. db->aVTrans[db->nVTrans++] = pVTab;
  90817. sqlite3VtabLock(pVTab);
  90818. return SQLITE_OK;
  90819. }
  90820. /*
  90821. ** This function is invoked by the vdbe to call the xCreate method
  90822. ** of the virtual table named zTab in database iDb.
  90823. **
  90824. ** If an error occurs, *pzErr is set to point an an English language
  90825. ** description of the error and an SQLITE_XXX error code is returned.
  90826. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  90827. */
  90828. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  90829. int rc = SQLITE_OK;
  90830. Table *pTab;
  90831. Module *pMod;
  90832. const char *zMod;
  90833. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  90834. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  90835. /* Locate the required virtual table module */
  90836. zMod = pTab->azModuleArg[0];
  90837. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  90838. /* If the module has been registered and includes a Create method,
  90839. ** invoke it now. If the module has not been registered, return an
  90840. ** error. Otherwise, do nothing.
  90841. */
  90842. if( !pMod ){
  90843. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  90844. rc = SQLITE_ERROR;
  90845. }else{
  90846. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  90847. }
  90848. /* Justification of ALWAYS(): The xConstructor method is required to
  90849. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  90850. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  90851. rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
  90852. }
  90853. return rc;
  90854. }
  90855. /*
  90856. ** This function is used to set the schema of a virtual table. It is only
  90857. ** valid to call this function from within the xCreate() or xConnect() of a
  90858. ** virtual table module.
  90859. */
  90860. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  90861. Parse *pParse;
  90862. int rc = SQLITE_OK;
  90863. Table *pTab;
  90864. char *zErr = 0;
  90865. sqlite3_mutex_enter(db->mutex);
  90866. pTab = db->pVTab;
  90867. if( !pTab ){
  90868. sqlite3Error(db, SQLITE_MISUSE, 0);
  90869. sqlite3_mutex_leave(db->mutex);
  90870. return SQLITE_MISUSE_BKPT;
  90871. }
  90872. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  90873. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  90874. if( pParse==0 ){
  90875. rc = SQLITE_NOMEM;
  90876. }else{
  90877. pParse->declareVtab = 1;
  90878. pParse->db = db;
  90879. pParse->nQueryLoop = 1;
  90880. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  90881. && pParse->pNewTable
  90882. && !db->mallocFailed
  90883. && !pParse->pNewTable->pSelect
  90884. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  90885. ){
  90886. if( !pTab->aCol ){
  90887. pTab->aCol = pParse->pNewTable->aCol;
  90888. pTab->nCol = pParse->pNewTable->nCol;
  90889. pParse->pNewTable->nCol = 0;
  90890. pParse->pNewTable->aCol = 0;
  90891. }
  90892. db->pVTab = 0;
  90893. }else{
  90894. sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  90895. sqlite3DbFree(db, zErr);
  90896. rc = SQLITE_ERROR;
  90897. }
  90898. pParse->declareVtab = 0;
  90899. if( pParse->pVdbe ){
  90900. sqlite3VdbeFinalize(pParse->pVdbe);
  90901. }
  90902. sqlite3DeleteTable(db, pParse->pNewTable);
  90903. sqlite3StackFree(db, pParse);
  90904. }
  90905. assert( (rc&0xff)==rc );
  90906. rc = sqlite3ApiExit(db, rc);
  90907. sqlite3_mutex_leave(db->mutex);
  90908. return rc;
  90909. }
  90910. /*
  90911. ** This function is invoked by the vdbe to call the xDestroy method
  90912. ** of the virtual table named zTab in database iDb. This occurs
  90913. ** when a DROP TABLE is mentioned.
  90914. **
  90915. ** This call is a no-op if zTab is not a virtual table.
  90916. */
  90917. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  90918. int rc = SQLITE_OK;
  90919. Table *pTab;
  90920. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  90921. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  90922. VTable *p = vtabDisconnectAll(db, pTab);
  90923. assert( rc==SQLITE_OK );
  90924. rc = p->pMod->pModule->xDestroy(p->pVtab);
  90925. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  90926. if( rc==SQLITE_OK ){
  90927. assert( pTab->pVTable==p && p->pNext==0 );
  90928. p->pVtab = 0;
  90929. pTab->pVTable = 0;
  90930. sqlite3VtabUnlock(p);
  90931. }
  90932. }
  90933. return rc;
  90934. }
  90935. /*
  90936. ** This function invokes either the xRollback or xCommit method
  90937. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  90938. ** called is identified by the second argument, "offset", which is
  90939. ** the offset of the method to call in the sqlite3_module structure.
  90940. **
  90941. ** The array is cleared after invoking the callbacks.
  90942. */
  90943. static void callFinaliser(sqlite3 *db, int offset){
  90944. int i;
  90945. if( db->aVTrans ){
  90946. for(i=0; i<db->nVTrans; i++){
  90947. VTable *pVTab = db->aVTrans[i];
  90948. sqlite3_vtab *p = pVTab->pVtab;
  90949. if( p ){
  90950. int (*x)(sqlite3_vtab *);
  90951. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  90952. if( x ) x(p);
  90953. }
  90954. sqlite3VtabUnlock(pVTab);
  90955. }
  90956. sqlite3DbFree(db, db->aVTrans);
  90957. db->nVTrans = 0;
  90958. db->aVTrans = 0;
  90959. }
  90960. }
  90961. /*
  90962. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  90963. ** array. Return the error code for the first error that occurs, or
  90964. ** SQLITE_OK if all xSync operations are successful.
  90965. **
  90966. ** Set *pzErrmsg to point to a buffer that should be released using
  90967. ** sqlite3DbFree() containing an error message, if one is available.
  90968. */
  90969. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
  90970. int i;
  90971. int rc = SQLITE_OK;
  90972. VTable **aVTrans = db->aVTrans;
  90973. db->aVTrans = 0;
  90974. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  90975. int (*x)(sqlite3_vtab *);
  90976. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  90977. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  90978. rc = x(pVtab);
  90979. sqlite3DbFree(db, *pzErrmsg);
  90980. *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  90981. sqlite3_free(pVtab->zErrMsg);
  90982. }
  90983. }
  90984. db->aVTrans = aVTrans;
  90985. return rc;
  90986. }
  90987. /*
  90988. ** Invoke the xRollback method of all virtual tables in the
  90989. ** sqlite3.aVTrans array. Then clear the array itself.
  90990. */
  90991. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  90992. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  90993. return SQLITE_OK;
  90994. }
  90995. /*
  90996. ** Invoke the xCommit method of all virtual tables in the
  90997. ** sqlite3.aVTrans array. Then clear the array itself.
  90998. */
  90999. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  91000. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  91001. return SQLITE_OK;
  91002. }
  91003. /*
  91004. ** If the virtual table pVtab supports the transaction interface
  91005. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  91006. ** not currently open, invoke the xBegin method now.
  91007. **
  91008. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  91009. ** in the sqlite3.aVTrans array.
  91010. */
  91011. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  91012. int rc = SQLITE_OK;
  91013. const sqlite3_module *pModule;
  91014. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  91015. ** than zero, then this function is being called from within a
  91016. ** virtual module xSync() callback. It is illegal to write to
  91017. ** virtual module tables in this case, so return SQLITE_LOCKED.
  91018. */
  91019. if( sqlite3VtabInSync(db) ){
  91020. return SQLITE_LOCKED;
  91021. }
  91022. if( !pVTab ){
  91023. return SQLITE_OK;
  91024. }
  91025. pModule = pVTab->pVtab->pModule;
  91026. if( pModule->xBegin ){
  91027. int i;
  91028. /* If pVtab is already in the aVTrans array, return early */
  91029. for(i=0; i<db->nVTrans; i++){
  91030. if( db->aVTrans[i]==pVTab ){
  91031. return SQLITE_OK;
  91032. }
  91033. }
  91034. /* Invoke the xBegin method */
  91035. rc = pModule->xBegin(pVTab->pVtab);
  91036. if( rc==SQLITE_OK ){
  91037. rc = addToVTrans(db, pVTab);
  91038. }
  91039. }
  91040. return rc;
  91041. }
  91042. /*
  91043. ** The first parameter (pDef) is a function implementation. The
  91044. ** second parameter (pExpr) is the first argument to this function.
  91045. ** If pExpr is a column in a virtual table, then let the virtual
  91046. ** table implementation have an opportunity to overload the function.
  91047. **
  91048. ** This routine is used to allow virtual table implementations to
  91049. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  91050. **
  91051. ** Return either the pDef argument (indicating no change) or a
  91052. ** new FuncDef structure that is marked as ephemeral using the
  91053. ** SQLITE_FUNC_EPHEM flag.
  91054. */
  91055. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  91056. sqlite3 *db, /* Database connection for reporting malloc problems */
  91057. FuncDef *pDef, /* Function to possibly overload */
  91058. int nArg, /* Number of arguments to the function */
  91059. Expr *pExpr /* First argument to the function */
  91060. ){
  91061. Table *pTab;
  91062. sqlite3_vtab *pVtab;
  91063. sqlite3_module *pMod;
  91064. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  91065. void *pArg = 0;
  91066. FuncDef *pNew;
  91067. int rc = 0;
  91068. char *zLowerName;
  91069. unsigned char *z;
  91070. /* Check to see the left operand is a column in a virtual table */
  91071. if( NEVER(pExpr==0) ) return pDef;
  91072. if( pExpr->op!=TK_COLUMN ) return pDef;
  91073. pTab = pExpr->pTab;
  91074. if( NEVER(pTab==0) ) return pDef;
  91075. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  91076. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  91077. assert( pVtab!=0 );
  91078. assert( pVtab->pModule!=0 );
  91079. pMod = (sqlite3_module *)pVtab->pModule;
  91080. if( pMod->xFindFunction==0 ) return pDef;
  91081. /* Call the xFindFunction method on the virtual table implementation
  91082. ** to see if the implementation wants to overload this function
  91083. */
  91084. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  91085. if( zLowerName ){
  91086. for(z=(unsigned char*)zLowerName; *z; z++){
  91087. *z = sqlite3UpperToLower[*z];
  91088. }
  91089. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  91090. sqlite3DbFree(db, zLowerName);
  91091. }
  91092. if( rc==0 ){
  91093. return pDef;
  91094. }
  91095. /* Create a new ephemeral function definition for the overloaded
  91096. ** function */
  91097. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  91098. + sqlite3Strlen30(pDef->zName) + 1);
  91099. if( pNew==0 ){
  91100. return pDef;
  91101. }
  91102. *pNew = *pDef;
  91103. pNew->zName = (char *)&pNew[1];
  91104. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  91105. pNew->xFunc = xFunc;
  91106. pNew->pUserData = pArg;
  91107. pNew->flags |= SQLITE_FUNC_EPHEM;
  91108. return pNew;
  91109. }
  91110. /*
  91111. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  91112. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  91113. ** array if it is missing. If pTab is already in the array, this routine
  91114. ** is a no-op.
  91115. */
  91116. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  91117. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91118. int i, n;
  91119. Table **apVtabLock;
  91120. assert( IsVirtual(pTab) );
  91121. for(i=0; i<pToplevel->nVtabLock; i++){
  91122. if( pTab==pToplevel->apVtabLock[i] ) return;
  91123. }
  91124. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  91125. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  91126. if( apVtabLock ){
  91127. pToplevel->apVtabLock = apVtabLock;
  91128. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  91129. }else{
  91130. pToplevel->db->mallocFailed = 1;
  91131. }
  91132. }
  91133. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  91134. /************** End of vtab.c ************************************************/
  91135. /************** Begin file where.c *******************************************/
  91136. /*
  91137. ** 2001 September 15
  91138. **
  91139. ** The author disclaims copyright to this source code. In place of
  91140. ** a legal notice, here is a blessing:
  91141. **
  91142. ** May you do good and not evil.
  91143. ** May you find forgiveness for yourself and forgive others.
  91144. ** May you share freely, never taking more than you give.
  91145. **
  91146. *************************************************************************
  91147. ** This module contains C code that generates VDBE code used to process
  91148. ** the WHERE clause of SQL statements. This module is responsible for
  91149. ** generating the code that loops through a table looking for applicable
  91150. ** rows. Indices are selected and used to speed the search when doing
  91151. ** so is applicable. Because this module is responsible for selecting
  91152. ** indices, you might also think of this module as the "query optimizer".
  91153. */
  91154. /*
  91155. ** Trace output macros
  91156. */
  91157. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  91158. SQLITE_PRIVATE int sqlite3WhereTrace = 0;
  91159. #endif
  91160. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  91161. # define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
  91162. #else
  91163. # define WHERETRACE(X)
  91164. #endif
  91165. /* Forward reference
  91166. */
  91167. typedef struct WhereClause WhereClause;
  91168. typedef struct WhereMaskSet WhereMaskSet;
  91169. typedef struct WhereOrInfo WhereOrInfo;
  91170. typedef struct WhereAndInfo WhereAndInfo;
  91171. typedef struct WhereCost WhereCost;
  91172. /*
  91173. ** The query generator uses an array of instances of this structure to
  91174. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  91175. ** clause subexpression is separated from the others by AND operators,
  91176. ** usually, or sometimes subexpressions separated by OR.
  91177. **
  91178. ** All WhereTerms are collected into a single WhereClause structure.
  91179. ** The following identity holds:
  91180. **
  91181. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  91182. **
  91183. ** When a term is of the form:
  91184. **
  91185. ** X <op> <expr>
  91186. **
  91187. ** where X is a column name and <op> is one of certain operators,
  91188. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  91189. ** cursor number and column number for X. WhereTerm.eOperator records
  91190. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  91191. ** use of a bitmask encoding for the operator allows us to search
  91192. ** quickly for terms that match any of several different operators.
  91193. **
  91194. ** A WhereTerm might also be two or more subterms connected by OR:
  91195. **
  91196. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  91197. **
  91198. ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
  91199. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  91200. ** is collected about the
  91201. **
  91202. ** If a term in the WHERE clause does not match either of the two previous
  91203. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  91204. ** to the original subexpression content and wtFlags is set up appropriately
  91205. ** but no other fields in the WhereTerm object are meaningful.
  91206. **
  91207. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  91208. ** but they do so indirectly. A single WhereMaskSet structure translates
  91209. ** cursor number into bits and the translated bit is stored in the prereq
  91210. ** fields. The translation is used in order to maximize the number of
  91211. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  91212. ** spread out over the non-negative integers. For example, the cursor
  91213. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  91214. ** translates these sparse cursor numbers into consecutive integers
  91215. ** beginning with 0 in order to make the best possible use of the available
  91216. ** bits in the Bitmask. So, in the example above, the cursor numbers
  91217. ** would be mapped into integers 0 through 7.
  91218. **
  91219. ** The number of terms in a join is limited by the number of bits
  91220. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  91221. ** is only able to process joins with 64 or fewer tables.
  91222. */
  91223. typedef struct WhereTerm WhereTerm;
  91224. struct WhereTerm {
  91225. Expr *pExpr; /* Pointer to the subexpression that is this term */
  91226. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  91227. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  91228. union {
  91229. int leftColumn; /* Column number of X in "X <op> <expr>" */
  91230. WhereOrInfo *pOrInfo; /* Extra information if eOperator==WO_OR */
  91231. WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
  91232. } u;
  91233. u16 eOperator; /* A WO_xx value describing <op> */
  91234. u8 wtFlags; /* TERM_xxx bit flags. See below */
  91235. u8 nChild; /* Number of children that must disable us */
  91236. WhereClause *pWC; /* The clause this term is part of */
  91237. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  91238. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  91239. };
  91240. /*
  91241. ** Allowed values of WhereTerm.wtFlags
  91242. */
  91243. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  91244. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  91245. #define TERM_CODED 0x04 /* This term is already coded */
  91246. #define TERM_COPIED 0x08 /* Has a child */
  91247. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  91248. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  91249. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  91250. #ifdef SQLITE_ENABLE_STAT2
  91251. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  91252. #else
  91253. # define TERM_VNULL 0x00 /* Disabled if not using stat2 */
  91254. #endif
  91255. /*
  91256. ** An instance of the following structure holds all information about a
  91257. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  91258. */
  91259. struct WhereClause {
  91260. Parse *pParse; /* The parser context */
  91261. WhereMaskSet *pMaskSet; /* Mapping of table cursor numbers to bitmasks */
  91262. Bitmask vmask; /* Bitmask identifying virtual table cursors */
  91263. u8 op; /* Split operator. TK_AND or TK_OR */
  91264. int nTerm; /* Number of terms */
  91265. int nSlot; /* Number of entries in a[] */
  91266. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  91267. #if defined(SQLITE_SMALL_STACK)
  91268. WhereTerm aStatic[1]; /* Initial static space for a[] */
  91269. #else
  91270. WhereTerm aStatic[8]; /* Initial static space for a[] */
  91271. #endif
  91272. };
  91273. /*
  91274. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  91275. ** a dynamically allocated instance of the following structure.
  91276. */
  91277. struct WhereOrInfo {
  91278. WhereClause wc; /* Decomposition into subterms */
  91279. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  91280. };
  91281. /*
  91282. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  91283. ** a dynamically allocated instance of the following structure.
  91284. */
  91285. struct WhereAndInfo {
  91286. WhereClause wc; /* The subexpression broken out */
  91287. };
  91288. /*
  91289. ** An instance of the following structure keeps track of a mapping
  91290. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  91291. **
  91292. ** The VDBE cursor numbers are small integers contained in
  91293. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  91294. ** clause, the cursor numbers might not begin with 0 and they might
  91295. ** contain gaps in the numbering sequence. But we want to make maximum
  91296. ** use of the bits in our bitmasks. This structure provides a mapping
  91297. ** from the sparse cursor numbers into consecutive integers beginning
  91298. ** with 0.
  91299. **
  91300. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  91301. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  91302. **
  91303. ** For example, if the WHERE clause expression used these VDBE
  91304. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  91305. ** would map those cursor numbers into bits 0 through 5.
  91306. **
  91307. ** Note that the mapping is not necessarily ordered. In the example
  91308. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  91309. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  91310. ** does not really matter. What is important is that sparse cursor
  91311. ** numbers all get mapped into bit numbers that begin with 0 and contain
  91312. ** no gaps.
  91313. */
  91314. struct WhereMaskSet {
  91315. int n; /* Number of assigned cursor values */
  91316. int ix[BMS]; /* Cursor assigned to each bit */
  91317. };
  91318. /*
  91319. ** A WhereCost object records a lookup strategy and the estimated
  91320. ** cost of pursuing that strategy.
  91321. */
  91322. struct WhereCost {
  91323. WherePlan plan; /* The lookup strategy */
  91324. double rCost; /* Overall cost of pursuing this search strategy */
  91325. Bitmask used; /* Bitmask of cursors used by this plan */
  91326. };
  91327. /*
  91328. ** Bitmasks for the operators that indices are able to exploit. An
  91329. ** OR-ed combination of these values can be used when searching for
  91330. ** terms in the where clause.
  91331. */
  91332. #define WO_IN 0x001
  91333. #define WO_EQ 0x002
  91334. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  91335. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  91336. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  91337. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  91338. #define WO_MATCH 0x040
  91339. #define WO_ISNULL 0x080
  91340. #define WO_OR 0x100 /* Two or more OR-connected terms */
  91341. #define WO_AND 0x200 /* Two or more AND-connected terms */
  91342. #define WO_NOOP 0x800 /* This term does not restrict search space */
  91343. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  91344. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  91345. /*
  91346. ** Value for wsFlags returned by bestIndex() and stored in
  91347. ** WhereLevel.wsFlags. These flags determine which search
  91348. ** strategies are appropriate.
  91349. **
  91350. ** The least significant 12 bits is reserved as a mask for WO_ values above.
  91351. ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
  91352. ** But if the table is the right table of a left join, WhereLevel.wsFlags
  91353. ** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
  91354. ** the "op" parameter to findTerm when we are resolving equality constraints.
  91355. ** ISNULL constraints will then not be used on the right table of a left
  91356. ** join. Tickets #2177 and #2189.
  91357. */
  91358. #define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
  91359. #define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
  91360. #define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
  91361. #define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
  91362. #define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
  91363. #define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
  91364. #define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
  91365. #define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
  91366. #define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
  91367. #define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
  91368. #define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
  91369. #define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
  91370. #define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
  91371. #define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
  91372. #define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
  91373. #define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
  91374. #define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
  91375. #define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
  91376. #define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
  91377. /*
  91378. ** Initialize a preallocated WhereClause structure.
  91379. */
  91380. static void whereClauseInit(
  91381. WhereClause *pWC, /* The WhereClause to be initialized */
  91382. Parse *pParse, /* The parsing context */
  91383. WhereMaskSet *pMaskSet /* Mapping from table cursor numbers to bitmasks */
  91384. ){
  91385. pWC->pParse = pParse;
  91386. pWC->pMaskSet = pMaskSet;
  91387. pWC->nTerm = 0;
  91388. pWC->nSlot = ArraySize(pWC->aStatic);
  91389. pWC->a = pWC->aStatic;
  91390. pWC->vmask = 0;
  91391. }
  91392. /* Forward reference */
  91393. static void whereClauseClear(WhereClause*);
  91394. /*
  91395. ** Deallocate all memory associated with a WhereOrInfo object.
  91396. */
  91397. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  91398. whereClauseClear(&p->wc);
  91399. sqlite3DbFree(db, p);
  91400. }
  91401. /*
  91402. ** Deallocate all memory associated with a WhereAndInfo object.
  91403. */
  91404. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  91405. whereClauseClear(&p->wc);
  91406. sqlite3DbFree(db, p);
  91407. }
  91408. /*
  91409. ** Deallocate a WhereClause structure. The WhereClause structure
  91410. ** itself is not freed. This routine is the inverse of whereClauseInit().
  91411. */
  91412. static void whereClauseClear(WhereClause *pWC){
  91413. int i;
  91414. WhereTerm *a;
  91415. sqlite3 *db = pWC->pParse->db;
  91416. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  91417. if( a->wtFlags & TERM_DYNAMIC ){
  91418. sqlite3ExprDelete(db, a->pExpr);
  91419. }
  91420. if( a->wtFlags & TERM_ORINFO ){
  91421. whereOrInfoDelete(db, a->u.pOrInfo);
  91422. }else if( a->wtFlags & TERM_ANDINFO ){
  91423. whereAndInfoDelete(db, a->u.pAndInfo);
  91424. }
  91425. }
  91426. if( pWC->a!=pWC->aStatic ){
  91427. sqlite3DbFree(db, pWC->a);
  91428. }
  91429. }
  91430. /*
  91431. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  91432. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  91433. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  91434. ** 0 is returned if the new WhereTerm could not be added due to a memory
  91435. ** allocation error. The memory allocation failure will be recorded in
  91436. ** the db->mallocFailed flag so that higher-level functions can detect it.
  91437. **
  91438. ** This routine will increase the size of the pWC->a[] array as necessary.
  91439. **
  91440. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  91441. ** for freeing the expression p is assumed by the WhereClause object pWC.
  91442. ** This is true even if this routine fails to allocate a new WhereTerm.
  91443. **
  91444. ** WARNING: This routine might reallocate the space used to store
  91445. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  91446. ** calling this routine. Such pointers may be reinitialized by referencing
  91447. ** the pWC->a[] array.
  91448. */
  91449. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  91450. WhereTerm *pTerm;
  91451. int idx;
  91452. testcase( wtFlags & TERM_VIRTUAL ); /* EV: R-00211-15100 */
  91453. if( pWC->nTerm>=pWC->nSlot ){
  91454. WhereTerm *pOld = pWC->a;
  91455. sqlite3 *db = pWC->pParse->db;
  91456. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  91457. if( pWC->a==0 ){
  91458. if( wtFlags & TERM_DYNAMIC ){
  91459. sqlite3ExprDelete(db, p);
  91460. }
  91461. pWC->a = pOld;
  91462. return 0;
  91463. }
  91464. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  91465. if( pOld!=pWC->aStatic ){
  91466. sqlite3DbFree(db, pOld);
  91467. }
  91468. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  91469. }
  91470. pTerm = &pWC->a[idx = pWC->nTerm++];
  91471. pTerm->pExpr = p;
  91472. pTerm->wtFlags = wtFlags;
  91473. pTerm->pWC = pWC;
  91474. pTerm->iParent = -1;
  91475. return idx;
  91476. }
  91477. /*
  91478. ** This routine identifies subexpressions in the WHERE clause where
  91479. ** each subexpression is separated by the AND operator or some other
  91480. ** operator specified in the op parameter. The WhereClause structure
  91481. ** is filled with pointers to subexpressions. For example:
  91482. **
  91483. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  91484. ** \________/ \_______________/ \________________/
  91485. ** slot[0] slot[1] slot[2]
  91486. **
  91487. ** The original WHERE clause in pExpr is unaltered. All this routine
  91488. ** does is make slot[] entries point to substructure within pExpr.
  91489. **
  91490. ** In the previous sentence and in the diagram, "slot[]" refers to
  91491. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  91492. ** all terms of the WHERE clause.
  91493. */
  91494. static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
  91495. pWC->op = (u8)op;
  91496. if( pExpr==0 ) return;
  91497. if( pExpr->op!=op ){
  91498. whereClauseInsert(pWC, pExpr, 0);
  91499. }else{
  91500. whereSplit(pWC, pExpr->pLeft, op);
  91501. whereSplit(pWC, pExpr->pRight, op);
  91502. }
  91503. }
  91504. /*
  91505. ** Initialize an expression mask set (a WhereMaskSet object)
  91506. */
  91507. #define initMaskSet(P) memset(P, 0, sizeof(*P))
  91508. /*
  91509. ** Return the bitmask for the given cursor number. Return 0 if
  91510. ** iCursor is not in the set.
  91511. */
  91512. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  91513. int i;
  91514. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  91515. for(i=0; i<pMaskSet->n; i++){
  91516. if( pMaskSet->ix[i]==iCursor ){
  91517. return ((Bitmask)1)<<i;
  91518. }
  91519. }
  91520. return 0;
  91521. }
  91522. /*
  91523. ** Create a new mask for cursor iCursor.
  91524. **
  91525. ** There is one cursor per table in the FROM clause. The number of
  91526. ** tables in the FROM clause is limited by a test early in the
  91527. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  91528. ** array will never overflow.
  91529. */
  91530. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  91531. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  91532. pMaskSet->ix[pMaskSet->n++] = iCursor;
  91533. }
  91534. /*
  91535. ** This routine walks (recursively) an expression tree and generates
  91536. ** a bitmask indicating which tables are used in that expression
  91537. ** tree.
  91538. **
  91539. ** In order for this routine to work, the calling function must have
  91540. ** previously invoked sqlite3ResolveExprNames() on the expression. See
  91541. ** the header comment on that routine for additional information.
  91542. ** The sqlite3ResolveExprNames() routines looks for column names and
  91543. ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
  91544. ** the VDBE cursor number of the table. This routine just has to
  91545. ** translate the cursor numbers into bitmask values and OR all
  91546. ** the bitmasks together.
  91547. */
  91548. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  91549. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  91550. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  91551. Bitmask mask = 0;
  91552. if( p==0 ) return 0;
  91553. if( p->op==TK_COLUMN ){
  91554. mask = getMask(pMaskSet, p->iTable);
  91555. return mask;
  91556. }
  91557. mask = exprTableUsage(pMaskSet, p->pRight);
  91558. mask |= exprTableUsage(pMaskSet, p->pLeft);
  91559. if( ExprHasProperty(p, EP_xIsSelect) ){
  91560. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  91561. }else{
  91562. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  91563. }
  91564. return mask;
  91565. }
  91566. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  91567. int i;
  91568. Bitmask mask = 0;
  91569. if( pList ){
  91570. for(i=0; i<pList->nExpr; i++){
  91571. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  91572. }
  91573. }
  91574. return mask;
  91575. }
  91576. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  91577. Bitmask mask = 0;
  91578. while( pS ){
  91579. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  91580. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  91581. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  91582. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  91583. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  91584. pS = pS->pPrior;
  91585. }
  91586. return mask;
  91587. }
  91588. /*
  91589. ** Return TRUE if the given operator is one of the operators that is
  91590. ** allowed for an indexable WHERE clause term. The allowed operators are
  91591. ** "=", "<", ">", "<=", ">=", and "IN".
  91592. **
  91593. ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
  91594. ** of one of the following forms: column = expression column > expression
  91595. ** column >= expression column < expression column <= expression
  91596. ** expression = column expression > column expression >= column
  91597. ** expression < column expression <= column column IN
  91598. ** (expression-list) column IN (subquery) column IS NULL
  91599. */
  91600. static int allowedOp(int op){
  91601. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  91602. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  91603. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  91604. assert( TK_GE==TK_EQ+4 );
  91605. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  91606. }
  91607. /*
  91608. ** Swap two objects of type TYPE.
  91609. */
  91610. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  91611. /*
  91612. ** Commute a comparison operator. Expressions of the form "X op Y"
  91613. ** are converted into "Y op X".
  91614. **
  91615. ** If a collation sequence is associated with either the left or right
  91616. ** side of the comparison, it remains associated with the same side after
  91617. ** the commutation. So "Y collate NOCASE op X" becomes
  91618. ** "X collate NOCASE op Y". This is because any collation sequence on
  91619. ** the left hand side of a comparison overrides any collation sequence
  91620. ** attached to the right. For the same reason the EP_ExpCollate flag
  91621. ** is not commuted.
  91622. */
  91623. static void exprCommute(Parse *pParse, Expr *pExpr){
  91624. u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
  91625. u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
  91626. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  91627. pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  91628. pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  91629. SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
  91630. pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
  91631. pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
  91632. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  91633. if( pExpr->op>=TK_GT ){
  91634. assert( TK_LT==TK_GT+2 );
  91635. assert( TK_GE==TK_LE+2 );
  91636. assert( TK_GT>TK_EQ );
  91637. assert( TK_GT<TK_LE );
  91638. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  91639. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  91640. }
  91641. }
  91642. /*
  91643. ** Translate from TK_xx operator to WO_xx bitmask.
  91644. */
  91645. static u16 operatorMask(int op){
  91646. u16 c;
  91647. assert( allowedOp(op) );
  91648. if( op==TK_IN ){
  91649. c = WO_IN;
  91650. }else if( op==TK_ISNULL ){
  91651. c = WO_ISNULL;
  91652. }else{
  91653. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  91654. c = (u16)(WO_EQ<<(op-TK_EQ));
  91655. }
  91656. assert( op!=TK_ISNULL || c==WO_ISNULL );
  91657. assert( op!=TK_IN || c==WO_IN );
  91658. assert( op!=TK_EQ || c==WO_EQ );
  91659. assert( op!=TK_LT || c==WO_LT );
  91660. assert( op!=TK_LE || c==WO_LE );
  91661. assert( op!=TK_GT || c==WO_GT );
  91662. assert( op!=TK_GE || c==WO_GE );
  91663. return c;
  91664. }
  91665. /*
  91666. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  91667. ** where X is a reference to the iColumn of table iCur and <op> is one of
  91668. ** the WO_xx operator codes specified by the op parameter.
  91669. ** Return a pointer to the term. Return 0 if not found.
  91670. */
  91671. static WhereTerm *findTerm(
  91672. WhereClause *pWC, /* The WHERE clause to be searched */
  91673. int iCur, /* Cursor number of LHS */
  91674. int iColumn, /* Column number of LHS */
  91675. Bitmask notReady, /* RHS must not overlap with this mask */
  91676. u32 op, /* Mask of WO_xx values describing operator */
  91677. Index *pIdx /* Must be compatible with this index, if not NULL */
  91678. ){
  91679. WhereTerm *pTerm;
  91680. int k;
  91681. assert( iCur>=0 );
  91682. op &= WO_ALL;
  91683. for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
  91684. if( pTerm->leftCursor==iCur
  91685. && (pTerm->prereqRight & notReady)==0
  91686. && pTerm->u.leftColumn==iColumn
  91687. && (pTerm->eOperator & op)!=0
  91688. ){
  91689. if( pIdx && pTerm->eOperator!=WO_ISNULL ){
  91690. Expr *pX = pTerm->pExpr;
  91691. CollSeq *pColl;
  91692. char idxaff;
  91693. int j;
  91694. Parse *pParse = pWC->pParse;
  91695. idxaff = pIdx->pTable->aCol[iColumn].affinity;
  91696. if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
  91697. /* Figure out the collation sequence required from an index for
  91698. ** it to be useful for optimising expression pX. Store this
  91699. ** value in variable pColl.
  91700. */
  91701. assert(pX->pLeft);
  91702. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  91703. assert(pColl || pParse->nErr);
  91704. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  91705. if( NEVER(j>=pIdx->nColumn) ) return 0;
  91706. }
  91707. if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
  91708. }
  91709. return pTerm;
  91710. }
  91711. }
  91712. return 0;
  91713. }
  91714. /* Forward reference */
  91715. static void exprAnalyze(SrcList*, WhereClause*, int);
  91716. /*
  91717. ** Call exprAnalyze on all terms in a WHERE clause.
  91718. **
  91719. **
  91720. */
  91721. static void exprAnalyzeAll(
  91722. SrcList *pTabList, /* the FROM clause */
  91723. WhereClause *pWC /* the WHERE clause to be analyzed */
  91724. ){
  91725. int i;
  91726. for(i=pWC->nTerm-1; i>=0; i--){
  91727. exprAnalyze(pTabList, pWC, i);
  91728. }
  91729. }
  91730. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  91731. /*
  91732. ** Check to see if the given expression is a LIKE or GLOB operator that
  91733. ** can be optimized using inequality constraints. Return TRUE if it is
  91734. ** so and false if not.
  91735. **
  91736. ** In order for the operator to be optimizible, the RHS must be a string
  91737. ** literal that does not begin with a wildcard.
  91738. */
  91739. static int isLikeOrGlob(
  91740. Parse *pParse, /* Parsing and code generating context */
  91741. Expr *pExpr, /* Test this expression */
  91742. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  91743. int *pisComplete, /* True if the only wildcard is % in the last character */
  91744. int *pnoCase /* True if uppercase is equivalent to lowercase */
  91745. ){
  91746. const char *z = 0; /* String on RHS of LIKE operator */
  91747. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  91748. ExprList *pList; /* List of operands to the LIKE operator */
  91749. int c; /* One character in z[] */
  91750. int cnt; /* Number of non-wildcard prefix characters */
  91751. char wc[3]; /* Wildcard characters */
  91752. sqlite3 *db = pParse->db; /* Database connection */
  91753. sqlite3_value *pVal = 0;
  91754. int op; /* Opcode of pRight */
  91755. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  91756. return 0;
  91757. }
  91758. #ifdef SQLITE_EBCDIC
  91759. if( *pnoCase ) return 0;
  91760. #endif
  91761. pList = pExpr->x.pList;
  91762. pLeft = pList->a[1].pExpr;
  91763. if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
  91764. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  91765. ** be the name of an indexed column with TEXT affinity. */
  91766. return 0;
  91767. }
  91768. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  91769. pRight = pList->a[0].pExpr;
  91770. op = pRight->op;
  91771. if( op==TK_REGISTER ){
  91772. op = pRight->op2;
  91773. }
  91774. if( op==TK_VARIABLE ){
  91775. Vdbe *pReprepare = pParse->pReprepare;
  91776. int iCol = pRight->iColumn;
  91777. pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
  91778. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  91779. z = (char *)sqlite3_value_text(pVal);
  91780. }
  91781. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
  91782. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  91783. }else if( op==TK_STRING ){
  91784. z = pRight->u.zToken;
  91785. }
  91786. if( z ){
  91787. cnt = 0;
  91788. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  91789. cnt++;
  91790. }
  91791. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  91792. Expr *pPrefix;
  91793. *pisComplete = c==wc[0] && z[cnt+1]==0;
  91794. pPrefix = sqlite3Expr(db, TK_STRING, z);
  91795. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  91796. *ppPrefix = pPrefix;
  91797. if( op==TK_VARIABLE ){
  91798. Vdbe *v = pParse->pVdbe;
  91799. sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
  91800. if( *pisComplete && pRight->u.zToken[1] ){
  91801. /* If the rhs of the LIKE expression is a variable, and the current
  91802. ** value of the variable means there is no need to invoke the LIKE
  91803. ** function, then no OP_Variable will be added to the program.
  91804. ** This causes problems for the sqlite3_bind_parameter_name()
  91805. ** API. To workaround them, add a dummy OP_Variable here.
  91806. */
  91807. int r1 = sqlite3GetTempReg(pParse);
  91808. sqlite3ExprCodeTarget(pParse, pRight, r1);
  91809. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  91810. sqlite3ReleaseTempReg(pParse, r1);
  91811. }
  91812. }
  91813. }else{
  91814. z = 0;
  91815. }
  91816. }
  91817. sqlite3ValueFree(pVal);
  91818. return (z!=0);
  91819. }
  91820. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  91821. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91822. /*
  91823. ** Check to see if the given expression is of the form
  91824. **
  91825. ** column MATCH expr
  91826. **
  91827. ** If it is then return TRUE. If not, return FALSE.
  91828. */
  91829. static int isMatchOfColumn(
  91830. Expr *pExpr /* Test this expression */
  91831. ){
  91832. ExprList *pList;
  91833. if( pExpr->op!=TK_FUNCTION ){
  91834. return 0;
  91835. }
  91836. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  91837. return 0;
  91838. }
  91839. pList = pExpr->x.pList;
  91840. if( pList->nExpr!=2 ){
  91841. return 0;
  91842. }
  91843. if( pList->a[1].pExpr->op != TK_COLUMN ){
  91844. return 0;
  91845. }
  91846. return 1;
  91847. }
  91848. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  91849. /*
  91850. ** If the pBase expression originated in the ON or USING clause of
  91851. ** a join, then transfer the appropriate markings over to derived.
  91852. */
  91853. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  91854. pDerived->flags |= pBase->flags & EP_FromJoin;
  91855. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  91856. }
  91857. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  91858. /*
  91859. ** Analyze a term that consists of two or more OR-connected
  91860. ** subterms. So in:
  91861. **
  91862. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  91863. ** ^^^^^^^^^^^^^^^^^^^^
  91864. **
  91865. ** This routine analyzes terms such as the middle term in the above example.
  91866. ** A WhereOrTerm object is computed and attached to the term under
  91867. ** analysis, regardless of the outcome of the analysis. Hence:
  91868. **
  91869. ** WhereTerm.wtFlags |= TERM_ORINFO
  91870. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  91871. **
  91872. ** The term being analyzed must have two or more of OR-connected subterms.
  91873. ** A single subterm might be a set of AND-connected sub-subterms.
  91874. ** Examples of terms under analysis:
  91875. **
  91876. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  91877. ** (B) x=expr1 OR expr2=x OR x=expr3
  91878. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  91879. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  91880. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  91881. **
  91882. ** CASE 1:
  91883. **
  91884. ** If all subterms are of the form T.C=expr for some single column of C
  91885. ** a single table T (as shown in example B above) then create a new virtual
  91886. ** term that is an equivalent IN expression. In other words, if the term
  91887. ** being analyzed is:
  91888. **
  91889. ** x = expr1 OR expr2 = x OR x = expr3
  91890. **
  91891. ** then create a new virtual term like this:
  91892. **
  91893. ** x IN (expr1,expr2,expr3)
  91894. **
  91895. ** CASE 2:
  91896. **
  91897. ** If all subterms are indexable by a single table T, then set
  91898. **
  91899. ** WhereTerm.eOperator = WO_OR
  91900. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  91901. **
  91902. ** A subterm is "indexable" if it is of the form
  91903. ** "T.C <op> <expr>" where C is any column of table T and
  91904. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  91905. ** A subterm is also indexable if it is an AND of two or more
  91906. ** subsubterms at least one of which is indexable. Indexable AND
  91907. ** subterms have their eOperator set to WO_AND and they have
  91908. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  91909. **
  91910. ** From another point of view, "indexable" means that the subterm could
  91911. ** potentially be used with an index if an appropriate index exists.
  91912. ** This analysis does not consider whether or not the index exists; that
  91913. ** is something the bestIndex() routine will determine. This analysis
  91914. ** only looks at whether subterms appropriate for indexing exist.
  91915. **
  91916. ** All examples A through E above all satisfy case 2. But if a term
  91917. ** also statisfies case 1 (such as B) we know that the optimizer will
  91918. ** always prefer case 1, so in that case we pretend that case 2 is not
  91919. ** satisfied.
  91920. **
  91921. ** It might be the case that multiple tables are indexable. For example,
  91922. ** (E) above is indexable on tables P, Q, and R.
  91923. **
  91924. ** Terms that satisfy case 2 are candidates for lookup by using
  91925. ** separate indices to find rowids for each subterm and composing
  91926. ** the union of all rowids using a RowSet object. This is similar
  91927. ** to "bitmap indices" in other database engines.
  91928. **
  91929. ** OTHERWISE:
  91930. **
  91931. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  91932. ** zero. This term is not useful for search.
  91933. */
  91934. static void exprAnalyzeOrTerm(
  91935. SrcList *pSrc, /* the FROM clause */
  91936. WhereClause *pWC, /* the complete WHERE clause */
  91937. int idxTerm /* Index of the OR-term to be analyzed */
  91938. ){
  91939. Parse *pParse = pWC->pParse; /* Parser context */
  91940. sqlite3 *db = pParse->db; /* Database connection */
  91941. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  91942. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  91943. WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
  91944. int i; /* Loop counters */
  91945. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  91946. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  91947. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  91948. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  91949. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  91950. /*
  91951. ** Break the OR clause into its separate subterms. The subterms are
  91952. ** stored in a WhereClause structure containing within the WhereOrInfo
  91953. ** object that is attached to the original OR clause term.
  91954. */
  91955. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  91956. assert( pExpr->op==TK_OR );
  91957. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  91958. if( pOrInfo==0 ) return;
  91959. pTerm->wtFlags |= TERM_ORINFO;
  91960. pOrWc = &pOrInfo->wc;
  91961. whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
  91962. whereSplit(pOrWc, pExpr, TK_OR);
  91963. exprAnalyzeAll(pSrc, pOrWc);
  91964. if( db->mallocFailed ) return;
  91965. assert( pOrWc->nTerm>=2 );
  91966. /*
  91967. ** Compute the set of tables that might satisfy cases 1 or 2.
  91968. */
  91969. indexable = ~(Bitmask)0;
  91970. chngToIN = ~(pWC->vmask);
  91971. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  91972. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  91973. WhereAndInfo *pAndInfo;
  91974. assert( pOrTerm->eOperator==0 );
  91975. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  91976. chngToIN = 0;
  91977. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  91978. if( pAndInfo ){
  91979. WhereClause *pAndWC;
  91980. WhereTerm *pAndTerm;
  91981. int j;
  91982. Bitmask b = 0;
  91983. pOrTerm->u.pAndInfo = pAndInfo;
  91984. pOrTerm->wtFlags |= TERM_ANDINFO;
  91985. pOrTerm->eOperator = WO_AND;
  91986. pAndWC = &pAndInfo->wc;
  91987. whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
  91988. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  91989. exprAnalyzeAll(pSrc, pAndWC);
  91990. testcase( db->mallocFailed );
  91991. if( !db->mallocFailed ){
  91992. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  91993. assert( pAndTerm->pExpr );
  91994. if( allowedOp(pAndTerm->pExpr->op) ){
  91995. b |= getMask(pMaskSet, pAndTerm->leftCursor);
  91996. }
  91997. }
  91998. }
  91999. indexable &= b;
  92000. }
  92001. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  92002. /* Skip this term for now. We revisit it when we process the
  92003. ** corresponding TERM_VIRTUAL term */
  92004. }else{
  92005. Bitmask b;
  92006. b = getMask(pMaskSet, pOrTerm->leftCursor);
  92007. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  92008. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  92009. b |= getMask(pMaskSet, pOther->leftCursor);
  92010. }
  92011. indexable &= b;
  92012. if( pOrTerm->eOperator!=WO_EQ ){
  92013. chngToIN = 0;
  92014. }else{
  92015. chngToIN &= b;
  92016. }
  92017. }
  92018. }
  92019. /*
  92020. ** Record the set of tables that satisfy case 2. The set might be
  92021. ** empty.
  92022. */
  92023. pOrInfo->indexable = indexable;
  92024. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  92025. /*
  92026. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  92027. ** we have to do some additional checking to see if case 1 really
  92028. ** is satisfied.
  92029. **
  92030. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  92031. ** that there is no possibility of transforming the OR clause into an
  92032. ** IN operator because one or more terms in the OR clause contain
  92033. ** something other than == on a column in the single table. The 1-bit
  92034. ** case means that every term of the OR clause is of the form
  92035. ** "table.column=expr" for some single table. The one bit that is set
  92036. ** will correspond to the common table. We still need to check to make
  92037. ** sure the same column is used on all terms. The 2-bit case is when
  92038. ** the all terms are of the form "table1.column=table2.column". It
  92039. ** might be possible to form an IN operator with either table1.column
  92040. ** or table2.column as the LHS if either is common to every term of
  92041. ** the OR clause.
  92042. **
  92043. ** Note that terms of the form "table.column1=table.column2" (the
  92044. ** same table on both sizes of the ==) cannot be optimized.
  92045. */
  92046. if( chngToIN ){
  92047. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  92048. int iColumn = -1; /* Column index on lhs of IN operator */
  92049. int iCursor = -1; /* Table cursor common to all terms */
  92050. int j = 0; /* Loop counter */
  92051. /* Search for a table and column that appears on one side or the
  92052. ** other of the == operator in every subterm. That table and column
  92053. ** will be recorded in iCursor and iColumn. There might not be any
  92054. ** such table and column. Set okToChngToIN if an appropriate table
  92055. ** and column is found but leave okToChngToIN false if not found.
  92056. */
  92057. for(j=0; j<2 && !okToChngToIN; j++){
  92058. pOrTerm = pOrWc->a;
  92059. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  92060. assert( pOrTerm->eOperator==WO_EQ );
  92061. pOrTerm->wtFlags &= ~TERM_OR_OK;
  92062. if( pOrTerm->leftCursor==iCursor ){
  92063. /* This is the 2-bit case and we are on the second iteration and
  92064. ** current term is from the first iteration. So skip this term. */
  92065. assert( j==1 );
  92066. continue;
  92067. }
  92068. if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
  92069. /* This term must be of the form t1.a==t2.b where t2 is in the
  92070. ** chngToIN set but t1 is not. This term will be either preceeded
  92071. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  92072. ** and use its inversion. */
  92073. testcase( pOrTerm->wtFlags & TERM_COPIED );
  92074. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  92075. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  92076. continue;
  92077. }
  92078. iColumn = pOrTerm->u.leftColumn;
  92079. iCursor = pOrTerm->leftCursor;
  92080. break;
  92081. }
  92082. if( i<0 ){
  92083. /* No candidate table+column was found. This can only occur
  92084. ** on the second iteration */
  92085. assert( j==1 );
  92086. assert( (chngToIN&(chngToIN-1))==0 );
  92087. assert( chngToIN==getMask(pMaskSet, iCursor) );
  92088. break;
  92089. }
  92090. testcase( j==1 );
  92091. /* We have found a candidate table and column. Check to see if that
  92092. ** table and column is common to every term in the OR clause */
  92093. okToChngToIN = 1;
  92094. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  92095. assert( pOrTerm->eOperator==WO_EQ );
  92096. if( pOrTerm->leftCursor!=iCursor ){
  92097. pOrTerm->wtFlags &= ~TERM_OR_OK;
  92098. }else if( pOrTerm->u.leftColumn!=iColumn ){
  92099. okToChngToIN = 0;
  92100. }else{
  92101. int affLeft, affRight;
  92102. /* If the right-hand side is also a column, then the affinities
  92103. ** of both right and left sides must be such that no type
  92104. ** conversions are required on the right. (Ticket #2249)
  92105. */
  92106. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  92107. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  92108. if( affRight!=0 && affRight!=affLeft ){
  92109. okToChngToIN = 0;
  92110. }else{
  92111. pOrTerm->wtFlags |= TERM_OR_OK;
  92112. }
  92113. }
  92114. }
  92115. }
  92116. /* At this point, okToChngToIN is true if original pTerm satisfies
  92117. ** case 1. In that case, construct a new virtual term that is
  92118. ** pTerm converted into an IN operator.
  92119. **
  92120. ** EV: R-00211-15100
  92121. */
  92122. if( okToChngToIN ){
  92123. Expr *pDup; /* A transient duplicate expression */
  92124. ExprList *pList = 0; /* The RHS of the IN operator */
  92125. Expr *pLeft = 0; /* The LHS of the IN operator */
  92126. Expr *pNew; /* The complete IN operator */
  92127. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  92128. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  92129. assert( pOrTerm->eOperator==WO_EQ );
  92130. assert( pOrTerm->leftCursor==iCursor );
  92131. assert( pOrTerm->u.leftColumn==iColumn );
  92132. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  92133. pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
  92134. pLeft = pOrTerm->pExpr->pLeft;
  92135. }
  92136. assert( pLeft!=0 );
  92137. pDup = sqlite3ExprDup(db, pLeft, 0);
  92138. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  92139. if( pNew ){
  92140. int idxNew;
  92141. transferJoinMarkings(pNew, pExpr);
  92142. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  92143. pNew->x.pList = pList;
  92144. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  92145. testcase( idxNew==0 );
  92146. exprAnalyze(pSrc, pWC, idxNew);
  92147. pTerm = &pWC->a[idxTerm];
  92148. pWC->a[idxNew].iParent = idxTerm;
  92149. pTerm->nChild = 1;
  92150. }else{
  92151. sqlite3ExprListDelete(db, pList);
  92152. }
  92153. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  92154. }
  92155. }
  92156. }
  92157. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  92158. /*
  92159. ** The input to this routine is an WhereTerm structure with only the
  92160. ** "pExpr" field filled in. The job of this routine is to analyze the
  92161. ** subexpression and populate all the other fields of the WhereTerm
  92162. ** structure.
  92163. **
  92164. ** If the expression is of the form "<expr> <op> X" it gets commuted
  92165. ** to the standard form of "X <op> <expr>".
  92166. **
  92167. ** If the expression is of the form "X <op> Y" where both X and Y are
  92168. ** columns, then the original expression is unchanged and a new virtual
  92169. ** term of the form "Y <op> X" is added to the WHERE clause and
  92170. ** analyzed separately. The original term is marked with TERM_COPIED
  92171. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  92172. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  92173. ** is a commuted copy of a prior term.) The original term has nChild=1
  92174. ** and the copy has idxParent set to the index of the original term.
  92175. */
  92176. static void exprAnalyze(
  92177. SrcList *pSrc, /* the FROM clause */
  92178. WhereClause *pWC, /* the WHERE clause */
  92179. int idxTerm /* Index of the term to be analyzed */
  92180. ){
  92181. WhereTerm *pTerm; /* The term to be analyzed */
  92182. WhereMaskSet *pMaskSet; /* Set of table index masks */
  92183. Expr *pExpr; /* The expression to be analyzed */
  92184. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  92185. Bitmask prereqAll; /* Prerequesites of pExpr */
  92186. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  92187. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  92188. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  92189. int noCase = 0; /* LIKE/GLOB distinguishes case */
  92190. int op; /* Top-level operator. pExpr->op */
  92191. Parse *pParse = pWC->pParse; /* Parsing context */
  92192. sqlite3 *db = pParse->db; /* Database connection */
  92193. if( db->mallocFailed ){
  92194. return;
  92195. }
  92196. pTerm = &pWC->a[idxTerm];
  92197. pMaskSet = pWC->pMaskSet;
  92198. pExpr = pTerm->pExpr;
  92199. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  92200. op = pExpr->op;
  92201. if( op==TK_IN ){
  92202. assert( pExpr->pRight==0 );
  92203. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  92204. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  92205. }else{
  92206. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  92207. }
  92208. }else if( op==TK_ISNULL ){
  92209. pTerm->prereqRight = 0;
  92210. }else{
  92211. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  92212. }
  92213. prereqAll = exprTableUsage(pMaskSet, pExpr);
  92214. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  92215. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  92216. prereqAll |= x;
  92217. extraRight = x-1; /* ON clause terms may not be used with an index
  92218. ** on left table of a LEFT JOIN. Ticket #3015 */
  92219. }
  92220. pTerm->prereqAll = prereqAll;
  92221. pTerm->leftCursor = -1;
  92222. pTerm->iParent = -1;
  92223. pTerm->eOperator = 0;
  92224. if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
  92225. Expr *pLeft = pExpr->pLeft;
  92226. Expr *pRight = pExpr->pRight;
  92227. if( pLeft->op==TK_COLUMN ){
  92228. pTerm->leftCursor = pLeft->iTable;
  92229. pTerm->u.leftColumn = pLeft->iColumn;
  92230. pTerm->eOperator = operatorMask(op);
  92231. }
  92232. if( pRight && pRight->op==TK_COLUMN ){
  92233. WhereTerm *pNew;
  92234. Expr *pDup;
  92235. if( pTerm->leftCursor>=0 ){
  92236. int idxNew;
  92237. pDup = sqlite3ExprDup(db, pExpr, 0);
  92238. if( db->mallocFailed ){
  92239. sqlite3ExprDelete(db, pDup);
  92240. return;
  92241. }
  92242. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  92243. if( idxNew==0 ) return;
  92244. pNew = &pWC->a[idxNew];
  92245. pNew->iParent = idxTerm;
  92246. pTerm = &pWC->a[idxTerm];
  92247. pTerm->nChild = 1;
  92248. pTerm->wtFlags |= TERM_COPIED;
  92249. }else{
  92250. pDup = pExpr;
  92251. pNew = pTerm;
  92252. }
  92253. exprCommute(pParse, pDup);
  92254. pLeft = pDup->pLeft;
  92255. pNew->leftCursor = pLeft->iTable;
  92256. pNew->u.leftColumn = pLeft->iColumn;
  92257. testcase( (prereqLeft | extraRight) != prereqLeft );
  92258. pNew->prereqRight = prereqLeft | extraRight;
  92259. pNew->prereqAll = prereqAll;
  92260. pNew->eOperator = operatorMask(pDup->op);
  92261. }
  92262. }
  92263. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  92264. /* If a term is the BETWEEN operator, create two new virtual terms
  92265. ** that define the range that the BETWEEN implements. For example:
  92266. **
  92267. ** a BETWEEN b AND c
  92268. **
  92269. ** is converted into:
  92270. **
  92271. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  92272. **
  92273. ** The two new terms are added onto the end of the WhereClause object.
  92274. ** The new terms are "dynamic" and are children of the original BETWEEN
  92275. ** term. That means that if the BETWEEN term is coded, the children are
  92276. ** skipped. Or, if the children are satisfied by an index, the original
  92277. ** BETWEEN term is skipped.
  92278. */
  92279. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  92280. ExprList *pList = pExpr->x.pList;
  92281. int i;
  92282. static const u8 ops[] = {TK_GE, TK_LE};
  92283. assert( pList!=0 );
  92284. assert( pList->nExpr==2 );
  92285. for(i=0; i<2; i++){
  92286. Expr *pNewExpr;
  92287. int idxNew;
  92288. pNewExpr = sqlite3PExpr(pParse, ops[i],
  92289. sqlite3ExprDup(db, pExpr->pLeft, 0),
  92290. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  92291. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  92292. testcase( idxNew==0 );
  92293. exprAnalyze(pSrc, pWC, idxNew);
  92294. pTerm = &pWC->a[idxTerm];
  92295. pWC->a[idxNew].iParent = idxTerm;
  92296. }
  92297. pTerm->nChild = 2;
  92298. }
  92299. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  92300. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  92301. /* Analyze a term that is composed of two or more subterms connected by
  92302. ** an OR operator.
  92303. */
  92304. else if( pExpr->op==TK_OR ){
  92305. assert( pWC->op==TK_AND );
  92306. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  92307. pTerm = &pWC->a[idxTerm];
  92308. }
  92309. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  92310. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  92311. /* Add constraints to reduce the search space on a LIKE or GLOB
  92312. ** operator.
  92313. **
  92314. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  92315. **
  92316. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  92317. **
  92318. ** The last character of the prefix "abc" is incremented to form the
  92319. ** termination condition "abd".
  92320. */
  92321. if( pWC->op==TK_AND
  92322. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  92323. ){
  92324. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  92325. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  92326. Expr *pNewExpr1;
  92327. Expr *pNewExpr2;
  92328. int idxNew1;
  92329. int idxNew2;
  92330. CollSeq *pColl; /* Collating sequence to use */
  92331. pLeft = pExpr->x.pList->a[1].pExpr;
  92332. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  92333. if( !db->mallocFailed ){
  92334. u8 c, *pC; /* Last character before the first wildcard */
  92335. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  92336. c = *pC;
  92337. if( noCase ){
  92338. /* The point is to increment the last character before the first
  92339. ** wildcard. But if we increment '@', that will push it into the
  92340. ** alphabetic range where case conversions will mess up the
  92341. ** inequality. To avoid this, make sure to also run the full
  92342. ** LIKE on all candidate expressions by clearing the isComplete flag
  92343. */
  92344. if( c=='A'-1 ) isComplete = 0; /* EV: R-64339-08207 */
  92345. c = sqlite3UpperToLower[c];
  92346. }
  92347. *pC = c + 1;
  92348. }
  92349. pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
  92350. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  92351. sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
  92352. pStr1, 0);
  92353. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  92354. testcase( idxNew1==0 );
  92355. exprAnalyze(pSrc, pWC, idxNew1);
  92356. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  92357. sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
  92358. pStr2, 0);
  92359. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  92360. testcase( idxNew2==0 );
  92361. exprAnalyze(pSrc, pWC, idxNew2);
  92362. pTerm = &pWC->a[idxTerm];
  92363. if( isComplete ){
  92364. pWC->a[idxNew1].iParent = idxTerm;
  92365. pWC->a[idxNew2].iParent = idxTerm;
  92366. pTerm->nChild = 2;
  92367. }
  92368. }
  92369. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  92370. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92371. /* Add a WO_MATCH auxiliary term to the constraint set if the
  92372. ** current expression is of the form: column MATCH expr.
  92373. ** This information is used by the xBestIndex methods of
  92374. ** virtual tables. The native query optimizer does not attempt
  92375. ** to do anything with MATCH functions.
  92376. */
  92377. if( isMatchOfColumn(pExpr) ){
  92378. int idxNew;
  92379. Expr *pRight, *pLeft;
  92380. WhereTerm *pNewTerm;
  92381. Bitmask prereqColumn, prereqExpr;
  92382. pRight = pExpr->x.pList->a[0].pExpr;
  92383. pLeft = pExpr->x.pList->a[1].pExpr;
  92384. prereqExpr = exprTableUsage(pMaskSet, pRight);
  92385. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  92386. if( (prereqExpr & prereqColumn)==0 ){
  92387. Expr *pNewExpr;
  92388. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  92389. 0, sqlite3ExprDup(db, pRight, 0), 0);
  92390. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  92391. testcase( idxNew==0 );
  92392. pNewTerm = &pWC->a[idxNew];
  92393. pNewTerm->prereqRight = prereqExpr;
  92394. pNewTerm->leftCursor = pLeft->iTable;
  92395. pNewTerm->u.leftColumn = pLeft->iColumn;
  92396. pNewTerm->eOperator = WO_MATCH;
  92397. pNewTerm->iParent = idxTerm;
  92398. pTerm = &pWC->a[idxTerm];
  92399. pTerm->nChild = 1;
  92400. pTerm->wtFlags |= TERM_COPIED;
  92401. pNewTerm->prereqAll = pTerm->prereqAll;
  92402. }
  92403. }
  92404. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  92405. #ifdef SQLITE_ENABLE_STAT2
  92406. /* When sqlite_stat2 histogram data is available an operator of the
  92407. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  92408. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  92409. ** virtual term of that form.
  92410. **
  92411. ** Note that the virtual term must be tagged with TERM_VNULL. This
  92412. ** TERM_VNULL tag will suppress the not-null check at the beginning
  92413. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  92414. ** the start of the loop will prevent any results from being returned.
  92415. */
  92416. if( pExpr->op==TK_NOTNULL
  92417. && pExpr->pLeft->op==TK_COLUMN
  92418. && pExpr->pLeft->iColumn>=0
  92419. ){
  92420. Expr *pNewExpr;
  92421. Expr *pLeft = pExpr->pLeft;
  92422. int idxNew;
  92423. WhereTerm *pNewTerm;
  92424. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  92425. sqlite3ExprDup(db, pLeft, 0),
  92426. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  92427. idxNew = whereClauseInsert(pWC, pNewExpr,
  92428. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  92429. if( idxNew ){
  92430. pNewTerm = &pWC->a[idxNew];
  92431. pNewTerm->prereqRight = 0;
  92432. pNewTerm->leftCursor = pLeft->iTable;
  92433. pNewTerm->u.leftColumn = pLeft->iColumn;
  92434. pNewTerm->eOperator = WO_GT;
  92435. pNewTerm->iParent = idxTerm;
  92436. pTerm = &pWC->a[idxTerm];
  92437. pTerm->nChild = 1;
  92438. pTerm->wtFlags |= TERM_COPIED;
  92439. pNewTerm->prereqAll = pTerm->prereqAll;
  92440. }
  92441. }
  92442. #endif /* SQLITE_ENABLE_STAT2 */
  92443. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  92444. ** an index for tables to the left of the join.
  92445. */
  92446. pTerm->prereqRight |= extraRight;
  92447. }
  92448. /*
  92449. ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
  92450. ** a reference to any table other than the iBase table.
  92451. */
  92452. static int referencesOtherTables(
  92453. ExprList *pList, /* Search expressions in ths list */
  92454. WhereMaskSet *pMaskSet, /* Mapping from tables to bitmaps */
  92455. int iFirst, /* Be searching with the iFirst-th expression */
  92456. int iBase /* Ignore references to this table */
  92457. ){
  92458. Bitmask allowed = ~getMask(pMaskSet, iBase);
  92459. while( iFirst<pList->nExpr ){
  92460. if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
  92461. return 1;
  92462. }
  92463. }
  92464. return 0;
  92465. }
  92466. /*
  92467. ** This routine decides if pIdx can be used to satisfy the ORDER BY
  92468. ** clause. If it can, it returns 1. If pIdx cannot satisfy the
  92469. ** ORDER BY clause, this routine returns 0.
  92470. **
  92471. ** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
  92472. ** left-most table in the FROM clause of that same SELECT statement and
  92473. ** the table has a cursor number of "base". pIdx is an index on pTab.
  92474. **
  92475. ** nEqCol is the number of columns of pIdx that are used as equality
  92476. ** constraints. Any of these columns may be missing from the ORDER BY
  92477. ** clause and the match can still be a success.
  92478. **
  92479. ** All terms of the ORDER BY that match against the index must be either
  92480. ** ASC or DESC. (Terms of the ORDER BY clause past the end of a UNIQUE
  92481. ** index do not need to satisfy this constraint.) The *pbRev value is
  92482. ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
  92483. ** the ORDER BY clause is all ASC.
  92484. */
  92485. static int isSortingIndex(
  92486. Parse *pParse, /* Parsing context */
  92487. WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
  92488. Index *pIdx, /* The index we are testing */
  92489. int base, /* Cursor number for the table to be sorted */
  92490. ExprList *pOrderBy, /* The ORDER BY clause */
  92491. int nEqCol, /* Number of index columns with == constraints */
  92492. int wsFlags, /* Index usages flags */
  92493. int *pbRev /* Set to 1 if ORDER BY is DESC */
  92494. ){
  92495. int i, j; /* Loop counters */
  92496. int sortOrder = 0; /* XOR of index and ORDER BY sort direction */
  92497. int nTerm; /* Number of ORDER BY terms */
  92498. struct ExprList_item *pTerm; /* A term of the ORDER BY clause */
  92499. sqlite3 *db = pParse->db;
  92500. assert( pOrderBy!=0 );
  92501. nTerm = pOrderBy->nExpr;
  92502. assert( nTerm>0 );
  92503. /* Argument pIdx must either point to a 'real' named index structure,
  92504. ** or an index structure allocated on the stack by bestBtreeIndex() to
  92505. ** represent the rowid index that is part of every table. */
  92506. assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
  92507. /* Match terms of the ORDER BY clause against columns of
  92508. ** the index.
  92509. **
  92510. ** Note that indices have pIdx->nColumn regular columns plus
  92511. ** one additional column containing the rowid. The rowid column
  92512. ** of the index is also allowed to match against the ORDER BY
  92513. ** clause.
  92514. */
  92515. for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
  92516. Expr *pExpr; /* The expression of the ORDER BY pTerm */
  92517. CollSeq *pColl; /* The collating sequence of pExpr */
  92518. int termSortOrder; /* Sort order for this term */
  92519. int iColumn; /* The i-th column of the index. -1 for rowid */
  92520. int iSortOrder; /* 1 for DESC, 0 for ASC on the i-th index term */
  92521. const char *zColl; /* Name of the collating sequence for i-th index term */
  92522. pExpr = pTerm->pExpr;
  92523. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
  92524. /* Can not use an index sort on anything that is not a column in the
  92525. ** left-most table of the FROM clause */
  92526. break;
  92527. }
  92528. pColl = sqlite3ExprCollSeq(pParse, pExpr);
  92529. if( !pColl ){
  92530. pColl = db->pDfltColl;
  92531. }
  92532. if( pIdx->zName && i<pIdx->nColumn ){
  92533. iColumn = pIdx->aiColumn[i];
  92534. if( iColumn==pIdx->pTable->iPKey ){
  92535. iColumn = -1;
  92536. }
  92537. iSortOrder = pIdx->aSortOrder[i];
  92538. zColl = pIdx->azColl[i];
  92539. }else{
  92540. iColumn = -1;
  92541. iSortOrder = 0;
  92542. zColl = pColl->zName;
  92543. }
  92544. if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
  92545. /* Term j of the ORDER BY clause does not match column i of the index */
  92546. if( i<nEqCol ){
  92547. /* If an index column that is constrained by == fails to match an
  92548. ** ORDER BY term, that is OK. Just ignore that column of the index
  92549. */
  92550. continue;
  92551. }else if( i==pIdx->nColumn ){
  92552. /* Index column i is the rowid. All other terms match. */
  92553. break;
  92554. }else{
  92555. /* If an index column fails to match and is not constrained by ==
  92556. ** then the index cannot satisfy the ORDER BY constraint.
  92557. */
  92558. return 0;
  92559. }
  92560. }
  92561. assert( pIdx->aSortOrder!=0 || iColumn==-1 );
  92562. assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
  92563. assert( iSortOrder==0 || iSortOrder==1 );
  92564. termSortOrder = iSortOrder ^ pTerm->sortOrder;
  92565. if( i>nEqCol ){
  92566. if( termSortOrder!=sortOrder ){
  92567. /* Indices can only be used if all ORDER BY terms past the
  92568. ** equality constraints are all either DESC or ASC. */
  92569. return 0;
  92570. }
  92571. }else{
  92572. sortOrder = termSortOrder;
  92573. }
  92574. j++;
  92575. pTerm++;
  92576. if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
  92577. /* If the indexed column is the primary key and everything matches
  92578. ** so far and none of the ORDER BY terms to the right reference other
  92579. ** tables in the join, then we are assured that the index can be used
  92580. ** to sort because the primary key is unique and so none of the other
  92581. ** columns will make any difference
  92582. */
  92583. j = nTerm;
  92584. }
  92585. }
  92586. *pbRev = sortOrder!=0;
  92587. if( j>=nTerm ){
  92588. /* All terms of the ORDER BY clause are covered by this index so
  92589. ** this index can be used for sorting. */
  92590. return 1;
  92591. }
  92592. if( pIdx->onError!=OE_None && i==pIdx->nColumn
  92593. && (wsFlags & WHERE_COLUMN_NULL)==0
  92594. && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
  92595. /* All terms of this index match some prefix of the ORDER BY clause
  92596. ** and the index is UNIQUE and no terms on the tail of the ORDER BY
  92597. ** clause reference other tables in a join. If this is all true then
  92598. ** the order by clause is superfluous. Not that if the matching
  92599. ** condition is IS NULL then the result is not necessarily unique
  92600. ** even on a UNIQUE index, so disallow those cases. */
  92601. return 1;
  92602. }
  92603. return 0;
  92604. }
  92605. /*
  92606. ** Prepare a crude estimate of the logarithm of the input value.
  92607. ** The results need not be exact. This is only used for estimating
  92608. ** the total cost of performing operations with O(logN) or O(NlogN)
  92609. ** complexity. Because N is just a guess, it is no great tragedy if
  92610. ** logN is a little off.
  92611. */
  92612. static double estLog(double N){
  92613. double logN = 1;
  92614. double x = 10;
  92615. while( N>x ){
  92616. logN += 1;
  92617. x *= 10;
  92618. }
  92619. return logN;
  92620. }
  92621. /*
  92622. ** Two routines for printing the content of an sqlite3_index_info
  92623. ** structure. Used for testing and debugging only. If neither
  92624. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  92625. ** are no-ops.
  92626. */
  92627. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
  92628. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  92629. int i;
  92630. if( !sqlite3WhereTrace ) return;
  92631. for(i=0; i<p->nConstraint; i++){
  92632. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  92633. i,
  92634. p->aConstraint[i].iColumn,
  92635. p->aConstraint[i].iTermOffset,
  92636. p->aConstraint[i].op,
  92637. p->aConstraint[i].usable);
  92638. }
  92639. for(i=0; i<p->nOrderBy; i++){
  92640. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  92641. i,
  92642. p->aOrderBy[i].iColumn,
  92643. p->aOrderBy[i].desc);
  92644. }
  92645. }
  92646. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  92647. int i;
  92648. if( !sqlite3WhereTrace ) return;
  92649. for(i=0; i<p->nConstraint; i++){
  92650. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  92651. i,
  92652. p->aConstraintUsage[i].argvIndex,
  92653. p->aConstraintUsage[i].omit);
  92654. }
  92655. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  92656. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  92657. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  92658. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  92659. }
  92660. #else
  92661. #define TRACE_IDX_INPUTS(A)
  92662. #define TRACE_IDX_OUTPUTS(A)
  92663. #endif
  92664. /*
  92665. ** Required because bestIndex() is called by bestOrClauseIndex()
  92666. */
  92667. static void bestIndex(
  92668. Parse*, WhereClause*, struct SrcList_item*,
  92669. Bitmask, Bitmask, ExprList*, WhereCost*);
  92670. /*
  92671. ** This routine attempts to find an scanning strategy that can be used
  92672. ** to optimize an 'OR' expression that is part of a WHERE clause.
  92673. **
  92674. ** The table associated with FROM clause term pSrc may be either a
  92675. ** regular B-Tree table or a virtual table.
  92676. */
  92677. static void bestOrClauseIndex(
  92678. Parse *pParse, /* The parsing context */
  92679. WhereClause *pWC, /* The WHERE clause */
  92680. struct SrcList_item *pSrc, /* The FROM clause term to search */
  92681. Bitmask notReady, /* Mask of cursors not available for indexing */
  92682. Bitmask notValid, /* Cursors not available for any purpose */
  92683. ExprList *pOrderBy, /* The ORDER BY clause */
  92684. WhereCost *pCost /* Lowest cost query plan */
  92685. ){
  92686. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  92687. const int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
  92688. const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur); /* Bitmask for pSrc */
  92689. WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm]; /* End of pWC->a[] */
  92690. WhereTerm *pTerm; /* A single term of the WHERE clause */
  92691. /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
  92692. ** are used */
  92693. if( pSrc->notIndexed || pSrc->pIndex!=0 ){
  92694. return;
  92695. }
  92696. /* Search the WHERE clause terms for a usable WO_OR term. */
  92697. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  92698. if( pTerm->eOperator==WO_OR
  92699. && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
  92700. && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
  92701. ){
  92702. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  92703. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  92704. WhereTerm *pOrTerm;
  92705. int flags = WHERE_MULTI_OR;
  92706. double rTotal = 0;
  92707. double nRow = 0;
  92708. Bitmask used = 0;
  92709. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  92710. WhereCost sTermCost;
  92711. WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
  92712. (pOrTerm - pOrWC->a), (pTerm - pWC->a)
  92713. ));
  92714. if( pOrTerm->eOperator==WO_AND ){
  92715. WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
  92716. bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
  92717. }else if( pOrTerm->leftCursor==iCur ){
  92718. WhereClause tempWC;
  92719. tempWC.pParse = pWC->pParse;
  92720. tempWC.pMaskSet = pWC->pMaskSet;
  92721. tempWC.op = TK_AND;
  92722. tempWC.a = pOrTerm;
  92723. tempWC.nTerm = 1;
  92724. bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
  92725. }else{
  92726. continue;
  92727. }
  92728. rTotal += sTermCost.rCost;
  92729. nRow += sTermCost.plan.nRow;
  92730. used |= sTermCost.used;
  92731. if( rTotal>=pCost->rCost ) break;
  92732. }
  92733. /* If there is an ORDER BY clause, increase the scan cost to account
  92734. ** for the cost of the sort. */
  92735. if( pOrderBy!=0 ){
  92736. WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
  92737. rTotal, rTotal+nRow*estLog(nRow)));
  92738. rTotal += nRow*estLog(nRow);
  92739. }
  92740. /* If the cost of scanning using this OR term for optimization is
  92741. ** less than the current cost stored in pCost, replace the contents
  92742. ** of pCost. */
  92743. WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
  92744. if( rTotal<pCost->rCost ){
  92745. pCost->rCost = rTotal;
  92746. pCost->used = used;
  92747. pCost->plan.nRow = nRow;
  92748. pCost->plan.wsFlags = flags;
  92749. pCost->plan.u.pTerm = pTerm;
  92750. }
  92751. }
  92752. }
  92753. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  92754. }
  92755. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  92756. /*
  92757. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  92758. ** could be used with an index to access pSrc, assuming an appropriate
  92759. ** index existed.
  92760. */
  92761. static int termCanDriveIndex(
  92762. WhereTerm *pTerm, /* WHERE clause term to check */
  92763. struct SrcList_item *pSrc, /* Table we are trying to access */
  92764. Bitmask notReady /* Tables in outer loops of the join */
  92765. ){
  92766. char aff;
  92767. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  92768. if( pTerm->eOperator!=WO_EQ ) return 0;
  92769. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  92770. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  92771. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  92772. return 1;
  92773. }
  92774. #endif
  92775. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  92776. /*
  92777. ** If the query plan for pSrc specified in pCost is a full table scan
  92778. ** and indexing is allows (if there is no NOT INDEXED clause) and it
  92779. ** possible to construct a transient index that would perform better
  92780. ** than a full table scan even when the cost of constructing the index
  92781. ** is taken into account, then alter the query plan to use the
  92782. ** transient index.
  92783. */
  92784. static void bestAutomaticIndex(
  92785. Parse *pParse, /* The parsing context */
  92786. WhereClause *pWC, /* The WHERE clause */
  92787. struct SrcList_item *pSrc, /* The FROM clause term to search */
  92788. Bitmask notReady, /* Mask of cursors that are not available */
  92789. WhereCost *pCost /* Lowest cost query plan */
  92790. ){
  92791. double nTableRow; /* Rows in the input table */
  92792. double logN; /* log(nTableRow) */
  92793. double costTempIdx; /* per-query cost of the transient index */
  92794. WhereTerm *pTerm; /* A single term of the WHERE clause */
  92795. WhereTerm *pWCEnd; /* End of pWC->a[] */
  92796. Table *pTable; /* Table tht might be indexed */
  92797. if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
  92798. /* Automatic indices are disabled at run-time */
  92799. return;
  92800. }
  92801. if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
  92802. /* We already have some kind of index in use for this query. */
  92803. return;
  92804. }
  92805. if( pSrc->notIndexed ){
  92806. /* The NOT INDEXED clause appears in the SQL. */
  92807. return;
  92808. }
  92809. assert( pParse->nQueryLoop >= (double)1 );
  92810. pTable = pSrc->pTab;
  92811. nTableRow = pTable->nRowEst;
  92812. logN = estLog(nTableRow);
  92813. costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
  92814. if( costTempIdx>=pCost->rCost ){
  92815. /* The cost of creating the transient table would be greater than
  92816. ** doing the full table scan */
  92817. return;
  92818. }
  92819. /* Search for any equality comparison term */
  92820. pWCEnd = &pWC->a[pWC->nTerm];
  92821. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  92822. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  92823. WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
  92824. pCost->rCost, costTempIdx));
  92825. pCost->rCost = costTempIdx;
  92826. pCost->plan.nRow = logN + 1;
  92827. pCost->plan.wsFlags = WHERE_TEMP_INDEX;
  92828. pCost->used = pTerm->prereqRight;
  92829. break;
  92830. }
  92831. }
  92832. }
  92833. #else
  92834. # define bestAutomaticIndex(A,B,C,D,E) /* no-op */
  92835. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  92836. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  92837. /*
  92838. ** Generate code to construct the Index object for an automatic index
  92839. ** and to set up the WhereLevel object pLevel so that the code generator
  92840. ** makes use of the automatic index.
  92841. */
  92842. static void constructAutomaticIndex(
  92843. Parse *pParse, /* The parsing context */
  92844. WhereClause *pWC, /* The WHERE clause */
  92845. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  92846. Bitmask notReady, /* Mask of cursors that are not available */
  92847. WhereLevel *pLevel /* Write new index here */
  92848. ){
  92849. int nColumn; /* Number of columns in the constructed index */
  92850. WhereTerm *pTerm; /* A single term of the WHERE clause */
  92851. WhereTerm *pWCEnd; /* End of pWC->a[] */
  92852. int nByte; /* Byte of memory needed for pIdx */
  92853. Index *pIdx; /* Object describing the transient index */
  92854. Vdbe *v; /* Prepared statement under construction */
  92855. int regIsInit; /* Register set by initialization */
  92856. int addrInit; /* Address of the initialization bypass jump */
  92857. Table *pTable; /* The table being indexed */
  92858. KeyInfo *pKeyinfo; /* Key information for the index */
  92859. int addrTop; /* Top of the index fill loop */
  92860. int regRecord; /* Register holding an index record */
  92861. int n; /* Column counter */
  92862. int i; /* Loop counter */
  92863. int mxBitCol; /* Maximum column in pSrc->colUsed */
  92864. CollSeq *pColl; /* Collating sequence to on a column */
  92865. Bitmask idxCols; /* Bitmap of columns used for indexing */
  92866. Bitmask extraCols; /* Bitmap of additional columns */
  92867. /* Generate code to skip over the creation and initialization of the
  92868. ** transient index on 2nd and subsequent iterations of the loop. */
  92869. v = pParse->pVdbe;
  92870. assert( v!=0 );
  92871. regIsInit = ++pParse->nMem;
  92872. addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
  92873. sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
  92874. /* Count the number of columns that will be added to the index
  92875. ** and used to match WHERE clause constraints */
  92876. nColumn = 0;
  92877. pTable = pSrc->pTab;
  92878. pWCEnd = &pWC->a[pWC->nTerm];
  92879. idxCols = 0;
  92880. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  92881. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  92882. int iCol = pTerm->u.leftColumn;
  92883. Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
  92884. testcase( iCol==BMS );
  92885. testcase( iCol==BMS-1 );
  92886. if( (idxCols & cMask)==0 ){
  92887. nColumn++;
  92888. idxCols |= cMask;
  92889. }
  92890. }
  92891. }
  92892. assert( nColumn>0 );
  92893. pLevel->plan.nEq = nColumn;
  92894. /* Count the number of additional columns needed to create a
  92895. ** covering index. A "covering index" is an index that contains all
  92896. ** columns that are needed by the query. With a covering index, the
  92897. ** original table never needs to be accessed. Automatic indices must
  92898. ** be a covering index because the index will not be updated if the
  92899. ** original table changes and the index and table cannot both be used
  92900. ** if they go out of sync.
  92901. */
  92902. extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
  92903. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  92904. testcase( pTable->nCol==BMS-1 );
  92905. testcase( pTable->nCol==BMS-2 );
  92906. for(i=0; i<mxBitCol; i++){
  92907. if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
  92908. }
  92909. if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
  92910. nColumn += pTable->nCol - BMS + 1;
  92911. }
  92912. pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
  92913. /* Construct the Index object to describe this index */
  92914. nByte = sizeof(Index);
  92915. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  92916. nByte += nColumn*sizeof(char*); /* Index.azColl */
  92917. nByte += nColumn; /* Index.aSortOrder */
  92918. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  92919. if( pIdx==0 ) return;
  92920. pLevel->plan.u.pIdx = pIdx;
  92921. pIdx->azColl = (char**)&pIdx[1];
  92922. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  92923. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  92924. pIdx->zName = "auto-index";
  92925. pIdx->nColumn = nColumn;
  92926. pIdx->pTable = pTable;
  92927. n = 0;
  92928. idxCols = 0;
  92929. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  92930. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  92931. int iCol = pTerm->u.leftColumn;
  92932. Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
  92933. if( (idxCols & cMask)==0 ){
  92934. Expr *pX = pTerm->pExpr;
  92935. idxCols |= cMask;
  92936. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  92937. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  92938. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  92939. n++;
  92940. }
  92941. }
  92942. }
  92943. assert( (u32)n==pLevel->plan.nEq );
  92944. /* Add additional columns needed to make the automatic index into
  92945. ** a covering index */
  92946. for(i=0; i<mxBitCol; i++){
  92947. if( extraCols & (((Bitmask)1)<<i) ){
  92948. pIdx->aiColumn[n] = i;
  92949. pIdx->azColl[n] = "BINARY";
  92950. n++;
  92951. }
  92952. }
  92953. if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
  92954. for(i=BMS-1; i<pTable->nCol; i++){
  92955. pIdx->aiColumn[n] = i;
  92956. pIdx->azColl[n] = "BINARY";
  92957. n++;
  92958. }
  92959. }
  92960. assert( n==nColumn );
  92961. /* Create the automatic index */
  92962. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  92963. assert( pLevel->iIdxCur>=0 );
  92964. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  92965. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  92966. VdbeComment((v, "for %s", pTable->zName));
  92967. /* Fill the automatic index with content */
  92968. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  92969. regRecord = sqlite3GetTempReg(pParse);
  92970. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
  92971. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  92972. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  92973. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  92974. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  92975. sqlite3VdbeJumpHere(v, addrTop);
  92976. sqlite3ReleaseTempReg(pParse, regRecord);
  92977. /* Jump here when skipping the initialization */
  92978. sqlite3VdbeJumpHere(v, addrInit);
  92979. }
  92980. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  92981. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92982. /*
  92983. ** Allocate and populate an sqlite3_index_info structure. It is the
  92984. ** responsibility of the caller to eventually release the structure
  92985. ** by passing the pointer returned by this function to sqlite3_free().
  92986. */
  92987. static sqlite3_index_info *allocateIndexInfo(
  92988. Parse *pParse,
  92989. WhereClause *pWC,
  92990. struct SrcList_item *pSrc,
  92991. ExprList *pOrderBy
  92992. ){
  92993. int i, j;
  92994. int nTerm;
  92995. struct sqlite3_index_constraint *pIdxCons;
  92996. struct sqlite3_index_orderby *pIdxOrderBy;
  92997. struct sqlite3_index_constraint_usage *pUsage;
  92998. WhereTerm *pTerm;
  92999. int nOrderBy;
  93000. sqlite3_index_info *pIdxInfo;
  93001. WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
  93002. /* Count the number of possible WHERE clause constraints referring
  93003. ** to this virtual table */
  93004. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  93005. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  93006. assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
  93007. testcase( pTerm->eOperator==WO_IN );
  93008. testcase( pTerm->eOperator==WO_ISNULL );
  93009. if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
  93010. nTerm++;
  93011. }
  93012. /* If the ORDER BY clause contains only columns in the current
  93013. ** virtual table then allocate space for the aOrderBy part of
  93014. ** the sqlite3_index_info structure.
  93015. */
  93016. nOrderBy = 0;
  93017. if( pOrderBy ){
  93018. for(i=0; i<pOrderBy->nExpr; i++){
  93019. Expr *pExpr = pOrderBy->a[i].pExpr;
  93020. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  93021. }
  93022. if( i==pOrderBy->nExpr ){
  93023. nOrderBy = pOrderBy->nExpr;
  93024. }
  93025. }
  93026. /* Allocate the sqlite3_index_info structure
  93027. */
  93028. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  93029. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  93030. + sizeof(*pIdxOrderBy)*nOrderBy );
  93031. if( pIdxInfo==0 ){
  93032. sqlite3ErrorMsg(pParse, "out of memory");
  93033. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  93034. return 0;
  93035. }
  93036. /* Initialize the structure. The sqlite3_index_info structure contains
  93037. ** many fields that are declared "const" to prevent xBestIndex from
  93038. ** changing them. We have to do some funky casting in order to
  93039. ** initialize those fields.
  93040. */
  93041. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  93042. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  93043. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  93044. *(int*)&pIdxInfo->nConstraint = nTerm;
  93045. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  93046. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  93047. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  93048. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  93049. pUsage;
  93050. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  93051. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  93052. assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
  93053. testcase( pTerm->eOperator==WO_IN );
  93054. testcase( pTerm->eOperator==WO_ISNULL );
  93055. if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
  93056. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  93057. pIdxCons[j].iTermOffset = i;
  93058. pIdxCons[j].op = (u8)pTerm->eOperator;
  93059. /* The direct assignment in the previous line is possible only because
  93060. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  93061. ** following asserts verify this fact. */
  93062. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  93063. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  93064. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  93065. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  93066. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  93067. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  93068. assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  93069. j++;
  93070. }
  93071. for(i=0; i<nOrderBy; i++){
  93072. Expr *pExpr = pOrderBy->a[i].pExpr;
  93073. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  93074. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  93075. }
  93076. return pIdxInfo;
  93077. }
  93078. /*
  93079. ** The table object reference passed as the second argument to this function
  93080. ** must represent a virtual table. This function invokes the xBestIndex()
  93081. ** method of the virtual table with the sqlite3_index_info pointer passed
  93082. ** as the argument.
  93083. **
  93084. ** If an error occurs, pParse is populated with an error message and a
  93085. ** non-zero value is returned. Otherwise, 0 is returned and the output
  93086. ** part of the sqlite3_index_info structure is left populated.
  93087. **
  93088. ** Whether or not an error is returned, it is the responsibility of the
  93089. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  93090. ** that this is required.
  93091. */
  93092. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  93093. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  93094. int i;
  93095. int rc;
  93096. WHERETRACE(("xBestIndex for %s\n", pTab->zName));
  93097. TRACE_IDX_INPUTS(p);
  93098. rc = pVtab->pModule->xBestIndex(pVtab, p);
  93099. TRACE_IDX_OUTPUTS(p);
  93100. if( rc!=SQLITE_OK ){
  93101. if( rc==SQLITE_NOMEM ){
  93102. pParse->db->mallocFailed = 1;
  93103. }else if( !pVtab->zErrMsg ){
  93104. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  93105. }else{
  93106. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  93107. }
  93108. }
  93109. sqlite3_free(pVtab->zErrMsg);
  93110. pVtab->zErrMsg = 0;
  93111. for(i=0; i<p->nConstraint; i++){
  93112. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  93113. sqlite3ErrorMsg(pParse,
  93114. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  93115. }
  93116. }
  93117. return pParse->nErr;
  93118. }
  93119. /*
  93120. ** Compute the best index for a virtual table.
  93121. **
  93122. ** The best index is computed by the xBestIndex method of the virtual
  93123. ** table module. This routine is really just a wrapper that sets up
  93124. ** the sqlite3_index_info structure that is used to communicate with
  93125. ** xBestIndex.
  93126. **
  93127. ** In a join, this routine might be called multiple times for the
  93128. ** same virtual table. The sqlite3_index_info structure is created
  93129. ** and initialized on the first invocation and reused on all subsequent
  93130. ** invocations. The sqlite3_index_info structure is also used when
  93131. ** code is generated to access the virtual table. The whereInfoDelete()
  93132. ** routine takes care of freeing the sqlite3_index_info structure after
  93133. ** everybody has finished with it.
  93134. */
  93135. static void bestVirtualIndex(
  93136. Parse *pParse, /* The parsing context */
  93137. WhereClause *pWC, /* The WHERE clause */
  93138. struct SrcList_item *pSrc, /* The FROM clause term to search */
  93139. Bitmask notReady, /* Mask of cursors not available for index */
  93140. Bitmask notValid, /* Cursors not valid for any purpose */
  93141. ExprList *pOrderBy, /* The order by clause */
  93142. WhereCost *pCost, /* Lowest cost query plan */
  93143. sqlite3_index_info **ppIdxInfo /* Index information passed to xBestIndex */
  93144. ){
  93145. Table *pTab = pSrc->pTab;
  93146. sqlite3_index_info *pIdxInfo;
  93147. struct sqlite3_index_constraint *pIdxCons;
  93148. struct sqlite3_index_constraint_usage *pUsage;
  93149. WhereTerm *pTerm;
  93150. int i, j;
  93151. int nOrderBy;
  93152. double rCost;
  93153. /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
  93154. ** malloc in allocateIndexInfo() fails and this function returns leaving
  93155. ** wsFlags in an uninitialized state, the caller may behave unpredictably.
  93156. */
  93157. memset(pCost, 0, sizeof(*pCost));
  93158. pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
  93159. /* If the sqlite3_index_info structure has not been previously
  93160. ** allocated and initialized, then allocate and initialize it now.
  93161. */
  93162. pIdxInfo = *ppIdxInfo;
  93163. if( pIdxInfo==0 ){
  93164. *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
  93165. }
  93166. if( pIdxInfo==0 ){
  93167. return;
  93168. }
  93169. /* At this point, the sqlite3_index_info structure that pIdxInfo points
  93170. ** to will have been initialized, either during the current invocation or
  93171. ** during some prior invocation. Now we just have to customize the
  93172. ** details of pIdxInfo for the current invocation and pass it to
  93173. ** xBestIndex.
  93174. */
  93175. /* The module name must be defined. Also, by this point there must
  93176. ** be a pointer to an sqlite3_vtab structure. Otherwise
  93177. ** sqlite3ViewGetColumnNames() would have picked up the error.
  93178. */
  93179. assert( pTab->azModuleArg && pTab->azModuleArg[0] );
  93180. assert( sqlite3GetVTable(pParse->db, pTab) );
  93181. /* Set the aConstraint[].usable fields and initialize all
  93182. ** output variables to zero.
  93183. **
  93184. ** aConstraint[].usable is true for constraints where the right-hand
  93185. ** side contains only references to tables to the left of the current
  93186. ** table. In other words, if the constraint is of the form:
  93187. **
  93188. ** column = expr
  93189. **
  93190. ** and we are evaluating a join, then the constraint on column is
  93191. ** only valid if all tables referenced in expr occur to the left
  93192. ** of the table containing column.
  93193. **
  93194. ** The aConstraints[] array contains entries for all constraints
  93195. ** on the current table. That way we only have to compute it once
  93196. ** even though we might try to pick the best index multiple times.
  93197. ** For each attempt at picking an index, the order of tables in the
  93198. ** join might be different so we have to recompute the usable flag
  93199. ** each time.
  93200. */
  93201. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  93202. pUsage = pIdxInfo->aConstraintUsage;
  93203. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  93204. j = pIdxCons->iTermOffset;
  93205. pTerm = &pWC->a[j];
  93206. pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
  93207. }
  93208. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  93209. if( pIdxInfo->needToFreeIdxStr ){
  93210. sqlite3_free(pIdxInfo->idxStr);
  93211. }
  93212. pIdxInfo->idxStr = 0;
  93213. pIdxInfo->idxNum = 0;
  93214. pIdxInfo->needToFreeIdxStr = 0;
  93215. pIdxInfo->orderByConsumed = 0;
  93216. /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
  93217. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
  93218. nOrderBy = pIdxInfo->nOrderBy;
  93219. if( !pOrderBy ){
  93220. pIdxInfo->nOrderBy = 0;
  93221. }
  93222. if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
  93223. return;
  93224. }
  93225. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  93226. for(i=0; i<pIdxInfo->nConstraint; i++){
  93227. if( pUsage[i].argvIndex>0 ){
  93228. pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
  93229. }
  93230. }
  93231. /* If there is an ORDER BY clause, and the selected virtual table index
  93232. ** does not satisfy it, increase the cost of the scan accordingly. This
  93233. ** matches the processing for non-virtual tables in bestBtreeIndex().
  93234. */
  93235. rCost = pIdxInfo->estimatedCost;
  93236. if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
  93237. rCost += estLog(rCost)*rCost;
  93238. }
  93239. /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
  93240. ** inital value of lowestCost in this loop. If it is, then the
  93241. ** (cost<lowestCost) test below will never be true.
  93242. **
  93243. ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
  93244. ** is defined.
  93245. */
  93246. if( (SQLITE_BIG_DBL/((double)2))<rCost ){
  93247. pCost->rCost = (SQLITE_BIG_DBL/((double)2));
  93248. }else{
  93249. pCost->rCost = rCost;
  93250. }
  93251. pCost->plan.u.pVtabIdx = pIdxInfo;
  93252. if( pIdxInfo->orderByConsumed ){
  93253. pCost->plan.wsFlags |= WHERE_ORDERBY;
  93254. }
  93255. pCost->plan.nEq = 0;
  93256. pIdxInfo->nOrderBy = nOrderBy;
  93257. /* Try to find a more efficient access pattern by using multiple indexes
  93258. ** to optimize an OR expression within the WHERE clause.
  93259. */
  93260. bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
  93261. }
  93262. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  93263. /*
  93264. ** Argument pIdx is a pointer to an index structure that has an array of
  93265. ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
  93266. ** stored in Index.aSample. These samples divide the domain of values stored
  93267. ** the index into (SQLITE_INDEX_SAMPLES+1) regions.
  93268. ** Region 0 contains all values less than the first sample value. Region
  93269. ** 1 contains values between the first and second samples. Region 2 contains
  93270. ** values between samples 2 and 3. And so on. Region SQLITE_INDEX_SAMPLES
  93271. ** contains values larger than the last sample.
  93272. **
  93273. ** If the index contains many duplicates of a single value, then it is
  93274. ** possible that two or more adjacent samples can hold the same value.
  93275. ** When that is the case, the smallest possible region code is returned
  93276. ** when roundUp is false and the largest possible region code is returned
  93277. ** when roundUp is true.
  93278. **
  93279. ** If successful, this function determines which of the regions value
  93280. ** pVal lies in, sets *piRegion to the region index (a value between 0
  93281. ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
  93282. ** Or, if an OOM occurs while converting text values between encodings,
  93283. ** SQLITE_NOMEM is returned and *piRegion is undefined.
  93284. */
  93285. #ifdef SQLITE_ENABLE_STAT2
  93286. static int whereRangeRegion(
  93287. Parse *pParse, /* Database connection */
  93288. Index *pIdx, /* Index to consider domain of */
  93289. sqlite3_value *pVal, /* Value to consider */
  93290. int roundUp, /* Return largest valid region if true */
  93291. int *piRegion /* OUT: Region of domain in which value lies */
  93292. ){
  93293. assert( roundUp==0 || roundUp==1 );
  93294. if( ALWAYS(pVal) ){
  93295. IndexSample *aSample = pIdx->aSample;
  93296. int i = 0;
  93297. int eType = sqlite3_value_type(pVal);
  93298. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  93299. double r = sqlite3_value_double(pVal);
  93300. for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
  93301. if( aSample[i].eType==SQLITE_NULL ) continue;
  93302. if( aSample[i].eType>=SQLITE_TEXT ) break;
  93303. if( roundUp ){
  93304. if( aSample[i].u.r>r ) break;
  93305. }else{
  93306. if( aSample[i].u.r>=r ) break;
  93307. }
  93308. }
  93309. }else if( eType==SQLITE_NULL ){
  93310. i = 0;
  93311. if( roundUp ){
  93312. while( i<SQLITE_INDEX_SAMPLES && aSample[i].eType==SQLITE_NULL ) i++;
  93313. }
  93314. }else{
  93315. sqlite3 *db = pParse->db;
  93316. CollSeq *pColl;
  93317. const u8 *z;
  93318. int n;
  93319. /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
  93320. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  93321. if( eType==SQLITE_BLOB ){
  93322. z = (const u8 *)sqlite3_value_blob(pVal);
  93323. pColl = db->pDfltColl;
  93324. assert( pColl->enc==SQLITE_UTF8 );
  93325. }else{
  93326. pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
  93327. if( pColl==0 ){
  93328. sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
  93329. *pIdx->azColl);
  93330. return SQLITE_ERROR;
  93331. }
  93332. z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
  93333. if( !z ){
  93334. return SQLITE_NOMEM;
  93335. }
  93336. assert( z && pColl && pColl->xCmp );
  93337. }
  93338. n = sqlite3ValueBytes(pVal, pColl->enc);
  93339. for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
  93340. int c;
  93341. int eSampletype = aSample[i].eType;
  93342. if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
  93343. if( (eSampletype!=eType) ) break;
  93344. #ifndef SQLITE_OMIT_UTF16
  93345. if( pColl->enc!=SQLITE_UTF8 ){
  93346. int nSample;
  93347. char *zSample = sqlite3Utf8to16(
  93348. db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
  93349. );
  93350. if( !zSample ){
  93351. assert( db->mallocFailed );
  93352. return SQLITE_NOMEM;
  93353. }
  93354. c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
  93355. sqlite3DbFree(db, zSample);
  93356. }else
  93357. #endif
  93358. {
  93359. c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
  93360. }
  93361. if( c-roundUp>=0 ) break;
  93362. }
  93363. }
  93364. assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
  93365. *piRegion = i;
  93366. }
  93367. return SQLITE_OK;
  93368. }
  93369. #endif /* #ifdef SQLITE_ENABLE_STAT2 */
  93370. /*
  93371. ** If expression pExpr represents a literal value, set *pp to point to
  93372. ** an sqlite3_value structure containing the same value, with affinity
  93373. ** aff applied to it, before returning. It is the responsibility of the
  93374. ** caller to eventually release this structure by passing it to
  93375. ** sqlite3ValueFree().
  93376. **
  93377. ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
  93378. ** is an SQL variable that currently has a non-NULL value bound to it,
  93379. ** create an sqlite3_value structure containing this value, again with
  93380. ** affinity aff applied to it, instead.
  93381. **
  93382. ** If neither of the above apply, set *pp to NULL.
  93383. **
  93384. ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
  93385. */
  93386. #ifdef SQLITE_ENABLE_STAT2
  93387. static int valueFromExpr(
  93388. Parse *pParse,
  93389. Expr *pExpr,
  93390. u8 aff,
  93391. sqlite3_value **pp
  93392. ){
  93393. if( pExpr->op==TK_VARIABLE
  93394. || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  93395. ){
  93396. int iVar = pExpr->iColumn;
  93397. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
  93398. *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
  93399. return SQLITE_OK;
  93400. }
  93401. return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
  93402. }
  93403. #endif
  93404. /*
  93405. ** This function is used to estimate the number of rows that will be visited
  93406. ** by scanning an index for a range of values. The range may have an upper
  93407. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  93408. ** and lower bounds are represented by pLower and pUpper respectively. For
  93409. ** example, assuming that index p is on t1(a):
  93410. **
  93411. ** ... FROM t1 WHERE a > ? AND a < ? ...
  93412. ** |_____| |_____|
  93413. ** | |
  93414. ** pLower pUpper
  93415. **
  93416. ** If either of the upper or lower bound is not present, then NULL is passed in
  93417. ** place of the corresponding WhereTerm.
  93418. **
  93419. ** The nEq parameter is passed the index of the index column subject to the
  93420. ** range constraint. Or, equivalently, the number of equality constraints
  93421. ** optimized by the proposed index scan. For example, assuming index p is
  93422. ** on t1(a, b), and the SQL query is:
  93423. **
  93424. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  93425. **
  93426. ** then nEq should be passed the value 1 (as the range restricted column,
  93427. ** b, is the second left-most column of the index). Or, if the query is:
  93428. **
  93429. ** ... FROM t1 WHERE a > ? AND a < ? ...
  93430. **
  93431. ** then nEq should be passed 0.
  93432. **
  93433. ** The returned value is an integer between 1 and 100, inclusive. A return
  93434. ** value of 1 indicates that the proposed range scan is expected to visit
  93435. ** approximately 1/100th (1%) of the rows selected by the nEq equality
  93436. ** constraints (if any). A return value of 100 indicates that it is expected
  93437. ** that the range scan will visit every row (100%) selected by the equality
  93438. ** constraints.
  93439. **
  93440. ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
  93441. ** reduces the search space by 3/4ths. Hence a single constraint (x>?)
  93442. ** results in a return of 25 and a range constraint (x>? AND x<?) results
  93443. ** in a return of 6.
  93444. */
  93445. static int whereRangeScanEst(
  93446. Parse *pParse, /* Parsing & code generating context */
  93447. Index *p, /* The index containing the range-compared column; "x" */
  93448. int nEq, /* index into p->aCol[] of the range-compared column */
  93449. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  93450. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  93451. int *piEst /* OUT: Return value */
  93452. ){
  93453. int rc = SQLITE_OK;
  93454. #ifdef SQLITE_ENABLE_STAT2
  93455. if( nEq==0 && p->aSample ){
  93456. sqlite3_value *pLowerVal = 0;
  93457. sqlite3_value *pUpperVal = 0;
  93458. int iEst;
  93459. int iLower = 0;
  93460. int iUpper = SQLITE_INDEX_SAMPLES;
  93461. int roundUpUpper = 0;
  93462. int roundUpLower = 0;
  93463. u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
  93464. if( pLower ){
  93465. Expr *pExpr = pLower->pExpr->pRight;
  93466. rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
  93467. assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
  93468. roundUpLower = (pLower->eOperator==WO_GT) ?1:0;
  93469. }
  93470. if( rc==SQLITE_OK && pUpper ){
  93471. Expr *pExpr = pUpper->pExpr->pRight;
  93472. rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
  93473. assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
  93474. roundUpUpper = (pUpper->eOperator==WO_LE) ?1:0;
  93475. }
  93476. if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
  93477. sqlite3ValueFree(pLowerVal);
  93478. sqlite3ValueFree(pUpperVal);
  93479. goto range_est_fallback;
  93480. }else if( pLowerVal==0 ){
  93481. rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
  93482. if( pLower ) iLower = iUpper/2;
  93483. }else if( pUpperVal==0 ){
  93484. rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
  93485. if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
  93486. }else{
  93487. rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
  93488. if( rc==SQLITE_OK ){
  93489. rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
  93490. }
  93491. }
  93492. WHERETRACE(("range scan regions: %d..%d\n", iLower, iUpper));
  93493. iEst = iUpper - iLower;
  93494. testcase( iEst==SQLITE_INDEX_SAMPLES );
  93495. assert( iEst<=SQLITE_INDEX_SAMPLES );
  93496. if( iEst<1 ){
  93497. *piEst = 50/SQLITE_INDEX_SAMPLES;
  93498. }else{
  93499. *piEst = (iEst*100)/SQLITE_INDEX_SAMPLES;
  93500. }
  93501. sqlite3ValueFree(pLowerVal);
  93502. sqlite3ValueFree(pUpperVal);
  93503. return rc;
  93504. }
  93505. range_est_fallback:
  93506. #else
  93507. UNUSED_PARAMETER(pParse);
  93508. UNUSED_PARAMETER(p);
  93509. UNUSED_PARAMETER(nEq);
  93510. #endif
  93511. assert( pLower || pUpper );
  93512. *piEst = 100;
  93513. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *piEst /= 4;
  93514. if( pUpper ) *piEst /= 4;
  93515. return rc;
  93516. }
  93517. #ifdef SQLITE_ENABLE_STAT2
  93518. /*
  93519. ** Estimate the number of rows that will be returned based on
  93520. ** an equality constraint x=VALUE and where that VALUE occurs in
  93521. ** the histogram data. This only works when x is the left-most
  93522. ** column of an index and sqlite_stat2 histogram data is available
  93523. ** for that index. When pExpr==NULL that means the constraint is
  93524. ** "x IS NULL" instead of "x=VALUE".
  93525. **
  93526. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  93527. ** If unable to make an estimate, leave *pnRow unchanged and return
  93528. ** non-zero.
  93529. **
  93530. ** This routine can fail if it is unable to load a collating sequence
  93531. ** required for string comparison, or if unable to allocate memory
  93532. ** for a UTF conversion required for comparison. The error is stored
  93533. ** in the pParse structure.
  93534. */
  93535. static int whereEqualScanEst(
  93536. Parse *pParse, /* Parsing & code generating context */
  93537. Index *p, /* The index whose left-most column is pTerm */
  93538. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  93539. double *pnRow /* Write the revised row estimate here */
  93540. ){
  93541. sqlite3_value *pRhs = 0; /* VALUE on right-hand side of pTerm */
  93542. int iLower, iUpper; /* Range of histogram regions containing pRhs */
  93543. u8 aff; /* Column affinity */
  93544. int rc; /* Subfunction return code */
  93545. double nRowEst; /* New estimate of the number of rows */
  93546. assert( p->aSample!=0 );
  93547. aff = p->pTable->aCol[p->aiColumn[0]].affinity;
  93548. if( pExpr ){
  93549. rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
  93550. if( rc ) goto whereEqualScanEst_cancel;
  93551. }else{
  93552. pRhs = sqlite3ValueNew(pParse->db);
  93553. }
  93554. if( pRhs==0 ) return SQLITE_NOTFOUND;
  93555. rc = whereRangeRegion(pParse, p, pRhs, 0, &iLower);
  93556. if( rc ) goto whereEqualScanEst_cancel;
  93557. rc = whereRangeRegion(pParse, p, pRhs, 1, &iUpper);
  93558. if( rc ) goto whereEqualScanEst_cancel;
  93559. WHERETRACE(("equality scan regions: %d..%d\n", iLower, iUpper));
  93560. if( iLower>=iUpper ){
  93561. nRowEst = p->aiRowEst[0]/(SQLITE_INDEX_SAMPLES*2);
  93562. if( nRowEst<*pnRow ) *pnRow = nRowEst;
  93563. }else{
  93564. nRowEst = (iUpper-iLower)*p->aiRowEst[0]/SQLITE_INDEX_SAMPLES;
  93565. *pnRow = nRowEst;
  93566. }
  93567. whereEqualScanEst_cancel:
  93568. sqlite3ValueFree(pRhs);
  93569. return rc;
  93570. }
  93571. #endif /* defined(SQLITE_ENABLE_STAT2) */
  93572. #ifdef SQLITE_ENABLE_STAT2
  93573. /*
  93574. ** Estimate the number of rows that will be returned based on
  93575. ** an IN constraint where the right-hand side of the IN operator
  93576. ** is a list of values. Example:
  93577. **
  93578. ** WHERE x IN (1,2,3,4)
  93579. **
  93580. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  93581. ** If unable to make an estimate, leave *pnRow unchanged and return
  93582. ** non-zero.
  93583. **
  93584. ** This routine can fail if it is unable to load a collating sequence
  93585. ** required for string comparison, or if unable to allocate memory
  93586. ** for a UTF conversion required for comparison. The error is stored
  93587. ** in the pParse structure.
  93588. */
  93589. static int whereInScanEst(
  93590. Parse *pParse, /* Parsing & code generating context */
  93591. Index *p, /* The index whose left-most column is pTerm */
  93592. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  93593. double *pnRow /* Write the revised row estimate here */
  93594. ){
  93595. sqlite3_value *pVal = 0; /* One value from list */
  93596. int iLower, iUpper; /* Range of histogram regions containing pRhs */
  93597. u8 aff; /* Column affinity */
  93598. int rc = SQLITE_OK; /* Subfunction return code */
  93599. double nRowEst; /* New estimate of the number of rows */
  93600. int nSpan = 0; /* Number of histogram regions spanned */
  93601. int nSingle = 0; /* Histogram regions hit by a single value */
  93602. int nNotFound = 0; /* Count of values that are not constants */
  93603. int i; /* Loop counter */
  93604. u8 aSpan[SQLITE_INDEX_SAMPLES+1]; /* Histogram regions that are spanned */
  93605. u8 aSingle[SQLITE_INDEX_SAMPLES+1]; /* Histogram regions hit once */
  93606. assert( p->aSample!=0 );
  93607. aff = p->pTable->aCol[p->aiColumn[0]].affinity;
  93608. memset(aSpan, 0, sizeof(aSpan));
  93609. memset(aSingle, 0, sizeof(aSingle));
  93610. for(i=0; i<pList->nExpr; i++){
  93611. sqlite3ValueFree(pVal);
  93612. rc = valueFromExpr(pParse, pList->a[i].pExpr, aff, &pVal);
  93613. if( rc ) break;
  93614. if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
  93615. nNotFound++;
  93616. continue;
  93617. }
  93618. rc = whereRangeRegion(pParse, p, pVal, 0, &iLower);
  93619. if( rc ) break;
  93620. rc = whereRangeRegion(pParse, p, pVal, 1, &iUpper);
  93621. if( rc ) break;
  93622. if( iLower>=iUpper ){
  93623. aSingle[iLower] = 1;
  93624. }else{
  93625. assert( iLower>=0 && iUpper<=SQLITE_INDEX_SAMPLES );
  93626. while( iLower<iUpper ) aSpan[iLower++] = 1;
  93627. }
  93628. }
  93629. if( rc==SQLITE_OK ){
  93630. for(i=nSpan=0; i<=SQLITE_INDEX_SAMPLES; i++){
  93631. if( aSpan[i] ){
  93632. nSpan++;
  93633. }else if( aSingle[i] ){
  93634. nSingle++;
  93635. }
  93636. }
  93637. nRowEst = (nSpan*2+nSingle)*p->aiRowEst[0]/(2*SQLITE_INDEX_SAMPLES)
  93638. + nNotFound*p->aiRowEst[1];
  93639. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  93640. *pnRow = nRowEst;
  93641. WHERETRACE(("IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
  93642. nSpan, nSingle, nNotFound, nRowEst));
  93643. }
  93644. sqlite3ValueFree(pVal);
  93645. return rc;
  93646. }
  93647. #endif /* defined(SQLITE_ENABLE_STAT2) */
  93648. /*
  93649. ** Find the best query plan for accessing a particular table. Write the
  93650. ** best query plan and its cost into the WhereCost object supplied as the
  93651. ** last parameter.
  93652. **
  93653. ** The lowest cost plan wins. The cost is an estimate of the amount of
  93654. ** CPU and disk I/O needed to process the requested result.
  93655. ** Factors that influence cost include:
  93656. **
  93657. ** * The estimated number of rows that will be retrieved. (The
  93658. ** fewer the better.)
  93659. **
  93660. ** * Whether or not sorting must occur.
  93661. **
  93662. ** * Whether or not there must be separate lookups in the
  93663. ** index and in the main table.
  93664. **
  93665. ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
  93666. ** the SQL statement, then this function only considers plans using the
  93667. ** named index. If no such plan is found, then the returned cost is
  93668. ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
  93669. ** then the cost is calculated in the usual way.
  93670. **
  93671. ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
  93672. ** in the SELECT statement, then no indexes are considered. However, the
  93673. ** selected plan may still take advantage of the built-in rowid primary key
  93674. ** index.
  93675. */
  93676. static void bestBtreeIndex(
  93677. Parse *pParse, /* The parsing context */
  93678. WhereClause *pWC, /* The WHERE clause */
  93679. struct SrcList_item *pSrc, /* The FROM clause term to search */
  93680. Bitmask notReady, /* Mask of cursors not available for indexing */
  93681. Bitmask notValid, /* Cursors not available for any purpose */
  93682. ExprList *pOrderBy, /* The ORDER BY clause */
  93683. WhereCost *pCost /* Lowest cost query plan */
  93684. ){
  93685. int iCur = pSrc->iCursor; /* The cursor of the table to be accessed */
  93686. Index *pProbe; /* An index we are evaluating */
  93687. Index *pIdx; /* Copy of pProbe, or zero for IPK index */
  93688. int eqTermMask; /* Current mask of valid equality operators */
  93689. int idxEqTermMask; /* Index mask of valid equality operators */
  93690. Index sPk; /* A fake index object for the primary key */
  93691. unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  93692. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  93693. int wsFlagMask; /* Allowed flags in pCost->plan.wsFlag */
  93694. /* Initialize the cost to a worst-case value */
  93695. memset(pCost, 0, sizeof(*pCost));
  93696. pCost->rCost = SQLITE_BIG_DBL;
  93697. /* If the pSrc table is the right table of a LEFT JOIN then we may not
  93698. ** use an index to satisfy IS NULL constraints on that table. This is
  93699. ** because columns might end up being NULL if the table does not match -
  93700. ** a circumstance which the index cannot help us discover. Ticket #2177.
  93701. */
  93702. if( pSrc->jointype & JT_LEFT ){
  93703. idxEqTermMask = WO_EQ|WO_IN;
  93704. }else{
  93705. idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
  93706. }
  93707. if( pSrc->pIndex ){
  93708. /* An INDEXED BY clause specifies a particular index to use */
  93709. pIdx = pProbe = pSrc->pIndex;
  93710. wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
  93711. eqTermMask = idxEqTermMask;
  93712. }else{
  93713. /* There is no INDEXED BY clause. Create a fake Index object in local
  93714. ** variable sPk to represent the rowid primary key index. Make this
  93715. ** fake index the first in a chain of Index objects with all of the real
  93716. ** indices to follow */
  93717. Index *pFirst; /* First of real indices on the table */
  93718. memset(&sPk, 0, sizeof(Index));
  93719. sPk.nColumn = 1;
  93720. sPk.aiColumn = &aiColumnPk;
  93721. sPk.aiRowEst = aiRowEstPk;
  93722. sPk.onError = OE_Replace;
  93723. sPk.pTable = pSrc->pTab;
  93724. aiRowEstPk[0] = pSrc->pTab->nRowEst;
  93725. aiRowEstPk[1] = 1;
  93726. pFirst = pSrc->pTab->pIndex;
  93727. if( pSrc->notIndexed==0 ){
  93728. /* The real indices of the table are only considered if the
  93729. ** NOT INDEXED qualifier is omitted from the FROM clause */
  93730. sPk.pNext = pFirst;
  93731. }
  93732. pProbe = &sPk;
  93733. wsFlagMask = ~(
  93734. WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
  93735. );
  93736. eqTermMask = WO_EQ|WO_IN;
  93737. pIdx = 0;
  93738. }
  93739. /* Loop over all indices looking for the best one to use
  93740. */
  93741. for(; pProbe; pIdx=pProbe=pProbe->pNext){
  93742. const unsigned int * const aiRowEst = pProbe->aiRowEst;
  93743. double cost; /* Cost of using pProbe */
  93744. double nRow; /* Estimated number of rows in result set */
  93745. double log10N; /* base-10 logarithm of nRow (inexact) */
  93746. int rev; /* True to scan in reverse order */
  93747. int wsFlags = 0;
  93748. Bitmask used = 0;
  93749. /* The following variables are populated based on the properties of
  93750. ** index being evaluated. They are then used to determine the expected
  93751. ** cost and number of rows returned.
  93752. **
  93753. ** nEq:
  93754. ** Number of equality terms that can be implemented using the index.
  93755. ** In other words, the number of initial fields in the index that
  93756. ** are used in == or IN or NOT NULL constraints of the WHERE clause.
  93757. **
  93758. ** nInMul:
  93759. ** The "in-multiplier". This is an estimate of how many seek operations
  93760. ** SQLite must perform on the index in question. For example, if the
  93761. ** WHERE clause is:
  93762. **
  93763. ** WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
  93764. **
  93765. ** SQLite must perform 9 lookups on an index on (a, b), so nInMul is
  93766. ** set to 9. Given the same schema and either of the following WHERE
  93767. ** clauses:
  93768. **
  93769. ** WHERE a = 1
  93770. ** WHERE a >= 2
  93771. **
  93772. ** nInMul is set to 1.
  93773. **
  93774. ** If there exists a WHERE term of the form "x IN (SELECT ...)", then
  93775. ** the sub-select is assumed to return 25 rows for the purposes of
  93776. ** determining nInMul.
  93777. **
  93778. ** bInEst:
  93779. ** Set to true if there was at least one "x IN (SELECT ...)" term used
  93780. ** in determining the value of nInMul. Note that the RHS of the
  93781. ** IN operator must be a SELECT, not a value list, for this variable
  93782. ** to be true.
  93783. **
  93784. ** estBound:
  93785. ** An estimate on the amount of the table that must be searched. A
  93786. ** value of 100 means the entire table is searched. Range constraints
  93787. ** might reduce this to a value less than 100 to indicate that only
  93788. ** a fraction of the table needs searching. In the absence of
  93789. ** sqlite_stat2 ANALYZE data, a single inequality reduces the search
  93790. ** space to 1/4rd its original size. So an x>? constraint reduces
  93791. ** estBound to 25. Two constraints (x>? AND x<?) reduce estBound to 6.
  93792. **
  93793. ** bSort:
  93794. ** Boolean. True if there is an ORDER BY clause that will require an
  93795. ** external sort (i.e. scanning the index being evaluated will not
  93796. ** correctly order records).
  93797. **
  93798. ** bLookup:
  93799. ** Boolean. True if a table lookup is required for each index entry
  93800. ** visited. In other words, true if this is not a covering index.
  93801. ** This is always false for the rowid primary key index of a table.
  93802. ** For other indexes, it is true unless all the columns of the table
  93803. ** used by the SELECT statement are present in the index (such an
  93804. ** index is sometimes described as a covering index).
  93805. ** For example, given the index on (a, b), the second of the following
  93806. ** two queries requires table b-tree lookups in order to find the value
  93807. ** of column c, but the first does not because columns a and b are
  93808. ** both available in the index.
  93809. **
  93810. ** SELECT a, b FROM tbl WHERE a = 1;
  93811. ** SELECT a, b, c FROM tbl WHERE a = 1;
  93812. */
  93813. int nEq; /* Number of == or IN terms matching index */
  93814. int bInEst = 0; /* True if "x IN (SELECT...)" seen */
  93815. int nInMul = 1; /* Number of distinct equalities to lookup */
  93816. int estBound = 100; /* Estimated reduction in search space */
  93817. int nBound = 0; /* Number of range constraints seen */
  93818. int bSort = 0; /* True if external sort required */
  93819. int bLookup = 0; /* True if not a covering index */
  93820. WhereTerm *pTerm; /* A single term of the WHERE clause */
  93821. #ifdef SQLITE_ENABLE_STAT2
  93822. WhereTerm *pFirstTerm = 0; /* First term matching the index */
  93823. #endif
  93824. /* Determine the values of nEq and nInMul */
  93825. for(nEq=0; nEq<pProbe->nColumn; nEq++){
  93826. int j = pProbe->aiColumn[nEq];
  93827. pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
  93828. if( pTerm==0 ) break;
  93829. wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
  93830. if( pTerm->eOperator & WO_IN ){
  93831. Expr *pExpr = pTerm->pExpr;
  93832. wsFlags |= WHERE_COLUMN_IN;
  93833. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93834. /* "x IN (SELECT ...)": Assume the SELECT returns 25 rows */
  93835. nInMul *= 25;
  93836. bInEst = 1;
  93837. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  93838. /* "x IN (value, value, ...)" */
  93839. nInMul *= pExpr->x.pList->nExpr;
  93840. }
  93841. }else if( pTerm->eOperator & WO_ISNULL ){
  93842. wsFlags |= WHERE_COLUMN_NULL;
  93843. }
  93844. #ifdef SQLITE_ENABLE_STAT2
  93845. if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
  93846. #endif
  93847. used |= pTerm->prereqRight;
  93848. }
  93849. /* Determine the value of estBound. */
  93850. if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
  93851. int j = pProbe->aiColumn[nEq];
  93852. if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
  93853. WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
  93854. WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
  93855. whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
  93856. if( pTop ){
  93857. nBound = 1;
  93858. wsFlags |= WHERE_TOP_LIMIT;
  93859. used |= pTop->prereqRight;
  93860. }
  93861. if( pBtm ){
  93862. nBound++;
  93863. wsFlags |= WHERE_BTM_LIMIT;
  93864. used |= pBtm->prereqRight;
  93865. }
  93866. wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
  93867. }
  93868. }else if( pProbe->onError!=OE_None ){
  93869. testcase( wsFlags & WHERE_COLUMN_IN );
  93870. testcase( wsFlags & WHERE_COLUMN_NULL );
  93871. if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
  93872. wsFlags |= WHERE_UNIQUE;
  93873. }
  93874. }
  93875. /* If there is an ORDER BY clause and the index being considered will
  93876. ** naturally scan rows in the required order, set the appropriate flags
  93877. ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
  93878. ** will scan rows in a different order, set the bSort variable. */
  93879. if( pOrderBy ){
  93880. if( (wsFlags & WHERE_COLUMN_IN)==0
  93881. && pProbe->bUnordered==0
  93882. && isSortingIndex(pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy,
  93883. nEq, wsFlags, &rev)
  93884. ){
  93885. wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
  93886. wsFlags |= (rev ? WHERE_REVERSE : 0);
  93887. }else{
  93888. bSort = 1;
  93889. }
  93890. }
  93891. /* If currently calculating the cost of using an index (not the IPK
  93892. ** index), determine if all required column data may be obtained without
  93893. ** using the main table (i.e. if the index is a covering
  93894. ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
  93895. ** wsFlags. Otherwise, set the bLookup variable to true. */
  93896. if( pIdx && wsFlags ){
  93897. Bitmask m = pSrc->colUsed;
  93898. int j;
  93899. for(j=0; j<pIdx->nColumn; j++){
  93900. int x = pIdx->aiColumn[j];
  93901. if( x<BMS-1 ){
  93902. m &= ~(((Bitmask)1)<<x);
  93903. }
  93904. }
  93905. if( m==0 ){
  93906. wsFlags |= WHERE_IDX_ONLY;
  93907. }else{
  93908. bLookup = 1;
  93909. }
  93910. }
  93911. /*
  93912. ** Estimate the number of rows of output. For an "x IN (SELECT...)"
  93913. ** constraint, do not let the estimate exceed half the rows in the table.
  93914. */
  93915. nRow = (double)(aiRowEst[nEq] * nInMul);
  93916. if( bInEst && nRow*2>aiRowEst[0] ){
  93917. nRow = aiRowEst[0]/2;
  93918. nInMul = (int)(nRow / aiRowEst[nEq]);
  93919. }
  93920. #ifdef SQLITE_ENABLE_STAT2
  93921. /* If the constraint is of the form x=VALUE and histogram
  93922. ** data is available for column x, then it might be possible
  93923. ** to get a better estimate on the number of rows based on
  93924. ** VALUE and how common that value is according to the histogram.
  93925. */
  93926. if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 ){
  93927. if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
  93928. testcase( pFirstTerm->eOperator==WO_EQ );
  93929. testcase( pFirstTerm->eOperator==WO_ISNULL );
  93930. whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
  93931. }else if( pFirstTerm->eOperator==WO_IN && bInEst==0 ){
  93932. whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
  93933. }
  93934. }
  93935. #endif /* SQLITE_ENABLE_STAT2 */
  93936. /* Adjust the number of output rows and downward to reflect rows
  93937. ** that are excluded by range constraints.
  93938. */
  93939. nRow = (nRow * (double)estBound) / (double)100;
  93940. if( nRow<1 ) nRow = 1;
  93941. /* Experiments run on real SQLite databases show that the time needed
  93942. ** to do a binary search to locate a row in a table or index is roughly
  93943. ** log10(N) times the time to move from one row to the next row within
  93944. ** a table or index. The actual times can vary, with the size of
  93945. ** records being an important factor. Both moves and searches are
  93946. ** slower with larger records, presumably because fewer records fit
  93947. ** on one page and hence more pages have to be fetched.
  93948. **
  93949. ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
  93950. ** not give us data on the relative sizes of table and index records.
  93951. ** So this computation assumes table records are about twice as big
  93952. ** as index records
  93953. */
  93954. if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
  93955. /* The cost of a full table scan is a number of move operations equal
  93956. ** to the number of rows in the table.
  93957. **
  93958. ** We add an additional 4x penalty to full table scans. This causes
  93959. ** the cost function to err on the side of choosing an index over
  93960. ** choosing a full scan. This 4x full-scan penalty is an arguable
  93961. ** decision and one which we expect to revisit in the future. But
  93962. ** it seems to be working well enough at the moment.
  93963. */
  93964. cost = aiRowEst[0]*4;
  93965. }else{
  93966. log10N = estLog(aiRowEst[0]);
  93967. cost = nRow;
  93968. if( pIdx ){
  93969. if( bLookup ){
  93970. /* For an index lookup followed by a table lookup:
  93971. ** nInMul index searches to find the start of each index range
  93972. ** + nRow steps through the index
  93973. ** + nRow table searches to lookup the table entry using the rowid
  93974. */
  93975. cost += (nInMul + nRow)*log10N;
  93976. }else{
  93977. /* For a covering index:
  93978. ** nInMul index searches to find the initial entry
  93979. ** + nRow steps through the index
  93980. */
  93981. cost += nInMul*log10N;
  93982. }
  93983. }else{
  93984. /* For a rowid primary key lookup:
  93985. ** nInMult table searches to find the initial entry for each range
  93986. ** + nRow steps through the table
  93987. */
  93988. cost += nInMul*log10N;
  93989. }
  93990. }
  93991. /* Add in the estimated cost of sorting the result. Actual experimental
  93992. ** measurements of sorting performance in SQLite show that sorting time
  93993. ** adds C*N*log10(N) to the cost, where N is the number of rows to be
  93994. ** sorted and C is a factor between 1.95 and 4.3. We will split the
  93995. ** difference and select C of 3.0.
  93996. */
  93997. if( bSort ){
  93998. cost += nRow*estLog(nRow)*3;
  93999. }
  94000. /**** Cost of using this index has now been computed ****/
  94001. /* If there are additional constraints on this table that cannot
  94002. ** be used with the current index, but which might lower the number
  94003. ** of output rows, adjust the nRow value accordingly. This only
  94004. ** matters if the current index is the least costly, so do not bother
  94005. ** with this step if we already know this index will not be chosen.
  94006. ** Also, never reduce the output row count below 2 using this step.
  94007. **
  94008. ** It is critical that the notValid mask be used here instead of
  94009. ** the notReady mask. When computing an "optimal" index, the notReady
  94010. ** mask will only have one bit set - the bit for the current table.
  94011. ** The notValid mask, on the other hand, always has all bits set for
  94012. ** tables that are not in outer loops. If notReady is used here instead
  94013. ** of notValid, then a optimal index that depends on inner joins loops
  94014. ** might be selected even when there exists an optimal index that has
  94015. ** no such dependency.
  94016. */
  94017. if( nRow>2 && cost<=pCost->rCost ){
  94018. int k; /* Loop counter */
  94019. int nSkipEq = nEq; /* Number of == constraints to skip */
  94020. int nSkipRange = nBound; /* Number of < constraints to skip */
  94021. Bitmask thisTab; /* Bitmap for pSrc */
  94022. thisTab = getMask(pWC->pMaskSet, iCur);
  94023. for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
  94024. if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
  94025. if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
  94026. if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
  94027. if( nSkipEq ){
  94028. /* Ignore the first nEq equality matches since the index
  94029. ** has already accounted for these */
  94030. nSkipEq--;
  94031. }else{
  94032. /* Assume each additional equality match reduces the result
  94033. ** set size by a factor of 10 */
  94034. nRow /= 10;
  94035. }
  94036. }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
  94037. if( nSkipRange ){
  94038. /* Ignore the first nSkipRange range constraints since the index
  94039. ** has already accounted for these */
  94040. nSkipRange--;
  94041. }else{
  94042. /* Assume each additional range constraint reduces the result
  94043. ** set size by a factor of 3. Indexed range constraints reduce
  94044. ** the search space by a larger factor: 4. We make indexed range
  94045. ** more selective intentionally because of the subjective
  94046. ** observation that indexed range constraints really are more
  94047. ** selective in practice, on average. */
  94048. nRow /= 3;
  94049. }
  94050. }else if( pTerm->eOperator!=WO_NOOP ){
  94051. /* Any other expression lowers the output row count by half */
  94052. nRow /= 2;
  94053. }
  94054. }
  94055. if( nRow<2 ) nRow = 2;
  94056. }
  94057. WHERETRACE((
  94058. "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
  94059. " notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
  94060. pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
  94061. nEq, nInMul, estBound, bSort, bLookup, wsFlags,
  94062. notReady, log10N, nRow, cost, used
  94063. ));
  94064. /* If this index is the best we have seen so far, then record this
  94065. ** index and its cost in the pCost structure.
  94066. */
  94067. if( (!pIdx || wsFlags)
  94068. && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
  94069. ){
  94070. pCost->rCost = cost;
  94071. pCost->used = used;
  94072. pCost->plan.nRow = nRow;
  94073. pCost->plan.wsFlags = (wsFlags&wsFlagMask);
  94074. pCost->plan.nEq = nEq;
  94075. pCost->plan.u.pIdx = pIdx;
  94076. }
  94077. /* If there was an INDEXED BY clause, then only that one index is
  94078. ** considered. */
  94079. if( pSrc->pIndex ) break;
  94080. /* Reset masks for the next index in the loop */
  94081. wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
  94082. eqTermMask = idxEqTermMask;
  94083. }
  94084. /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
  94085. ** is set, then reverse the order that the index will be scanned
  94086. ** in. This is used for application testing, to help find cases
  94087. ** where application behaviour depends on the (undefined) order that
  94088. ** SQLite outputs rows in in the absence of an ORDER BY clause. */
  94089. if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
  94090. pCost->plan.wsFlags |= WHERE_REVERSE;
  94091. }
  94092. assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
  94093. assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
  94094. assert( pSrc->pIndex==0
  94095. || pCost->plan.u.pIdx==0
  94096. || pCost->plan.u.pIdx==pSrc->pIndex
  94097. );
  94098. WHERETRACE(("best index is: %s\n",
  94099. ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
  94100. pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
  94101. ));
  94102. bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
  94103. bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
  94104. pCost->plan.wsFlags |= eqTermMask;
  94105. }
  94106. /*
  94107. ** Find the query plan for accessing table pSrc->pTab. Write the
  94108. ** best query plan and its cost into the WhereCost object supplied
  94109. ** as the last parameter. This function may calculate the cost of
  94110. ** both real and virtual table scans.
  94111. */
  94112. static void bestIndex(
  94113. Parse *pParse, /* The parsing context */
  94114. WhereClause *pWC, /* The WHERE clause */
  94115. struct SrcList_item *pSrc, /* The FROM clause term to search */
  94116. Bitmask notReady, /* Mask of cursors not available for indexing */
  94117. Bitmask notValid, /* Cursors not available for any purpose */
  94118. ExprList *pOrderBy, /* The ORDER BY clause */
  94119. WhereCost *pCost /* Lowest cost query plan */
  94120. ){
  94121. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94122. if( IsVirtual(pSrc->pTab) ){
  94123. sqlite3_index_info *p = 0;
  94124. bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
  94125. if( p->needToFreeIdxStr ){
  94126. sqlite3_free(p->idxStr);
  94127. }
  94128. sqlite3DbFree(pParse->db, p);
  94129. }else
  94130. #endif
  94131. {
  94132. bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
  94133. }
  94134. }
  94135. /*
  94136. ** Disable a term in the WHERE clause. Except, do not disable the term
  94137. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  94138. ** or USING clause of that join.
  94139. **
  94140. ** Consider the term t2.z='ok' in the following queries:
  94141. **
  94142. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  94143. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  94144. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  94145. **
  94146. ** The t2.z='ok' is disabled in the in (2) because it originates
  94147. ** in the ON clause. The term is disabled in (3) because it is not part
  94148. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  94149. **
  94150. ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
  94151. ** completely satisfied by indices.
  94152. **
  94153. ** Disabling a term causes that term to not be tested in the inner loop
  94154. ** of the join. Disabling is an optimization. When terms are satisfied
  94155. ** by indices, we disable them to prevent redundant tests in the inner
  94156. ** loop. We would get the correct results if nothing were ever disabled,
  94157. ** but joins might run a little slower. The trick is to disable as much
  94158. ** as we can without disabling too much. If we disabled in (1), we'd get
  94159. ** the wrong answer. See ticket #813.
  94160. */
  94161. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  94162. if( pTerm
  94163. && (pTerm->wtFlags & TERM_CODED)==0
  94164. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  94165. ){
  94166. pTerm->wtFlags |= TERM_CODED;
  94167. if( pTerm->iParent>=0 ){
  94168. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  94169. if( (--pOther->nChild)==0 ){
  94170. disableTerm(pLevel, pOther);
  94171. }
  94172. }
  94173. }
  94174. }
  94175. /*
  94176. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  94177. ** to the n registers starting at base.
  94178. **
  94179. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  94180. ** beginning and end of zAff are ignored. If all entries in zAff are
  94181. ** SQLITE_AFF_NONE, then no code gets generated.
  94182. **
  94183. ** This routine makes its own copy of zAff so that the caller is free
  94184. ** to modify zAff after this routine returns.
  94185. */
  94186. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  94187. Vdbe *v = pParse->pVdbe;
  94188. if( zAff==0 ){
  94189. assert( pParse->db->mallocFailed );
  94190. return;
  94191. }
  94192. assert( v!=0 );
  94193. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  94194. ** and end of the affinity string.
  94195. */
  94196. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  94197. n--;
  94198. base++;
  94199. zAff++;
  94200. }
  94201. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  94202. n--;
  94203. }
  94204. /* Code the OP_Affinity opcode if there is anything left to do. */
  94205. if( n>0 ){
  94206. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  94207. sqlite3VdbeChangeP4(v, -1, zAff, n);
  94208. sqlite3ExprCacheAffinityChange(pParse, base, n);
  94209. }
  94210. }
  94211. /*
  94212. ** Generate code for a single equality term of the WHERE clause. An equality
  94213. ** term can be either X=expr or X IN (...). pTerm is the term to be
  94214. ** coded.
  94215. **
  94216. ** The current value for the constraint is left in register iReg.
  94217. **
  94218. ** For a constraint of the form X=expr, the expression is evaluated and its
  94219. ** result is left on the stack. For constraints of the form X IN (...)
  94220. ** this routine sets up a loop that will iterate over all values of X.
  94221. */
  94222. static int codeEqualityTerm(
  94223. Parse *pParse, /* The parsing context */
  94224. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  94225. WhereLevel *pLevel, /* When level of the FROM clause we are working on */
  94226. int iTarget /* Attempt to leave results in this register */
  94227. ){
  94228. Expr *pX = pTerm->pExpr;
  94229. Vdbe *v = pParse->pVdbe;
  94230. int iReg; /* Register holding results */
  94231. assert( iTarget>0 );
  94232. if( pX->op==TK_EQ ){
  94233. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  94234. }else if( pX->op==TK_ISNULL ){
  94235. iReg = iTarget;
  94236. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  94237. #ifndef SQLITE_OMIT_SUBQUERY
  94238. }else{
  94239. int eType;
  94240. int iTab;
  94241. struct InLoop *pIn;
  94242. assert( pX->op==TK_IN );
  94243. iReg = iTarget;
  94244. eType = sqlite3FindInIndex(pParse, pX, 0);
  94245. iTab = pX->iTable;
  94246. sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  94247. assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
  94248. if( pLevel->u.in.nIn==0 ){
  94249. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  94250. }
  94251. pLevel->u.in.nIn++;
  94252. pLevel->u.in.aInLoop =
  94253. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  94254. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  94255. pIn = pLevel->u.in.aInLoop;
  94256. if( pIn ){
  94257. pIn += pLevel->u.in.nIn - 1;
  94258. pIn->iCur = iTab;
  94259. if( eType==IN_INDEX_ROWID ){
  94260. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  94261. }else{
  94262. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  94263. }
  94264. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  94265. }else{
  94266. pLevel->u.in.nIn = 0;
  94267. }
  94268. #endif
  94269. }
  94270. disableTerm(pLevel, pTerm);
  94271. return iReg;
  94272. }
  94273. /*
  94274. ** Generate code that will evaluate all == and IN constraints for an
  94275. ** index.
  94276. **
  94277. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  94278. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  94279. ** The index has as many as three equality constraints, but in this
  94280. ** example, the third "c" value is an inequality. So only two
  94281. ** constraints are coded. This routine will generate code to evaluate
  94282. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  94283. ** in consecutive registers and the index of the first register is returned.
  94284. **
  94285. ** In the example above nEq==2. But this subroutine works for any value
  94286. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  94287. ** The only thing it does is allocate the pLevel->iMem memory cell and
  94288. ** compute the affinity string.
  94289. **
  94290. ** This routine always allocates at least one memory cell and returns
  94291. ** the index of that memory cell. The code that
  94292. ** calls this routine will use that memory cell to store the termination
  94293. ** key value of the loop. If one or more IN operators appear, then
  94294. ** this routine allocates an additional nEq memory cells for internal
  94295. ** use.
  94296. **
  94297. ** Before returning, *pzAff is set to point to a buffer containing a
  94298. ** copy of the column affinity string of the index allocated using
  94299. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  94300. ** with equality constraints that use NONE affinity are set to
  94301. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  94302. **
  94303. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  94304. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  94305. **
  94306. ** In the example above, the index on t1(a) has TEXT affinity. But since
  94307. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  94308. ** no conversion should be attempted before using a t2.b value as part of
  94309. ** a key to search the index. Hence the first byte in the returned affinity
  94310. ** string in this example would be set to SQLITE_AFF_NONE.
  94311. */
  94312. static int codeAllEqualityTerms(
  94313. Parse *pParse, /* Parsing context */
  94314. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  94315. WhereClause *pWC, /* The WHERE clause */
  94316. Bitmask notReady, /* Which parts of FROM have not yet been coded */
  94317. int nExtraReg, /* Number of extra registers to allocate */
  94318. char **pzAff /* OUT: Set to point to affinity string */
  94319. ){
  94320. int nEq = pLevel->plan.nEq; /* The number of == or IN constraints to code */
  94321. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  94322. Index *pIdx; /* The index being used for this loop */
  94323. int iCur = pLevel->iTabCur; /* The cursor of the table */
  94324. WhereTerm *pTerm; /* A single constraint term */
  94325. int j; /* Loop counter */
  94326. int regBase; /* Base register */
  94327. int nReg; /* Number of registers to allocate */
  94328. char *zAff; /* Affinity string to return */
  94329. /* This module is only called on query plans that use an index. */
  94330. assert( pLevel->plan.wsFlags & WHERE_INDEXED );
  94331. pIdx = pLevel->plan.u.pIdx;
  94332. /* Figure out how many memory cells we will need then allocate them.
  94333. */
  94334. regBase = pParse->nMem + 1;
  94335. nReg = pLevel->plan.nEq + nExtraReg;
  94336. pParse->nMem += nReg;
  94337. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  94338. if( !zAff ){
  94339. pParse->db->mallocFailed = 1;
  94340. }
  94341. /* Evaluate the equality constraints
  94342. */
  94343. assert( pIdx->nColumn>=nEq );
  94344. for(j=0; j<nEq; j++){
  94345. int r1;
  94346. int k = pIdx->aiColumn[j];
  94347. pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
  94348. if( NEVER(pTerm==0) ) break;
  94349. /* The following true for indices with redundant columns.
  94350. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  94351. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  94352. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  94353. r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
  94354. if( r1!=regBase+j ){
  94355. if( nReg==1 ){
  94356. sqlite3ReleaseTempReg(pParse, regBase);
  94357. regBase = r1;
  94358. }else{
  94359. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  94360. }
  94361. }
  94362. testcase( pTerm->eOperator & WO_ISNULL );
  94363. testcase( pTerm->eOperator & WO_IN );
  94364. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  94365. Expr *pRight = pTerm->pExpr->pRight;
  94366. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  94367. if( zAff ){
  94368. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  94369. zAff[j] = SQLITE_AFF_NONE;
  94370. }
  94371. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  94372. zAff[j] = SQLITE_AFF_NONE;
  94373. }
  94374. }
  94375. }
  94376. }
  94377. *pzAff = zAff;
  94378. return regBase;
  94379. }
  94380. #ifndef SQLITE_OMIT_EXPLAIN
  94381. /*
  94382. ** This routine is a helper for explainIndexRange() below
  94383. **
  94384. ** pStr holds the text of an expression that we are building up one term
  94385. ** at a time. This routine adds a new term to the end of the expression.
  94386. ** Terms are separated by AND so add the "AND" text for second and subsequent
  94387. ** terms only.
  94388. */
  94389. static void explainAppendTerm(
  94390. StrAccum *pStr, /* The text expression being built */
  94391. int iTerm, /* Index of this term. First is zero */
  94392. const char *zColumn, /* Name of the column */
  94393. const char *zOp /* Name of the operator */
  94394. ){
  94395. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  94396. sqlite3StrAccumAppend(pStr, zColumn, -1);
  94397. sqlite3StrAccumAppend(pStr, zOp, 1);
  94398. sqlite3StrAccumAppend(pStr, "?", 1);
  94399. }
  94400. /*
  94401. ** Argument pLevel describes a strategy for scanning table pTab. This
  94402. ** function returns a pointer to a string buffer containing a description
  94403. ** of the subset of table rows scanned by the strategy in the form of an
  94404. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  94405. **
  94406. ** For example, if the query:
  94407. **
  94408. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  94409. **
  94410. ** is run and there is an index on (a, b), then this function returns a
  94411. ** string similar to:
  94412. **
  94413. ** "a=? AND b>?"
  94414. **
  94415. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  94416. ** It is the responsibility of the caller to free the buffer when it is
  94417. ** no longer required.
  94418. */
  94419. static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
  94420. WherePlan *pPlan = &pLevel->plan;
  94421. Index *pIndex = pPlan->u.pIdx;
  94422. int nEq = pPlan->nEq;
  94423. int i, j;
  94424. Column *aCol = pTab->aCol;
  94425. int *aiColumn = pIndex->aiColumn;
  94426. StrAccum txt;
  94427. if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  94428. return 0;
  94429. }
  94430. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  94431. txt.db = db;
  94432. sqlite3StrAccumAppend(&txt, " (", 2);
  94433. for(i=0; i<nEq; i++){
  94434. explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
  94435. }
  94436. j = i;
  94437. if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
  94438. explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
  94439. }
  94440. if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
  94441. explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
  94442. }
  94443. sqlite3StrAccumAppend(&txt, ")", 1);
  94444. return sqlite3StrAccumFinish(&txt);
  94445. }
  94446. /*
  94447. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  94448. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  94449. ** record is added to the output to describe the table scan strategy in
  94450. ** pLevel.
  94451. */
  94452. static void explainOneScan(
  94453. Parse *pParse, /* Parse context */
  94454. SrcList *pTabList, /* Table list this loop refers to */
  94455. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  94456. int iLevel, /* Value for "level" column of output */
  94457. int iFrom, /* Value for "from" column of output */
  94458. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  94459. ){
  94460. if( pParse->explain==2 ){
  94461. u32 flags = pLevel->plan.wsFlags;
  94462. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  94463. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  94464. sqlite3 *db = pParse->db; /* Database handle */
  94465. char *zMsg; /* Text to add to EQP output */
  94466. sqlite3_int64 nRow; /* Expected number of rows visited by scan */
  94467. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  94468. int isSearch; /* True for a SEARCH. False for SCAN. */
  94469. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  94470. isSearch = (pLevel->plan.nEq>0)
  94471. || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  94472. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  94473. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  94474. if( pItem->pSelect ){
  94475. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  94476. }else{
  94477. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  94478. }
  94479. if( pItem->zAlias ){
  94480. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  94481. }
  94482. if( (flags & WHERE_INDEXED)!=0 ){
  94483. char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
  94484. zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
  94485. ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
  94486. ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
  94487. ((flags & WHERE_TEMP_INDEX)?"":" "),
  94488. ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
  94489. zWhere
  94490. );
  94491. sqlite3DbFree(db, zWhere);
  94492. }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  94493. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  94494. if( flags&WHERE_ROWID_EQ ){
  94495. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  94496. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  94497. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  94498. }else if( flags&WHERE_BTM_LIMIT ){
  94499. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  94500. }else if( flags&WHERE_TOP_LIMIT ){
  94501. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  94502. }
  94503. }
  94504. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94505. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  94506. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  94507. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  94508. pVtabIdx->idxNum, pVtabIdx->idxStr);
  94509. }
  94510. #endif
  94511. if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
  94512. testcase( wctrlFlags & WHERE_ORDERBY_MIN );
  94513. nRow = 1;
  94514. }else{
  94515. nRow = (sqlite3_int64)pLevel->plan.nRow;
  94516. }
  94517. zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
  94518. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  94519. }
  94520. }
  94521. #else
  94522. # define explainOneScan(u,v,w,x,y,z)
  94523. #endif /* SQLITE_OMIT_EXPLAIN */
  94524. /*
  94525. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  94526. ** implementation described by pWInfo.
  94527. */
  94528. static Bitmask codeOneLoopStart(
  94529. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  94530. int iLevel, /* Which level of pWInfo->a[] should be coded */
  94531. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  94532. Bitmask notReady /* Which tables are currently available */
  94533. ){
  94534. int j, k; /* Loop counters */
  94535. int iCur; /* The VDBE cursor for the table */
  94536. int addrNxt; /* Where to jump to continue with the next IN case */
  94537. int omitTable; /* True if we use the index only */
  94538. int bRev; /* True if we need to scan in reverse order */
  94539. WhereLevel *pLevel; /* The where level to be coded */
  94540. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  94541. WhereTerm *pTerm; /* A WHERE clause term */
  94542. Parse *pParse; /* Parsing context */
  94543. Vdbe *v; /* The prepared stmt under constructions */
  94544. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  94545. int addrBrk; /* Jump here to break out of the loop */
  94546. int addrCont; /* Jump here to continue with next cycle */
  94547. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  94548. int iReleaseReg = 0; /* Temp register to free before returning */
  94549. pParse = pWInfo->pParse;
  94550. v = pParse->pVdbe;
  94551. pWC = pWInfo->pWC;
  94552. pLevel = &pWInfo->a[iLevel];
  94553. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  94554. iCur = pTabItem->iCursor;
  94555. bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
  94556. omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
  94557. && (wctrlFlags & WHERE_FORCE_TABLE)==0;
  94558. /* Create labels for the "break" and "continue" instructions
  94559. ** for the current loop. Jump to addrBrk to break out of a loop.
  94560. ** Jump to cont to go immediately to the next iteration of the
  94561. ** loop.
  94562. **
  94563. ** When there is an IN operator, we also have a "addrNxt" label that
  94564. ** means to continue with the next IN value combination. When
  94565. ** there are no IN operators in the constraints, the "addrNxt" label
  94566. ** is the same as "addrBrk".
  94567. */
  94568. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  94569. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  94570. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  94571. ** initialize a memory cell that records if this table matches any
  94572. ** row of the left table of the join.
  94573. */
  94574. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  94575. pLevel->iLeftJoin = ++pParse->nMem;
  94576. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  94577. VdbeComment((v, "init LEFT JOIN no-match flag"));
  94578. }
  94579. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94580. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  94581. /* Case 0: The table is a virtual-table. Use the VFilter and VNext
  94582. ** to access the data.
  94583. */
  94584. int iReg; /* P3 Value for OP_VFilter */
  94585. sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
  94586. int nConstraint = pVtabIdx->nConstraint;
  94587. struct sqlite3_index_constraint_usage *aUsage =
  94588. pVtabIdx->aConstraintUsage;
  94589. const struct sqlite3_index_constraint *aConstraint =
  94590. pVtabIdx->aConstraint;
  94591. sqlite3ExprCachePush(pParse);
  94592. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  94593. for(j=1; j<=nConstraint; j++){
  94594. for(k=0; k<nConstraint; k++){
  94595. if( aUsage[k].argvIndex==j ){
  94596. int iTerm = aConstraint[k].iTermOffset;
  94597. sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
  94598. break;
  94599. }
  94600. }
  94601. if( k==nConstraint ) break;
  94602. }
  94603. sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
  94604. sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
  94605. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
  94606. pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
  94607. pVtabIdx->needToFreeIdxStr = 0;
  94608. for(j=0; j<nConstraint; j++){
  94609. if( aUsage[j].omit ){
  94610. int iTerm = aConstraint[j].iTermOffset;
  94611. disableTerm(pLevel, &pWC->a[iTerm]);
  94612. }
  94613. }
  94614. pLevel->op = OP_VNext;
  94615. pLevel->p1 = iCur;
  94616. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  94617. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  94618. sqlite3ExprCachePop(pParse, 1);
  94619. }else
  94620. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  94621. if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
  94622. /* Case 1: We can directly reference a single row using an
  94623. ** equality comparison against the ROWID field. Or
  94624. ** we reference multiple rows using a "rowid IN (...)"
  94625. ** construct.
  94626. */
  94627. iReleaseReg = sqlite3GetTempReg(pParse);
  94628. pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
  94629. assert( pTerm!=0 );
  94630. assert( pTerm->pExpr!=0 );
  94631. assert( pTerm->leftCursor==iCur );
  94632. assert( omitTable==0 );
  94633. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  94634. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
  94635. addrNxt = pLevel->addrNxt;
  94636. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  94637. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  94638. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  94639. VdbeComment((v, "pk"));
  94640. pLevel->op = OP_Noop;
  94641. }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
  94642. /* Case 2: We have an inequality comparison against the ROWID field.
  94643. */
  94644. int testOp = OP_Noop;
  94645. int start;
  94646. int memEndValue = 0;
  94647. WhereTerm *pStart, *pEnd;
  94648. assert( omitTable==0 );
  94649. pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
  94650. pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
  94651. if( bRev ){
  94652. pTerm = pStart;
  94653. pStart = pEnd;
  94654. pEnd = pTerm;
  94655. }
  94656. if( pStart ){
  94657. Expr *pX; /* The expression that defines the start bound */
  94658. int r1, rTemp; /* Registers for holding the start boundary */
  94659. /* The following constant maps TK_xx codes into corresponding
  94660. ** seek opcodes. It depends on a particular ordering of TK_xx
  94661. */
  94662. const u8 aMoveOp[] = {
  94663. /* TK_GT */ OP_SeekGt,
  94664. /* TK_LE */ OP_SeekLe,
  94665. /* TK_LT */ OP_SeekLt,
  94666. /* TK_GE */ OP_SeekGe
  94667. };
  94668. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  94669. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  94670. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  94671. testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  94672. pX = pStart->pExpr;
  94673. assert( pX!=0 );
  94674. assert( pStart->leftCursor==iCur );
  94675. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  94676. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  94677. VdbeComment((v, "pk"));
  94678. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  94679. sqlite3ReleaseTempReg(pParse, rTemp);
  94680. disableTerm(pLevel, pStart);
  94681. }else{
  94682. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  94683. }
  94684. if( pEnd ){
  94685. Expr *pX;
  94686. pX = pEnd->pExpr;
  94687. assert( pX!=0 );
  94688. assert( pEnd->leftCursor==iCur );
  94689. testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  94690. memEndValue = ++pParse->nMem;
  94691. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  94692. if( pX->op==TK_LT || pX->op==TK_GT ){
  94693. testOp = bRev ? OP_Le : OP_Ge;
  94694. }else{
  94695. testOp = bRev ? OP_Lt : OP_Gt;
  94696. }
  94697. disableTerm(pLevel, pEnd);
  94698. }
  94699. start = sqlite3VdbeCurrentAddr(v);
  94700. pLevel->op = bRev ? OP_Prev : OP_Next;
  94701. pLevel->p1 = iCur;
  94702. pLevel->p2 = start;
  94703. if( pStart==0 && pEnd==0 ){
  94704. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  94705. }else{
  94706. assert( pLevel->p5==0 );
  94707. }
  94708. if( testOp!=OP_Noop ){
  94709. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  94710. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  94711. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  94712. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  94713. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  94714. }
  94715. }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
  94716. /* Case 3: A scan using an index.
  94717. **
  94718. ** The WHERE clause may contain zero or more equality
  94719. ** terms ("==" or "IN" operators) that refer to the N
  94720. ** left-most columns of the index. It may also contain
  94721. ** inequality constraints (>, <, >= or <=) on the indexed
  94722. ** column that immediately follows the N equalities. Only
  94723. ** the right-most column can be an inequality - the rest must
  94724. ** use the "==" and "IN" operators. For example, if the
  94725. ** index is on (x,y,z), then the following clauses are all
  94726. ** optimized:
  94727. **
  94728. ** x=5
  94729. ** x=5 AND y=10
  94730. ** x=5 AND y<10
  94731. ** x=5 AND y>5 AND y<10
  94732. ** x=5 AND y=5 AND z<=10
  94733. **
  94734. ** The z<10 term of the following cannot be used, only
  94735. ** the x=5 term:
  94736. **
  94737. ** x=5 AND z<10
  94738. **
  94739. ** N may be zero if there are inequality constraints.
  94740. ** If there are no inequality constraints, then N is at
  94741. ** least one.
  94742. **
  94743. ** This case is also used when there are no WHERE clause
  94744. ** constraints but an index is selected anyway, in order
  94745. ** to force the output order to conform to an ORDER BY.
  94746. */
  94747. static const u8 aStartOp[] = {
  94748. 0,
  94749. 0,
  94750. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  94751. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  94752. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  94753. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  94754. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  94755. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  94756. };
  94757. static const u8 aEndOp[] = {
  94758. OP_Noop, /* 0: (!end_constraints) */
  94759. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  94760. OP_IdxLT /* 2: (end_constraints && bRev) */
  94761. };
  94762. int nEq = pLevel->plan.nEq; /* Number of == or IN terms */
  94763. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  94764. int regBase; /* Base register holding constraint values */
  94765. int r1; /* Temp register */
  94766. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  94767. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  94768. int startEq; /* True if range start uses ==, >= or <= */
  94769. int endEq; /* True if range end uses ==, >= or <= */
  94770. int start_constraints; /* Start of range is constrained */
  94771. int nConstraint; /* Number of constraint terms */
  94772. Index *pIdx; /* The index we will be using */
  94773. int iIdxCur; /* The VDBE cursor for the index */
  94774. int nExtraReg = 0; /* Number of extra registers needed */
  94775. int op; /* Instruction opcode */
  94776. char *zStartAff; /* Affinity for start of range constraint */
  94777. char *zEndAff; /* Affinity for end of range constraint */
  94778. pIdx = pLevel->plan.u.pIdx;
  94779. iIdxCur = pLevel->iIdxCur;
  94780. k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */
  94781. /* If this loop satisfies a sort order (pOrderBy) request that
  94782. ** was passed to this function to implement a "SELECT min(x) ..."
  94783. ** query, then the caller will only allow the loop to run for
  94784. ** a single iteration. This means that the first row returned
  94785. ** should not have a NULL value stored in 'x'. If column 'x' is
  94786. ** the first one after the nEq equality constraints in the index,
  94787. ** this requires some special handling.
  94788. */
  94789. if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
  94790. && (pLevel->plan.wsFlags&WHERE_ORDERBY)
  94791. && (pIdx->nColumn>nEq)
  94792. ){
  94793. /* assert( pOrderBy->nExpr==1 ); */
  94794. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  94795. isMinQuery = 1;
  94796. nExtraReg = 1;
  94797. }
  94798. /* Find any inequality constraint terms for the start and end
  94799. ** of the range.
  94800. */
  94801. if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
  94802. pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
  94803. nExtraReg = 1;
  94804. }
  94805. if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
  94806. pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
  94807. nExtraReg = 1;
  94808. }
  94809. /* Generate code to evaluate all constraint terms using == or IN
  94810. ** and store the values of those terms in an array of registers
  94811. ** starting at regBase.
  94812. */
  94813. regBase = codeAllEqualityTerms(
  94814. pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
  94815. );
  94816. zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
  94817. addrNxt = pLevel->addrNxt;
  94818. /* If we are doing a reverse order scan on an ascending index, or
  94819. ** a forward order scan on a descending index, interchange the
  94820. ** start and end terms (pRangeStart and pRangeEnd).
  94821. */
  94822. if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
  94823. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  94824. }
  94825. testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
  94826. testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
  94827. testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
  94828. testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
  94829. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  94830. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  94831. start_constraints = pRangeStart || nEq>0;
  94832. /* Seek the index cursor to the start of the range. */
  94833. nConstraint = nEq;
  94834. if( pRangeStart ){
  94835. Expr *pRight = pRangeStart->pExpr->pRight;
  94836. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  94837. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  94838. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  94839. }
  94840. if( zStartAff ){
  94841. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  94842. /* Since the comparison is to be performed with no conversions
  94843. ** applied to the operands, set the affinity to apply to pRight to
  94844. ** SQLITE_AFF_NONE. */
  94845. zStartAff[nEq] = SQLITE_AFF_NONE;
  94846. }
  94847. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  94848. zStartAff[nEq] = SQLITE_AFF_NONE;
  94849. }
  94850. }
  94851. nConstraint++;
  94852. testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  94853. }else if( isMinQuery ){
  94854. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  94855. nConstraint++;
  94856. startEq = 0;
  94857. start_constraints = 1;
  94858. }
  94859. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  94860. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  94861. assert( op!=0 );
  94862. testcase( op==OP_Rewind );
  94863. testcase( op==OP_Last );
  94864. testcase( op==OP_SeekGt );
  94865. testcase( op==OP_SeekGe );
  94866. testcase( op==OP_SeekLe );
  94867. testcase( op==OP_SeekLt );
  94868. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  94869. /* Load the value for the inequality constraint at the end of the
  94870. ** range (if any).
  94871. */
  94872. nConstraint = nEq;
  94873. if( pRangeEnd ){
  94874. Expr *pRight = pRangeEnd->pExpr->pRight;
  94875. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  94876. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  94877. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  94878. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  94879. }
  94880. if( zEndAff ){
  94881. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  94882. /* Since the comparison is to be performed with no conversions
  94883. ** applied to the operands, set the affinity to apply to pRight to
  94884. ** SQLITE_AFF_NONE. */
  94885. zEndAff[nEq] = SQLITE_AFF_NONE;
  94886. }
  94887. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  94888. zEndAff[nEq] = SQLITE_AFF_NONE;
  94889. }
  94890. }
  94891. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  94892. nConstraint++;
  94893. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
  94894. }
  94895. sqlite3DbFree(pParse->db, zStartAff);
  94896. sqlite3DbFree(pParse->db, zEndAff);
  94897. /* Top of the loop body */
  94898. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  94899. /* Check if the index cursor is past the end of the range. */
  94900. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  94901. testcase( op==OP_Noop );
  94902. testcase( op==OP_IdxGE );
  94903. testcase( op==OP_IdxLT );
  94904. if( op!=OP_Noop ){
  94905. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  94906. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  94907. }
  94908. /* If there are inequality constraints, check that the value
  94909. ** of the table column that the inequality contrains is not NULL.
  94910. ** If it is, jump to the next iteration of the loop.
  94911. */
  94912. r1 = sqlite3GetTempReg(pParse);
  94913. testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
  94914. testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
  94915. if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  94916. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  94917. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  94918. }
  94919. sqlite3ReleaseTempReg(pParse, r1);
  94920. /* Seek the table cursor, if required */
  94921. disableTerm(pLevel, pRangeStart);
  94922. disableTerm(pLevel, pRangeEnd);
  94923. if( !omitTable ){
  94924. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  94925. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  94926. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  94927. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  94928. }
  94929. /* Record the instruction used to terminate the loop. Disable
  94930. ** WHERE clause terms made redundant by the index range scan.
  94931. */
  94932. if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
  94933. pLevel->op = OP_Noop;
  94934. }else if( bRev ){
  94935. pLevel->op = OP_Prev;
  94936. }else{
  94937. pLevel->op = OP_Next;
  94938. }
  94939. pLevel->p1 = iIdxCur;
  94940. }else
  94941. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  94942. if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
  94943. /* Case 4: Two or more separately indexed terms connected by OR
  94944. **
  94945. ** Example:
  94946. **
  94947. ** CREATE TABLE t1(a,b,c,d);
  94948. ** CREATE INDEX i1 ON t1(a);
  94949. ** CREATE INDEX i2 ON t1(b);
  94950. ** CREATE INDEX i3 ON t1(c);
  94951. **
  94952. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  94953. **
  94954. ** In the example, there are three indexed terms connected by OR.
  94955. ** The top of the loop looks like this:
  94956. **
  94957. ** Null 1 # Zero the rowset in reg 1
  94958. **
  94959. ** Then, for each indexed term, the following. The arguments to
  94960. ** RowSetTest are such that the rowid of the current row is inserted
  94961. ** into the RowSet. If it is already present, control skips the
  94962. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  94963. **
  94964. ** sqlite3WhereBegin(<term>)
  94965. ** RowSetTest # Insert rowid into rowset
  94966. ** Gosub 2 A
  94967. ** sqlite3WhereEnd()
  94968. **
  94969. ** Following the above, code to terminate the loop. Label A, the target
  94970. ** of the Gosub above, jumps to the instruction right after the Goto.
  94971. **
  94972. ** Null 1 # Zero the rowset in reg 1
  94973. ** Goto B # The loop is finished.
  94974. **
  94975. ** A: <loop body> # Return data, whatever.
  94976. **
  94977. ** Return 2 # Jump back to the Gosub
  94978. **
  94979. ** B: <after the loop>
  94980. **
  94981. */
  94982. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  94983. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  94984. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  94985. int regRowset = 0; /* Register for RowSet object */
  94986. int regRowid = 0; /* Register holding rowid */
  94987. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  94988. int iRetInit; /* Address of regReturn init */
  94989. int untestedTerms = 0; /* Some terms not completely tested */
  94990. int ii;
  94991. pTerm = pLevel->plan.u.pTerm;
  94992. assert( pTerm!=0 );
  94993. assert( pTerm->eOperator==WO_OR );
  94994. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  94995. pOrWc = &pTerm->u.pOrInfo->wc;
  94996. pLevel->op = OP_Return;
  94997. pLevel->p1 = regReturn;
  94998. /* Set up a new SrcList ni pOrTab containing the table being scanned
  94999. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  95000. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  95001. */
  95002. if( pWInfo->nLevel>1 ){
  95003. int nNotReady; /* The number of notReady tables */
  95004. struct SrcList_item *origSrc; /* Original list of tables */
  95005. nNotReady = pWInfo->nLevel - iLevel - 1;
  95006. pOrTab = sqlite3StackAllocRaw(pParse->db,
  95007. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  95008. if( pOrTab==0 ) return notReady;
  95009. pOrTab->nAlloc = (i16)(nNotReady + 1);
  95010. pOrTab->nSrc = pOrTab->nAlloc;
  95011. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  95012. origSrc = pWInfo->pTabList->a;
  95013. for(k=1; k<=nNotReady; k++){
  95014. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  95015. }
  95016. }else{
  95017. pOrTab = pWInfo->pTabList;
  95018. }
  95019. /* Initialize the rowset register to contain NULL. An SQL NULL is
  95020. ** equivalent to an empty rowset.
  95021. **
  95022. ** Also initialize regReturn to contain the address of the instruction
  95023. ** immediately following the OP_Return at the bottom of the loop. This
  95024. ** is required in a few obscure LEFT JOIN cases where control jumps
  95025. ** over the top of the loop into the body of it. In this case the
  95026. ** correct response for the end-of-loop code (the OP_Return) is to
  95027. ** fall through to the next instruction, just as an OP_Next does if
  95028. ** called on an uninitialized cursor.
  95029. */
  95030. if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  95031. regRowset = ++pParse->nMem;
  95032. regRowid = ++pParse->nMem;
  95033. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  95034. }
  95035. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  95036. for(ii=0; ii<pOrWc->nTerm; ii++){
  95037. WhereTerm *pOrTerm = &pOrWc->a[ii];
  95038. if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
  95039. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  95040. /* Loop through table entries that match term pOrTerm. */
  95041. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
  95042. WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
  95043. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
  95044. if( pSubWInfo ){
  95045. explainOneScan(
  95046. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  95047. );
  95048. if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  95049. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  95050. int r;
  95051. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  95052. regRowid);
  95053. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  95054. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  95055. }
  95056. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  95057. /* The pSubWInfo->untestedTerms flag means that this OR term
  95058. ** contained one or more AND term from a notReady table. The
  95059. ** terms from the notReady table could not be tested and will
  95060. ** need to be tested later.
  95061. */
  95062. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  95063. /* Finish the loop through table entries that match term pOrTerm. */
  95064. sqlite3WhereEnd(pSubWInfo);
  95065. }
  95066. }
  95067. }
  95068. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  95069. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  95070. sqlite3VdbeResolveLabel(v, iLoopBody);
  95071. if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
  95072. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  95073. }else
  95074. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  95075. {
  95076. /* Case 5: There is no usable index. We must do a complete
  95077. ** scan of the entire table.
  95078. */
  95079. static const u8 aStep[] = { OP_Next, OP_Prev };
  95080. static const u8 aStart[] = { OP_Rewind, OP_Last };
  95081. assert( bRev==0 || bRev==1 );
  95082. assert( omitTable==0 );
  95083. pLevel->op = aStep[bRev];
  95084. pLevel->p1 = iCur;
  95085. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  95086. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  95087. }
  95088. notReady &= ~getMask(pWC->pMaskSet, iCur);
  95089. /* Insert code to test every subexpression that can be completely
  95090. ** computed using the current set of tables.
  95091. **
  95092. ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
  95093. ** the use of indices become tests that are evaluated against each row of
  95094. ** the relevant input tables.
  95095. */
  95096. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  95097. Expr *pE;
  95098. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
  95099. testcase( pTerm->wtFlags & TERM_CODED );
  95100. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  95101. if( (pTerm->prereqAll & notReady)!=0 ){
  95102. testcase( pWInfo->untestedTerms==0
  95103. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  95104. pWInfo->untestedTerms = 1;
  95105. continue;
  95106. }
  95107. pE = pTerm->pExpr;
  95108. assert( pE!=0 );
  95109. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  95110. continue;
  95111. }
  95112. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  95113. pTerm->wtFlags |= TERM_CODED;
  95114. }
  95115. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  95116. ** at least one row of the right table has matched the left table.
  95117. */
  95118. if( pLevel->iLeftJoin ){
  95119. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  95120. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  95121. VdbeComment((v, "record LEFT JOIN hit"));
  95122. sqlite3ExprCacheClear(pParse);
  95123. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  95124. testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
  95125. testcase( pTerm->wtFlags & TERM_CODED );
  95126. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  95127. if( (pTerm->prereqAll & notReady)!=0 ){
  95128. assert( pWInfo->untestedTerms );
  95129. continue;
  95130. }
  95131. assert( pTerm->pExpr );
  95132. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  95133. pTerm->wtFlags |= TERM_CODED;
  95134. }
  95135. }
  95136. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  95137. return notReady;
  95138. }
  95139. #if defined(SQLITE_TEST)
  95140. /*
  95141. ** The following variable holds a text description of query plan generated
  95142. ** by the most recent call to sqlite3WhereBegin(). Each call to WhereBegin
  95143. ** overwrites the previous. This information is used for testing and
  95144. ** analysis only.
  95145. */
  95146. SQLITE_API char sqlite3_query_plan[BMS*2*40]; /* Text of the join */
  95147. static int nQPlan = 0; /* Next free slow in _query_plan[] */
  95148. #endif /* SQLITE_TEST */
  95149. /*
  95150. ** Free a WhereInfo structure
  95151. */
  95152. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  95153. if( ALWAYS(pWInfo) ){
  95154. int i;
  95155. for(i=0; i<pWInfo->nLevel; i++){
  95156. sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
  95157. if( pInfo ){
  95158. /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
  95159. if( pInfo->needToFreeIdxStr ){
  95160. sqlite3_free(pInfo->idxStr);
  95161. }
  95162. sqlite3DbFree(db, pInfo);
  95163. }
  95164. if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
  95165. Index *pIdx = pWInfo->a[i].plan.u.pIdx;
  95166. if( pIdx ){
  95167. sqlite3DbFree(db, pIdx->zColAff);
  95168. sqlite3DbFree(db, pIdx);
  95169. }
  95170. }
  95171. }
  95172. whereClauseClear(pWInfo->pWC);
  95173. sqlite3DbFree(db, pWInfo);
  95174. }
  95175. }
  95176. /*
  95177. ** Generate the beginning of the loop used for WHERE clause processing.
  95178. ** The return value is a pointer to an opaque structure that contains
  95179. ** information needed to terminate the loop. Later, the calling routine
  95180. ** should invoke sqlite3WhereEnd() with the return value of this function
  95181. ** in order to complete the WHERE clause processing.
  95182. **
  95183. ** If an error occurs, this routine returns NULL.
  95184. **
  95185. ** The basic idea is to do a nested loop, one loop for each table in
  95186. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  95187. ** same as a SELECT with only a single table in the FROM clause.) For
  95188. ** example, if the SQL is this:
  95189. **
  95190. ** SELECT * FROM t1, t2, t3 WHERE ...;
  95191. **
  95192. ** Then the code generated is conceptually like the following:
  95193. **
  95194. ** foreach row1 in t1 do \ Code generated
  95195. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  95196. ** foreach row3 in t3 do /
  95197. ** ...
  95198. ** end \ Code generated
  95199. ** end |-- by sqlite3WhereEnd()
  95200. ** end /
  95201. **
  95202. ** Note that the loops might not be nested in the order in which they
  95203. ** appear in the FROM clause if a different order is better able to make
  95204. ** use of indices. Note also that when the IN operator appears in
  95205. ** the WHERE clause, it might result in additional nested loops for
  95206. ** scanning through all values on the right-hand side of the IN.
  95207. **
  95208. ** There are Btree cursors associated with each table. t1 uses cursor
  95209. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  95210. ** And so forth. This routine generates code to open those VDBE cursors
  95211. ** and sqlite3WhereEnd() generates the code to close them.
  95212. **
  95213. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  95214. ** in pTabList pointing at their appropriate entries. The [...] code
  95215. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  95216. ** data from the various tables of the loop.
  95217. **
  95218. ** If the WHERE clause is empty, the foreach loops must each scan their
  95219. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  95220. ** the tables have indices and there are terms in the WHERE clause that
  95221. ** refer to those indices, a complete table scan can be avoided and the
  95222. ** code will run much faster. Most of the work of this routine is checking
  95223. ** to see if there are indices that can be used to speed up the loop.
  95224. **
  95225. ** Terms of the WHERE clause are also used to limit which rows actually
  95226. ** make it to the "..." in the middle of the loop. After each "foreach",
  95227. ** terms of the WHERE clause that use only terms in that loop and outer
  95228. ** loops are evaluated and if false a jump is made around all subsequent
  95229. ** inner loops (or around the "..." if the test occurs within the inner-
  95230. ** most loop)
  95231. **
  95232. ** OUTER JOINS
  95233. **
  95234. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  95235. **
  95236. ** foreach row1 in t1 do
  95237. ** flag = 0
  95238. ** foreach row2 in t2 do
  95239. ** start:
  95240. ** ...
  95241. ** flag = 1
  95242. ** end
  95243. ** if flag==0 then
  95244. ** move the row2 cursor to a null row
  95245. ** goto start
  95246. ** fi
  95247. ** end
  95248. **
  95249. ** ORDER BY CLAUSE PROCESSING
  95250. **
  95251. ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
  95252. ** if there is one. If there is no ORDER BY clause or if this routine
  95253. ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
  95254. **
  95255. ** If an index can be used so that the natural output order of the table
  95256. ** scan is correct for the ORDER BY clause, then that index is used and
  95257. ** *ppOrderBy is set to NULL. This is an optimization that prevents an
  95258. ** unnecessary sort of the result set if an index appropriate for the
  95259. ** ORDER BY clause already exists.
  95260. **
  95261. ** If the where clause loops cannot be arranged to provide the correct
  95262. ** output order, then the *ppOrderBy is unchanged.
  95263. */
  95264. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  95265. Parse *pParse, /* The parser context */
  95266. SrcList *pTabList, /* A list of all tables to be scanned */
  95267. Expr *pWhere, /* The WHERE clause */
  95268. ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
  95269. u16 wctrlFlags /* One of the WHERE_* flags defined in sqliteInt.h */
  95270. ){
  95271. int i; /* Loop counter */
  95272. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  95273. int nTabList; /* Number of elements in pTabList */
  95274. WhereInfo *pWInfo; /* Will become the return value of this function */
  95275. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  95276. Bitmask notReady; /* Cursors that are not yet positioned */
  95277. WhereMaskSet *pMaskSet; /* The expression mask set */
  95278. WhereClause *pWC; /* Decomposition of the WHERE clause */
  95279. struct SrcList_item *pTabItem; /* A single entry from pTabList */
  95280. WhereLevel *pLevel; /* A single level in the pWInfo list */
  95281. int iFrom; /* First unused FROM clause element */
  95282. int andFlags; /* AND-ed combination of all pWC->a[].wtFlags */
  95283. sqlite3 *db; /* Database connection */
  95284. /* The number of tables in the FROM clause is limited by the number of
  95285. ** bits in a Bitmask
  95286. */
  95287. testcase( pTabList->nSrc==BMS );
  95288. if( pTabList->nSrc>BMS ){
  95289. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  95290. return 0;
  95291. }
  95292. /* This function normally generates a nested loop for all tables in
  95293. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  95294. ** only generate code for the first table in pTabList and assume that
  95295. ** any cursors associated with subsequent tables are uninitialized.
  95296. */
  95297. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  95298. /* Allocate and initialize the WhereInfo structure that will become the
  95299. ** return value. A single allocation is used to store the WhereInfo
  95300. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  95301. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  95302. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  95303. ** some architectures. Hence the ROUND8() below.
  95304. */
  95305. db = pParse->db;
  95306. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  95307. pWInfo = sqlite3DbMallocZero(db,
  95308. nByteWInfo +
  95309. sizeof(WhereClause) +
  95310. sizeof(WhereMaskSet)
  95311. );
  95312. if( db->mallocFailed ){
  95313. sqlite3DbFree(db, pWInfo);
  95314. pWInfo = 0;
  95315. goto whereBeginError;
  95316. }
  95317. pWInfo->nLevel = nTabList;
  95318. pWInfo->pParse = pParse;
  95319. pWInfo->pTabList = pTabList;
  95320. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  95321. pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
  95322. pWInfo->wctrlFlags = wctrlFlags;
  95323. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  95324. pMaskSet = (WhereMaskSet*)&pWC[1];
  95325. /* Split the WHERE clause into separate subexpressions where each
  95326. ** subexpression is separated by an AND operator.
  95327. */
  95328. initMaskSet(pMaskSet);
  95329. whereClauseInit(pWC, pParse, pMaskSet);
  95330. sqlite3ExprCodeConstants(pParse, pWhere);
  95331. whereSplit(pWC, pWhere, TK_AND); /* IMP: R-15842-53296 */
  95332. /* Special case: a WHERE clause that is constant. Evaluate the
  95333. ** expression and either jump over all of the code or fall thru.
  95334. */
  95335. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  95336. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  95337. pWhere = 0;
  95338. }
  95339. /* Assign a bit from the bitmask to every term in the FROM clause.
  95340. **
  95341. ** When assigning bitmask values to FROM clause cursors, it must be
  95342. ** the case that if X is the bitmask for the N-th FROM clause term then
  95343. ** the bitmask for all FROM clause terms to the left of the N-th term
  95344. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  95345. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  95346. ** of the join. Subtracting one from the right table bitmask gives a
  95347. ** bitmask for all tables to the left of the join. Knowing the bitmask
  95348. ** for all tables to the left of a left join is important. Ticket #3015.
  95349. **
  95350. ** Configure the WhereClause.vmask variable so that bits that correspond
  95351. ** to virtual table cursors are set. This is used to selectively disable
  95352. ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
  95353. ** with virtual tables.
  95354. **
  95355. ** Note that bitmasks are created for all pTabList->nSrc tables in
  95356. ** pTabList, not just the first nTabList tables. nTabList is normally
  95357. ** equal to pTabList->nSrc but might be shortened to 1 if the
  95358. ** WHERE_ONETABLE_ONLY flag is set.
  95359. */
  95360. assert( pWC->vmask==0 && pMaskSet->n==0 );
  95361. for(i=0; i<pTabList->nSrc; i++){
  95362. createMask(pMaskSet, pTabList->a[i].iCursor);
  95363. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95364. if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
  95365. pWC->vmask |= ((Bitmask)1 << i);
  95366. }
  95367. #endif
  95368. }
  95369. #ifndef NDEBUG
  95370. {
  95371. Bitmask toTheLeft = 0;
  95372. for(i=0; i<pTabList->nSrc; i++){
  95373. Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
  95374. assert( (m-1)==toTheLeft );
  95375. toTheLeft |= m;
  95376. }
  95377. }
  95378. #endif
  95379. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  95380. ** add new virtual terms onto the end of the WHERE clause. We do not
  95381. ** want to analyze these virtual terms, so start analyzing at the end
  95382. ** and work forward so that the added virtual terms are never processed.
  95383. */
  95384. exprAnalyzeAll(pTabList, pWC);
  95385. if( db->mallocFailed ){
  95386. goto whereBeginError;
  95387. }
  95388. /* Chose the best index to use for each table in the FROM clause.
  95389. **
  95390. ** This loop fills in the following fields:
  95391. **
  95392. ** pWInfo->a[].pIdx The index to use for this level of the loop.
  95393. ** pWInfo->a[].wsFlags WHERE_xxx flags associated with pIdx
  95394. ** pWInfo->a[].nEq The number of == and IN constraints
  95395. ** pWInfo->a[].iFrom Which term of the FROM clause is being coded
  95396. ** pWInfo->a[].iTabCur The VDBE cursor for the database table
  95397. ** pWInfo->a[].iIdxCur The VDBE cursor for the index
  95398. ** pWInfo->a[].pTerm When wsFlags==WO_OR, the OR-clause term
  95399. **
  95400. ** This loop also figures out the nesting order of tables in the FROM
  95401. ** clause.
  95402. */
  95403. notReady = ~(Bitmask)0;
  95404. andFlags = ~0;
  95405. WHERETRACE(("*** Optimizer Start ***\n"));
  95406. for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
  95407. WhereCost bestPlan; /* Most efficient plan seen so far */
  95408. Index *pIdx; /* Index for FROM table at pTabItem */
  95409. int j; /* For looping over FROM tables */
  95410. int bestJ = -1; /* The value of j */
  95411. Bitmask m; /* Bitmask value for j or bestJ */
  95412. int isOptimal; /* Iterator for optimal/non-optimal search */
  95413. int nUnconstrained; /* Number tables without INDEXED BY */
  95414. Bitmask notIndexed; /* Mask of tables that cannot use an index */
  95415. memset(&bestPlan, 0, sizeof(bestPlan));
  95416. bestPlan.rCost = SQLITE_BIG_DBL;
  95417. WHERETRACE(("*** Begin search for loop %d ***\n", i));
  95418. /* Loop through the remaining entries in the FROM clause to find the
  95419. ** next nested loop. The loop tests all FROM clause entries
  95420. ** either once or twice.
  95421. **
  95422. ** The first test is always performed if there are two or more entries
  95423. ** remaining and never performed if there is only one FROM clause entry
  95424. ** to choose from. The first test looks for an "optimal" scan. In
  95425. ** this context an optimal scan is one that uses the same strategy
  95426. ** for the given FROM clause entry as would be selected if the entry
  95427. ** were used as the innermost nested loop. In other words, a table
  95428. ** is chosen such that the cost of running that table cannot be reduced
  95429. ** by waiting for other tables to run first. This "optimal" test works
  95430. ** by first assuming that the FROM clause is on the inner loop and finding
  95431. ** its query plan, then checking to see if that query plan uses any
  95432. ** other FROM clause terms that are notReady. If no notReady terms are
  95433. ** used then the "optimal" query plan works.
  95434. **
  95435. ** Note that the WhereCost.nRow parameter for an optimal scan might
  95436. ** not be as small as it would be if the table really were the innermost
  95437. ** join. The nRow value can be reduced by WHERE clause constraints
  95438. ** that do not use indices. But this nRow reduction only happens if the
  95439. ** table really is the innermost join.
  95440. **
  95441. ** The second loop iteration is only performed if no optimal scan
  95442. ** strategies were found by the first iteration. This second iteration
  95443. ** is used to search for the lowest cost scan overall.
  95444. **
  95445. ** Previous versions of SQLite performed only the second iteration -
  95446. ** the next outermost loop was always that with the lowest overall
  95447. ** cost. However, this meant that SQLite could select the wrong plan
  95448. ** for scripts such as the following:
  95449. **
  95450. ** CREATE TABLE t1(a, b);
  95451. ** CREATE TABLE t2(c, d);
  95452. ** SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
  95453. **
  95454. ** The best strategy is to iterate through table t1 first. However it
  95455. ** is not possible to determine this with a simple greedy algorithm.
  95456. ** Since the cost of a linear scan through table t2 is the same
  95457. ** as the cost of a linear scan through table t1, a simple greedy
  95458. ** algorithm may choose to use t2 for the outer loop, which is a much
  95459. ** costlier approach.
  95460. */
  95461. nUnconstrained = 0;
  95462. notIndexed = 0;
  95463. for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
  95464. Bitmask mask; /* Mask of tables not yet ready */
  95465. for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
  95466. int doNotReorder; /* True if this table should not be reordered */
  95467. WhereCost sCost; /* Cost information from best[Virtual]Index() */
  95468. ExprList *pOrderBy; /* ORDER BY clause for index to optimize */
  95469. doNotReorder = (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
  95470. if( j!=iFrom && doNotReorder ) break;
  95471. m = getMask(pMaskSet, pTabItem->iCursor);
  95472. if( (m & notReady)==0 ){
  95473. if( j==iFrom ) iFrom++;
  95474. continue;
  95475. }
  95476. mask = (isOptimal ? m : notReady);
  95477. pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
  95478. if( pTabItem->pIndex==0 ) nUnconstrained++;
  95479. WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
  95480. j, isOptimal));
  95481. assert( pTabItem->pTab );
  95482. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95483. if( IsVirtual(pTabItem->pTab) ){
  95484. sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
  95485. bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
  95486. &sCost, pp);
  95487. }else
  95488. #endif
  95489. {
  95490. bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
  95491. &sCost);
  95492. }
  95493. assert( isOptimal || (sCost.used&notReady)==0 );
  95494. /* If an INDEXED BY clause is present, then the plan must use that
  95495. ** index if it uses any index at all */
  95496. assert( pTabItem->pIndex==0
  95497. || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
  95498. || sCost.plan.u.pIdx==pTabItem->pIndex );
  95499. if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
  95500. notIndexed |= m;
  95501. }
  95502. /* Conditions under which this table becomes the best so far:
  95503. **
  95504. ** (1) The table must not depend on other tables that have not
  95505. ** yet run.
  95506. **
  95507. ** (2) A full-table-scan plan cannot supercede indexed plan unless
  95508. ** the full-table-scan is an "optimal" plan as defined above.
  95509. **
  95510. ** (3) All tables have an INDEXED BY clause or this table lacks an
  95511. ** INDEXED BY clause or this table uses the specific
  95512. ** index specified by its INDEXED BY clause. This rule ensures
  95513. ** that a best-so-far is always selected even if an impossible
  95514. ** combination of INDEXED BY clauses are given. The error
  95515. ** will be detected and relayed back to the application later.
  95516. ** The NEVER() comes about because rule (2) above prevents
  95517. ** An indexable full-table-scan from reaching rule (3).
  95518. **
  95519. ** (4) The plan cost must be lower than prior plans or else the
  95520. ** cost must be the same and the number of rows must be lower.
  95521. */
  95522. if( (sCost.used&notReady)==0 /* (1) */
  95523. && (bestJ<0 || (notIndexed&m)!=0 /* (2) */
  95524. || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
  95525. || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
  95526. && (nUnconstrained==0 || pTabItem->pIndex==0 /* (3) */
  95527. || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
  95528. && (bestJ<0 || sCost.rCost<bestPlan.rCost /* (4) */
  95529. || (sCost.rCost<=bestPlan.rCost
  95530. && sCost.plan.nRow<bestPlan.plan.nRow))
  95531. ){
  95532. WHERETRACE(("=== table %d is best so far"
  95533. " with cost=%g and nRow=%g\n",
  95534. j, sCost.rCost, sCost.plan.nRow));
  95535. bestPlan = sCost;
  95536. bestJ = j;
  95537. }
  95538. if( doNotReorder ) break;
  95539. }
  95540. }
  95541. assert( bestJ>=0 );
  95542. assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
  95543. WHERETRACE(("*** Optimizer selects table %d for loop %d"
  95544. " with cost=%g and nRow=%g\n",
  95545. bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
  95546. if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
  95547. *ppOrderBy = 0;
  95548. }
  95549. andFlags &= bestPlan.plan.wsFlags;
  95550. pLevel->plan = bestPlan.plan;
  95551. testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
  95552. testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
  95553. if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
  95554. pLevel->iIdxCur = pParse->nTab++;
  95555. }else{
  95556. pLevel->iIdxCur = -1;
  95557. }
  95558. notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
  95559. pLevel->iFrom = (u8)bestJ;
  95560. if( bestPlan.plan.nRow>=(double)1 ){
  95561. pParse->nQueryLoop *= bestPlan.plan.nRow;
  95562. }
  95563. /* Check that if the table scanned by this loop iteration had an
  95564. ** INDEXED BY clause attached to it, that the named index is being
  95565. ** used for the scan. If not, then query compilation has failed.
  95566. ** Return an error.
  95567. */
  95568. pIdx = pTabList->a[bestJ].pIndex;
  95569. if( pIdx ){
  95570. if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
  95571. sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
  95572. goto whereBeginError;
  95573. }else{
  95574. /* If an INDEXED BY clause is used, the bestIndex() function is
  95575. ** guaranteed to find the index specified in the INDEXED BY clause
  95576. ** if it find an index at all. */
  95577. assert( bestPlan.plan.u.pIdx==pIdx );
  95578. }
  95579. }
  95580. }
  95581. WHERETRACE(("*** Optimizer Finished ***\n"));
  95582. if( pParse->nErr || db->mallocFailed ){
  95583. goto whereBeginError;
  95584. }
  95585. /* If the total query only selects a single row, then the ORDER BY
  95586. ** clause is irrelevant.
  95587. */
  95588. if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
  95589. *ppOrderBy = 0;
  95590. }
  95591. /* If the caller is an UPDATE or DELETE statement that is requesting
  95592. ** to use a one-pass algorithm, determine if this is appropriate.
  95593. ** The one-pass algorithm only works if the WHERE clause constraints
  95594. ** the statement to update a single row.
  95595. */
  95596. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  95597. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
  95598. pWInfo->okOnePass = 1;
  95599. pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
  95600. }
  95601. /* Open all tables in the pTabList and any indices selected for
  95602. ** searching those tables.
  95603. */
  95604. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  95605. notReady = ~(Bitmask)0;
  95606. pWInfo->nRowOut = (double)1;
  95607. for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
  95608. Table *pTab; /* Table to open */
  95609. int iDb; /* Index of database containing table/index */
  95610. pTabItem = &pTabList->a[pLevel->iFrom];
  95611. pTab = pTabItem->pTab;
  95612. pLevel->iTabCur = pTabItem->iCursor;
  95613. pWInfo->nRowOut *= pLevel->plan.nRow;
  95614. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95615. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  95616. /* Do nothing */
  95617. }else
  95618. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95619. if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  95620. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  95621. int iCur = pTabItem->iCursor;
  95622. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  95623. }else
  95624. #endif
  95625. if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  95626. && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
  95627. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  95628. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  95629. testcase( pTab->nCol==BMS-1 );
  95630. testcase( pTab->nCol==BMS );
  95631. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  95632. Bitmask b = pTabItem->colUsed;
  95633. int n = 0;
  95634. for(; b; b=b>>1, n++){}
  95635. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  95636. SQLITE_INT_TO_PTR(n), P4_INT32);
  95637. assert( n<=pTab->nCol );
  95638. }
  95639. }else{
  95640. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  95641. }
  95642. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  95643. if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
  95644. constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
  95645. }else
  95646. #endif
  95647. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  95648. Index *pIx = pLevel->plan.u.pIdx;
  95649. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  95650. int iIdxCur = pLevel->iIdxCur;
  95651. assert( pIx->pSchema==pTab->pSchema );
  95652. assert( iIdxCur>=0 );
  95653. sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
  95654. (char*)pKey, P4_KEYINFO_HANDOFF);
  95655. VdbeComment((v, "%s", pIx->zName));
  95656. }
  95657. sqlite3CodeVerifySchema(pParse, iDb);
  95658. notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
  95659. }
  95660. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  95661. if( db->mallocFailed ) goto whereBeginError;
  95662. /* Generate the code to do the search. Each iteration of the for
  95663. ** loop below generates code for a single nested loop of the VM
  95664. ** program.
  95665. */
  95666. notReady = ~(Bitmask)0;
  95667. for(i=0; i<nTabList; i++){
  95668. pLevel = &pWInfo->a[i];
  95669. explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
  95670. notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
  95671. pWInfo->iContinue = pLevel->addrCont;
  95672. }
  95673. #ifdef SQLITE_TEST /* For testing and debugging use only */
  95674. /* Record in the query plan information about the current table
  95675. ** and the index used to access it (if any). If the table itself
  95676. ** is not used, its name is just '{}'. If no index is used
  95677. ** the index is listed as "{}". If the primary key is used the
  95678. ** index name is '*'.
  95679. */
  95680. for(i=0; i<nTabList; i++){
  95681. char *z;
  95682. int n;
  95683. pLevel = &pWInfo->a[i];
  95684. pTabItem = &pTabList->a[pLevel->iFrom];
  95685. z = pTabItem->zAlias;
  95686. if( z==0 ) z = pTabItem->pTab->zName;
  95687. n = sqlite3Strlen30(z);
  95688. if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
  95689. if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
  95690. memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
  95691. nQPlan += 2;
  95692. }else{
  95693. memcpy(&sqlite3_query_plan[nQPlan], z, n);
  95694. nQPlan += n;
  95695. }
  95696. sqlite3_query_plan[nQPlan++] = ' ';
  95697. }
  95698. testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
  95699. testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
  95700. if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
  95701. memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
  95702. nQPlan += 2;
  95703. }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
  95704. n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
  95705. if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
  95706. memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
  95707. nQPlan += n;
  95708. sqlite3_query_plan[nQPlan++] = ' ';
  95709. }
  95710. }else{
  95711. memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
  95712. nQPlan += 3;
  95713. }
  95714. }
  95715. while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
  95716. sqlite3_query_plan[--nQPlan] = 0;
  95717. }
  95718. sqlite3_query_plan[nQPlan] = 0;
  95719. nQPlan = 0;
  95720. #endif /* SQLITE_TEST // Testing and debugging use only */
  95721. /* Record the continuation address in the WhereInfo structure. Then
  95722. ** clean up and return.
  95723. */
  95724. return pWInfo;
  95725. /* Jump here if malloc fails */
  95726. whereBeginError:
  95727. if( pWInfo ){
  95728. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  95729. whereInfoFree(db, pWInfo);
  95730. }
  95731. return 0;
  95732. }
  95733. /*
  95734. ** Generate the end of the WHERE loop. See comments on
  95735. ** sqlite3WhereBegin() for additional information.
  95736. */
  95737. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  95738. Parse *pParse = pWInfo->pParse;
  95739. Vdbe *v = pParse->pVdbe;
  95740. int i;
  95741. WhereLevel *pLevel;
  95742. SrcList *pTabList = pWInfo->pTabList;
  95743. sqlite3 *db = pParse->db;
  95744. /* Generate loop termination code.
  95745. */
  95746. sqlite3ExprCacheClear(pParse);
  95747. for(i=pWInfo->nLevel-1; i>=0; i--){
  95748. pLevel = &pWInfo->a[i];
  95749. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  95750. if( pLevel->op!=OP_Noop ){
  95751. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  95752. sqlite3VdbeChangeP5(v, pLevel->p5);
  95753. }
  95754. if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  95755. struct InLoop *pIn;
  95756. int j;
  95757. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  95758. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  95759. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  95760. sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
  95761. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  95762. }
  95763. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  95764. }
  95765. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  95766. if( pLevel->iLeftJoin ){
  95767. int addr;
  95768. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  95769. assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  95770. || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
  95771. if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
  95772. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  95773. }
  95774. if( pLevel->iIdxCur>=0 ){
  95775. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  95776. }
  95777. if( pLevel->op==OP_Return ){
  95778. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  95779. }else{
  95780. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  95781. }
  95782. sqlite3VdbeJumpHere(v, addr);
  95783. }
  95784. }
  95785. /* The "break" point is here, just past the end of the outer loop.
  95786. ** Set it.
  95787. */
  95788. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  95789. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  95790. */
  95791. assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
  95792. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  95793. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  95794. Table *pTab = pTabItem->pTab;
  95795. assert( pTab!=0 );
  95796. if( (pTab->tabFlags & TF_Ephemeral)==0
  95797. && pTab->pSelect==0
  95798. && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
  95799. ){
  95800. int ws = pLevel->plan.wsFlags;
  95801. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  95802. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  95803. }
  95804. if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
  95805. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  95806. }
  95807. }
  95808. /* If this scan uses an index, make code substitutions to read data
  95809. ** from the index in preference to the table. Sometimes, this means
  95810. ** the table need never be read from. This is a performance boost,
  95811. ** as the vdbe level waits until the table is read before actually
  95812. ** seeking the table cursor to the record corresponding to the current
  95813. ** position in the index.
  95814. **
  95815. ** Calls to the code generator in between sqlite3WhereBegin and
  95816. ** sqlite3WhereEnd will have created code that references the table
  95817. ** directly. This loop scans all that code looking for opcodes
  95818. ** that reference the table and converts them into opcodes that
  95819. ** reference the index.
  95820. */
  95821. if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
  95822. int k, j, last;
  95823. VdbeOp *pOp;
  95824. Index *pIdx = pLevel->plan.u.pIdx;
  95825. assert( pIdx!=0 );
  95826. pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
  95827. last = sqlite3VdbeCurrentAddr(v);
  95828. for(k=pWInfo->iTop; k<last; k++, pOp++){
  95829. if( pOp->p1!=pLevel->iTabCur ) continue;
  95830. if( pOp->opcode==OP_Column ){
  95831. for(j=0; j<pIdx->nColumn; j++){
  95832. if( pOp->p2==pIdx->aiColumn[j] ){
  95833. pOp->p2 = j;
  95834. pOp->p1 = pLevel->iIdxCur;
  95835. break;
  95836. }
  95837. }
  95838. assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
  95839. || j<pIdx->nColumn );
  95840. }else if( pOp->opcode==OP_Rowid ){
  95841. pOp->p1 = pLevel->iIdxCur;
  95842. pOp->opcode = OP_IdxRowid;
  95843. }
  95844. }
  95845. }
  95846. }
  95847. /* Final cleanup
  95848. */
  95849. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  95850. whereInfoFree(db, pWInfo);
  95851. return;
  95852. }
  95853. /************** End of where.c ***********************************************/
  95854. /************** Begin file parse.c *******************************************/
  95855. /* Driver template for the LEMON parser generator.
  95856. ** The author disclaims copyright to this source code.
  95857. **
  95858. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  95859. ** The only modifications are the addition of a couple of NEVER()
  95860. ** macros to disable tests that are needed in the case of a general
  95861. ** LALR(1) grammar but which are always false in the
  95862. ** specific grammar used by SQLite.
  95863. */
  95864. /* First off, code is included that follows the "include" declaration
  95865. ** in the input grammar file. */
  95866. /*
  95867. ** Disable all error recovery processing in the parser push-down
  95868. ** automaton.
  95869. */
  95870. #define YYNOERRORRECOVERY 1
  95871. /*
  95872. ** Make yytestcase() the same as testcase()
  95873. */
  95874. #define yytestcase(X) testcase(X)
  95875. /*
  95876. ** An instance of this structure holds information about the
  95877. ** LIMIT clause of a SELECT statement.
  95878. */
  95879. struct LimitVal {
  95880. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  95881. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  95882. };
  95883. /*
  95884. ** An instance of this structure is used to store the LIKE,
  95885. ** GLOB, NOT LIKE, and NOT GLOB operators.
  95886. */
  95887. struct LikeOp {
  95888. Token eOperator; /* "like" or "glob" or "regexp" */
  95889. int not; /* True if the NOT keyword is present */
  95890. };
  95891. /*
  95892. ** An instance of the following structure describes the event of a
  95893. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  95894. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  95895. **
  95896. ** UPDATE ON (a,b,c)
  95897. **
  95898. ** Then the "b" IdList records the list "a,b,c".
  95899. */
  95900. struct TrigEvent { int a; IdList * b; };
  95901. /*
  95902. ** An instance of this structure holds the ATTACH key and the key type.
  95903. */
  95904. struct AttachKey { int type; Token key; };
  95905. /* This is a utility routine used to set the ExprSpan.zStart and
  95906. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  95907. ** range of text beginning with pStart and going to the end of pEnd.
  95908. */
  95909. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  95910. pOut->zStart = pStart->z;
  95911. pOut->zEnd = &pEnd->z[pEnd->n];
  95912. }
  95913. /* Construct a new Expr object from a single identifier. Use the
  95914. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  95915. ** that created the expression.
  95916. */
  95917. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  95918. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  95919. pOut->zStart = pValue->z;
  95920. pOut->zEnd = &pValue->z[pValue->n];
  95921. }
  95922. /* This routine constructs a binary expression node out of two ExprSpan
  95923. ** objects and uses the result to populate a new ExprSpan object.
  95924. */
  95925. static void spanBinaryExpr(
  95926. ExprSpan *pOut, /* Write the result here */
  95927. Parse *pParse, /* The parsing context. Errors accumulate here */
  95928. int op, /* The binary operation */
  95929. ExprSpan *pLeft, /* The left operand */
  95930. ExprSpan *pRight /* The right operand */
  95931. ){
  95932. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  95933. pOut->zStart = pLeft->zStart;
  95934. pOut->zEnd = pRight->zEnd;
  95935. }
  95936. /* Construct an expression node for a unary postfix operator
  95937. */
  95938. static void spanUnaryPostfix(
  95939. ExprSpan *pOut, /* Write the new expression node here */
  95940. Parse *pParse, /* Parsing context to record errors */
  95941. int op, /* The operator */
  95942. ExprSpan *pOperand, /* The operand */
  95943. Token *pPostOp /* The operand token for setting the span */
  95944. ){
  95945. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  95946. pOut->zStart = pOperand->zStart;
  95947. pOut->zEnd = &pPostOp->z[pPostOp->n];
  95948. }
  95949. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  95950. ** unary TK_ISNULL or TK_NOTNULL expression. */
  95951. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  95952. sqlite3 *db = pParse->db;
  95953. if( db->mallocFailed==0 && pY->op==TK_NULL ){
  95954. pA->op = (u8)op;
  95955. sqlite3ExprDelete(db, pA->pRight);
  95956. pA->pRight = 0;
  95957. }
  95958. }
  95959. /* Construct an expression node for a unary prefix operator
  95960. */
  95961. static void spanUnaryPrefix(
  95962. ExprSpan *pOut, /* Write the new expression node here */
  95963. Parse *pParse, /* Parsing context to record errors */
  95964. int op, /* The operator */
  95965. ExprSpan *pOperand, /* The operand */
  95966. Token *pPreOp /* The operand token for setting the span */
  95967. ){
  95968. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  95969. pOut->zStart = pPreOp->z;
  95970. pOut->zEnd = pOperand->zEnd;
  95971. }
  95972. /* Next is all token values, in a form suitable for use by makeheaders.
  95973. ** This section will be null unless lemon is run with the -m switch.
  95974. */
  95975. /*
  95976. ** These constants (all generated automatically by the parser generator)
  95977. ** specify the various kinds of tokens (terminals) that the parser
  95978. ** understands.
  95979. **
  95980. ** Each symbol here is a terminal symbol in the grammar.
  95981. */
  95982. /* Make sure the INTERFACE macro is defined.
  95983. */
  95984. #ifndef INTERFACE
  95985. # define INTERFACE 1
  95986. #endif
  95987. /* The next thing included is series of defines which control
  95988. ** various aspects of the generated parser.
  95989. ** YYCODETYPE is the data type used for storing terminal
  95990. ** and nonterminal numbers. "unsigned char" is
  95991. ** used if there are fewer than 250 terminals
  95992. ** and nonterminals. "int" is used otherwise.
  95993. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  95994. ** to no legal terminal or nonterminal number. This
  95995. ** number is used to fill in empty slots of the hash
  95996. ** table.
  95997. ** YYFALLBACK If defined, this indicates that one or more tokens
  95998. ** have fall-back values which should be used if the
  95999. ** original value of the token will not parse.
  96000. ** YYACTIONTYPE is the data type used for storing terminal
  96001. ** and nonterminal numbers. "unsigned char" is
  96002. ** used if there are fewer than 250 rules and
  96003. ** states combined. "int" is used otherwise.
  96004. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  96005. ** directly to the parser from the tokenizer.
  96006. ** YYMINORTYPE is the data type used for all minor tokens.
  96007. ** This is typically a union of many types, one of
  96008. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  96009. ** for base tokens is called "yy0".
  96010. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  96011. ** zero the stack is dynamically sized using realloc()
  96012. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  96013. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  96014. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  96015. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  96016. ** YYNSTATE the combined number of states.
  96017. ** YYNRULE the number of rules in the grammar
  96018. ** YYERRORSYMBOL is the code number of the error symbol. If not
  96019. ** defined, then do no error processing.
  96020. */
  96021. #define YYCODETYPE unsigned char
  96022. #define YYNOCODE 253
  96023. #define YYACTIONTYPE unsigned short int
  96024. #define YYWILDCARD 67
  96025. #define sqlite3ParserTOKENTYPE Token
  96026. typedef union {
  96027. int yyinit;
  96028. sqlite3ParserTOKENTYPE yy0;
  96029. int yy4;
  96030. struct TrigEvent yy90;
  96031. ExprSpan yy118;
  96032. TriggerStep* yy203;
  96033. u8 yy210;
  96034. struct {int value; int mask;} yy215;
  96035. SrcList* yy259;
  96036. struct LimitVal yy292;
  96037. Expr* yy314;
  96038. ExprList* yy322;
  96039. struct LikeOp yy342;
  96040. IdList* yy384;
  96041. Select* yy387;
  96042. } YYMINORTYPE;
  96043. #ifndef YYSTACKDEPTH
  96044. #define YYSTACKDEPTH 100
  96045. #endif
  96046. #define sqlite3ParserARG_SDECL Parse *pParse;
  96047. #define sqlite3ParserARG_PDECL ,Parse *pParse
  96048. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  96049. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  96050. #define YYNSTATE 630
  96051. #define YYNRULE 329
  96052. #define YYFALLBACK 1
  96053. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  96054. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  96055. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  96056. /* The yyzerominor constant is used to initialize instances of
  96057. ** YYMINORTYPE objects to zero. */
  96058. static const YYMINORTYPE yyzerominor = { 0 };
  96059. /* Define the yytestcase() macro to be a no-op if is not already defined
  96060. ** otherwise.
  96061. **
  96062. ** Applications can choose to define yytestcase() in the %include section
  96063. ** to a macro that can assist in verifying code coverage. For production
  96064. ** code the yytestcase() macro should be turned off. But it is useful
  96065. ** for testing.
  96066. */
  96067. #ifndef yytestcase
  96068. # define yytestcase(X)
  96069. #endif
  96070. /* Next are the tables used to determine what action to take based on the
  96071. ** current state and lookahead token. These tables are used to implement
  96072. ** functions that take a state number and lookahead value and return an
  96073. ** action integer.
  96074. **
  96075. ** Suppose the action integer is N. Then the action is determined as
  96076. ** follows
  96077. **
  96078. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  96079. ** token onto the stack and goto state N.
  96080. **
  96081. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  96082. **
  96083. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  96084. **
  96085. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  96086. **
  96087. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  96088. ** slots in the yy_action[] table.
  96089. **
  96090. ** The action table is constructed as a single large table named yy_action[].
  96091. ** Given state S and lookahead X, the action is computed as
  96092. **
  96093. ** yy_action[ yy_shift_ofst[S] + X ]
  96094. **
  96095. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  96096. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  96097. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  96098. ** and that yy_default[S] should be used instead.
  96099. **
  96100. ** The formula above is for computing the action when the lookahead is
  96101. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  96102. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  96103. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  96104. ** YY_SHIFT_USE_DFLT.
  96105. **
  96106. ** The following are the tables generated in this section:
  96107. **
  96108. ** yy_action[] A single table containing all actions.
  96109. ** yy_lookahead[] A table containing the lookahead for each entry in
  96110. ** yy_action. Used to detect hash collisions.
  96111. ** yy_shift_ofst[] For each state, the offset into yy_action for
  96112. ** shifting terminals.
  96113. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  96114. ** shifting non-terminals after a reduce.
  96115. ** yy_default[] Default action for each state.
  96116. */
  96117. #define YY_ACTTAB_COUNT (1557)
  96118. static const YYACTIONTYPE yy_action[] = {
  96119. /* 0 */ 313, 960, 186, 419, 2, 172, 627, 597, 55, 55,
  96120. /* 10 */ 55, 55, 48, 53, 53, 53, 53, 52, 52, 51,
  96121. /* 20 */ 51, 51, 50, 238, 302, 283, 623, 622, 516, 515,
  96122. /* 30 */ 590, 584, 55, 55, 55, 55, 282, 53, 53, 53,
  96123. /* 40 */ 53, 52, 52, 51, 51, 51, 50, 238, 6, 56,
  96124. /* 50 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
  96125. /* 60 */ 55, 55, 608, 53, 53, 53, 53, 52, 52, 51,
  96126. /* 70 */ 51, 51, 50, 238, 313, 597, 409, 330, 579, 579,
  96127. /* 80 */ 32, 53, 53, 53, 53, 52, 52, 51, 51, 51,
  96128. /* 90 */ 50, 238, 330, 217, 620, 619, 166, 411, 624, 382,
  96129. /* 100 */ 379, 378, 7, 491, 590, 584, 200, 199, 198, 58,
  96130. /* 110 */ 377, 300, 414, 621, 481, 66, 623, 622, 621, 580,
  96131. /* 120 */ 254, 601, 94, 56, 57, 47, 582, 581, 583, 583,
  96132. /* 130 */ 54, 54, 55, 55, 55, 55, 671, 53, 53, 53,
  96133. /* 140 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 532,
  96134. /* 150 */ 226, 506, 507, 133, 177, 139, 284, 385, 279, 384,
  96135. /* 160 */ 169, 197, 342, 398, 251, 226, 253, 275, 388, 167,
  96136. /* 170 */ 139, 284, 385, 279, 384, 169, 570, 236, 590, 584,
  96137. /* 180 */ 672, 240, 275, 157, 620, 619, 554, 437, 51, 51,
  96138. /* 190 */ 51, 50, 238, 343, 439, 553, 438, 56, 57, 47,
  96139. /* 200 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
  96140. /* 210 */ 465, 53, 53, 53, 53, 52, 52, 51, 51, 51,
  96141. /* 220 */ 50, 238, 313, 390, 52, 52, 51, 51, 51, 50,
  96142. /* 230 */ 238, 391, 166, 491, 566, 382, 379, 378, 409, 440,
  96143. /* 240 */ 579, 579, 252, 440, 607, 66, 377, 513, 621, 49,
  96144. /* 250 */ 46, 147, 590, 584, 621, 16, 466, 189, 621, 441,
  96145. /* 260 */ 442, 673, 526, 441, 340, 577, 595, 64, 194, 482,
  96146. /* 270 */ 434, 56, 57, 47, 582, 581, 583, 583, 54, 54,
  96147. /* 280 */ 55, 55, 55, 55, 30, 53, 53, 53, 53, 52,
  96148. /* 290 */ 52, 51, 51, 51, 50, 238, 313, 593, 593, 593,
  96149. /* 300 */ 387, 578, 606, 493, 259, 351, 258, 411, 1, 623,
  96150. /* 310 */ 622, 496, 623, 622, 65, 240, 623, 622, 597, 443,
  96151. /* 320 */ 237, 239, 414, 341, 237, 602, 590, 584, 18, 603,
  96152. /* 330 */ 166, 601, 87, 382, 379, 378, 67, 623, 622, 38,
  96153. /* 340 */ 623, 622, 176, 270, 377, 56, 57, 47, 582, 581,
  96154. /* 350 */ 583, 583, 54, 54, 55, 55, 55, 55, 175, 53,
  96155. /* 360 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
  96156. /* 370 */ 313, 396, 233, 411, 531, 565, 317, 620, 619, 44,
  96157. /* 380 */ 620, 619, 240, 206, 620, 619, 597, 266, 414, 268,
  96158. /* 390 */ 409, 597, 579, 579, 352, 184, 505, 601, 73, 533,
  96159. /* 400 */ 590, 584, 466, 548, 190, 620, 619, 576, 620, 619,
  96160. /* 410 */ 547, 383, 551, 35, 332, 575, 574, 600, 504, 56,
  96161. /* 420 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
  96162. /* 430 */ 55, 55, 567, 53, 53, 53, 53, 52, 52, 51,
  96163. /* 440 */ 51, 51, 50, 238, 313, 411, 561, 561, 528, 364,
  96164. /* 450 */ 259, 351, 258, 183, 361, 549, 524, 374, 411, 597,
  96165. /* 460 */ 414, 240, 560, 560, 409, 604, 579, 579, 328, 601,
  96166. /* 470 */ 93, 623, 622, 414, 590, 584, 237, 564, 559, 559,
  96167. /* 480 */ 520, 402, 601, 87, 409, 210, 579, 579, 168, 421,
  96168. /* 490 */ 950, 519, 950, 56, 57, 47, 582, 581, 583, 583,
  96169. /* 500 */ 54, 54, 55, 55, 55, 55, 192, 53, 53, 53,
  96170. /* 510 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 600,
  96171. /* 520 */ 293, 563, 511, 234, 357, 146, 475, 475, 367, 411,
  96172. /* 530 */ 562, 411, 358, 542, 425, 171, 411, 215, 144, 620,
  96173. /* 540 */ 619, 544, 318, 353, 414, 203, 414, 275, 590, 584,
  96174. /* 550 */ 549, 414, 174, 601, 94, 601, 79, 558, 471, 61,
  96175. /* 560 */ 601, 79, 421, 949, 350, 949, 34, 56, 57, 47,
  96176. /* 570 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
  96177. /* 580 */ 535, 53, 53, 53, 53, 52, 52, 51, 51, 51,
  96178. /* 590 */ 50, 238, 313, 307, 424, 394, 272, 49, 46, 147,
  96179. /* 600 */ 349, 322, 4, 411, 491, 312, 321, 425, 568, 492,
  96180. /* 610 */ 216, 264, 407, 575, 574, 429, 66, 549, 414, 621,
  96181. /* 620 */ 540, 602, 590, 584, 13, 603, 621, 601, 72, 12,
  96182. /* 630 */ 618, 617, 616, 202, 210, 621, 546, 469, 422, 319,
  96183. /* 640 */ 148, 56, 57, 47, 582, 581, 583, 583, 54, 54,
  96184. /* 650 */ 55, 55, 55, 55, 338, 53, 53, 53, 53, 52,
  96185. /* 660 */ 52, 51, 51, 51, 50, 238, 313, 600, 600, 411,
  96186. /* 670 */ 39, 21, 37, 170, 237, 875, 411, 572, 572, 201,
  96187. /* 680 */ 144, 473, 538, 331, 414, 474, 143, 146, 630, 628,
  96188. /* 690 */ 334, 414, 353, 601, 68, 168, 590, 584, 132, 365,
  96189. /* 700 */ 601, 96, 307, 423, 530, 336, 49, 46, 147, 568,
  96190. /* 710 */ 406, 216, 549, 360, 529, 56, 57, 47, 582, 581,
  96191. /* 720 */ 583, 583, 54, 54, 55, 55, 55, 55, 411, 53,
  96192. /* 730 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
  96193. /* 740 */ 313, 411, 605, 414, 484, 510, 172, 422, 597, 318,
  96194. /* 750 */ 496, 485, 601, 99, 411, 142, 414, 411, 231, 411,
  96195. /* 760 */ 540, 411, 359, 629, 2, 601, 97, 426, 308, 414,
  96196. /* 770 */ 590, 584, 414, 20, 414, 621, 414, 621, 601, 106,
  96197. /* 780 */ 503, 601, 105, 601, 108, 601, 109, 204, 28, 56,
  96198. /* 790 */ 57, 47, 582, 581, 583, 583, 54, 54, 55, 55,
  96199. /* 800 */ 55, 55, 411, 53, 53, 53, 53, 52, 52, 51,
  96200. /* 810 */ 51, 51, 50, 238, 313, 411, 597, 414, 411, 276,
  96201. /* 820 */ 214, 600, 411, 366, 213, 381, 601, 134, 274, 500,
  96202. /* 830 */ 414, 167, 130, 414, 621, 411, 354, 414, 376, 601,
  96203. /* 840 */ 135, 129, 601, 100, 590, 584, 601, 104, 522, 521,
  96204. /* 850 */ 414, 621, 224, 273, 600, 167, 327, 282, 600, 601,
  96205. /* 860 */ 103, 468, 521, 56, 57, 47, 582, 581, 583, 583,
  96206. /* 870 */ 54, 54, 55, 55, 55, 55, 411, 53, 53, 53,
  96207. /* 880 */ 53, 52, 52, 51, 51, 51, 50, 238, 313, 411,
  96208. /* 890 */ 27, 414, 411, 375, 276, 167, 359, 544, 50, 238,
  96209. /* 900 */ 601, 95, 128, 223, 414, 411, 165, 414, 411, 621,
  96210. /* 910 */ 411, 621, 612, 601, 102, 372, 601, 76, 590, 584,
  96211. /* 920 */ 414, 570, 236, 414, 470, 414, 167, 621, 188, 601,
  96212. /* 930 */ 98, 225, 601, 138, 601, 137, 232, 56, 45, 47,
  96213. /* 940 */ 582, 581, 583, 583, 54, 54, 55, 55, 55, 55,
  96214. /* 950 */ 411, 53, 53, 53, 53, 52, 52, 51, 51, 51,
  96215. /* 960 */ 50, 238, 313, 276, 276, 414, 411, 276, 544, 459,
  96216. /* 970 */ 359, 171, 209, 479, 601, 136, 628, 334, 621, 621,
  96217. /* 980 */ 125, 414, 621, 368, 411, 621, 257, 540, 589, 588,
  96218. /* 990 */ 601, 75, 590, 584, 458, 446, 23, 23, 124, 414,
  96219. /* 1000 */ 326, 325, 621, 427, 324, 309, 600, 288, 601, 92,
  96220. /* 1010 */ 586, 585, 57, 47, 582, 581, 583, 583, 54, 54,
  96221. /* 1020 */ 55, 55, 55, 55, 411, 53, 53, 53, 53, 52,
  96222. /* 1030 */ 52, 51, 51, 51, 50, 238, 313, 587, 411, 414,
  96223. /* 1040 */ 411, 207, 611, 476, 171, 472, 160, 123, 601, 91,
  96224. /* 1050 */ 323, 261, 15, 414, 464, 414, 411, 621, 411, 354,
  96225. /* 1060 */ 222, 411, 601, 74, 601, 90, 590, 584, 159, 264,
  96226. /* 1070 */ 158, 414, 461, 414, 621, 600, 414, 121, 120, 25,
  96227. /* 1080 */ 601, 89, 601, 101, 621, 601, 88, 47, 582, 581,
  96228. /* 1090 */ 583, 583, 54, 54, 55, 55, 55, 55, 544, 53,
  96229. /* 1100 */ 53, 53, 53, 52, 52, 51, 51, 51, 50, 238,
  96230. /* 1110 */ 43, 405, 263, 3, 610, 264, 140, 415, 622, 24,
  96231. /* 1120 */ 410, 11, 456, 594, 118, 155, 219, 452, 408, 621,
  96232. /* 1130 */ 621, 621, 156, 43, 405, 621, 3, 286, 621, 113,
  96233. /* 1140 */ 415, 622, 111, 445, 411, 400, 557, 403, 545, 10,
  96234. /* 1150 */ 411, 408, 264, 110, 205, 436, 541, 566, 453, 414,
  96235. /* 1160 */ 621, 621, 63, 621, 435, 414, 411, 621, 601, 94,
  96236. /* 1170 */ 403, 621, 411, 337, 601, 86, 150, 40, 41, 534,
  96237. /* 1180 */ 566, 414, 242, 264, 42, 413, 412, 414, 600, 595,
  96238. /* 1190 */ 601, 85, 191, 333, 107, 451, 601, 84, 621, 539,
  96239. /* 1200 */ 40, 41, 420, 230, 411, 149, 316, 42, 413, 412,
  96240. /* 1210 */ 398, 127, 595, 315, 621, 399, 278, 625, 181, 414,
  96241. /* 1220 */ 593, 593, 593, 592, 591, 14, 450, 411, 601, 71,
  96242. /* 1230 */ 240, 621, 43, 405, 264, 3, 615, 180, 264, 415,
  96243. /* 1240 */ 622, 614, 414, 593, 593, 593, 592, 591, 14, 621,
  96244. /* 1250 */ 408, 601, 70, 621, 417, 33, 405, 613, 3, 411,
  96245. /* 1260 */ 264, 411, 415, 622, 418, 626, 178, 509, 8, 403,
  96246. /* 1270 */ 241, 416, 126, 408, 414, 621, 414, 449, 208, 566,
  96247. /* 1280 */ 240, 221, 621, 601, 83, 601, 82, 599, 297, 277,
  96248. /* 1290 */ 296, 30, 403, 31, 395, 264, 295, 397, 489, 40,
  96249. /* 1300 */ 41, 411, 566, 220, 621, 294, 42, 413, 412, 271,
  96250. /* 1310 */ 621, 595, 600, 621, 59, 60, 414, 269, 267, 623,
  96251. /* 1320 */ 622, 36, 40, 41, 621, 601, 81, 598, 235, 42,
  96252. /* 1330 */ 413, 412, 621, 621, 595, 265, 344, 411, 248, 556,
  96253. /* 1340 */ 173, 185, 593, 593, 593, 592, 591, 14, 218, 29,
  96254. /* 1350 */ 621, 543, 414, 305, 304, 303, 179, 301, 411, 566,
  96255. /* 1360 */ 454, 601, 80, 289, 335, 593, 593, 593, 592, 591,
  96256. /* 1370 */ 14, 411, 287, 414, 151, 392, 246, 260, 411, 196,
  96257. /* 1380 */ 195, 523, 601, 69, 411, 245, 414, 526, 537, 285,
  96258. /* 1390 */ 389, 595, 621, 414, 536, 601, 17, 362, 153, 414,
  96259. /* 1400 */ 466, 463, 601, 78, 154, 414, 462, 152, 601, 77,
  96260. /* 1410 */ 355, 255, 621, 455, 601, 9, 621, 386, 444, 517,
  96261. /* 1420 */ 247, 621, 593, 593, 593, 621, 621, 244, 621, 243,
  96262. /* 1430 */ 430, 518, 292, 621, 329, 621, 145, 393, 280, 513,
  96263. /* 1440 */ 291, 131, 621, 514, 621, 621, 311, 621, 259, 346,
  96264. /* 1450 */ 249, 621, 621, 229, 314, 621, 228, 512, 227, 240,
  96265. /* 1460 */ 494, 488, 310, 164, 487, 486, 373, 480, 163, 262,
  96266. /* 1470 */ 369, 371, 162, 26, 212, 478, 477, 161, 141, 363,
  96267. /* 1480 */ 467, 122, 339, 187, 119, 348, 347, 117, 116, 115,
  96268. /* 1490 */ 114, 112, 182, 457, 320, 22, 433, 432, 448, 19,
  96269. /* 1500 */ 609, 431, 428, 62, 193, 596, 573, 298, 555, 552,
  96270. /* 1510 */ 571, 404, 290, 380, 498, 510, 495, 306, 281, 499,
  96271. /* 1520 */ 250, 5, 497, 460, 345, 447, 569, 550, 238, 299,
  96272. /* 1530 */ 527, 525, 508, 961, 502, 501, 961, 401, 961, 211,
  96273. /* 1540 */ 490, 356, 256, 961, 483, 961, 961, 961, 961, 961,
  96274. /* 1550 */ 961, 961, 961, 961, 961, 961, 370,
  96275. };
  96276. static const YYCODETYPE yy_lookahead[] = {
  96277. /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
  96278. /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  96279. /* 20 */ 89, 90, 91, 92, 15, 98, 26, 27, 7, 8,
  96280. /* 30 */ 49, 50, 77, 78, 79, 80, 109, 82, 83, 84,
  96281. /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 22, 68,
  96282. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96283. /* 60 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88,
  96284. /* 70 */ 89, 90, 91, 92, 19, 94, 112, 19, 114, 115,
  96285. /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96286. /* 90 */ 91, 92, 19, 22, 94, 95, 96, 150, 150, 99,
  96287. /* 100 */ 100, 101, 76, 150, 49, 50, 105, 106, 107, 54,
  96288. /* 110 */ 110, 158, 165, 165, 161, 162, 26, 27, 165, 113,
  96289. /* 120 */ 16, 174, 175, 68, 69, 70, 71, 72, 73, 74,
  96290. /* 130 */ 75, 76, 77, 78, 79, 80, 118, 82, 83, 84,
  96291. /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 23,
  96292. /* 150 */ 92, 97, 98, 24, 96, 97, 98, 99, 100, 101,
  96293. /* 160 */ 102, 25, 97, 216, 60, 92, 62, 109, 221, 25,
  96294. /* 170 */ 97, 98, 99, 100, 101, 102, 86, 87, 49, 50,
  96295. /* 180 */ 118, 116, 109, 25, 94, 95, 32, 97, 88, 89,
  96296. /* 190 */ 90, 91, 92, 128, 104, 41, 106, 68, 69, 70,
  96297. /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96298. /* 210 */ 11, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96299. /* 220 */ 91, 92, 19, 19, 86, 87, 88, 89, 90, 91,
  96300. /* 230 */ 92, 27, 96, 150, 66, 99, 100, 101, 112, 150,
  96301. /* 240 */ 114, 115, 138, 150, 161, 162, 110, 103, 165, 222,
  96302. /* 250 */ 223, 224, 49, 50, 165, 22, 57, 24, 165, 170,
  96303. /* 260 */ 171, 118, 94, 170, 171, 23, 98, 25, 185, 186,
  96304. /* 270 */ 243, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  96305. /* 280 */ 77, 78, 79, 80, 126, 82, 83, 84, 85, 86,
  96306. /* 290 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 131,
  96307. /* 300 */ 88, 23, 172, 173, 105, 106, 107, 150, 22, 26,
  96308. /* 310 */ 27, 181, 26, 27, 22, 116, 26, 27, 26, 230,
  96309. /* 320 */ 231, 197, 165, 230, 231, 113, 49, 50, 204, 117,
  96310. /* 330 */ 96, 174, 175, 99, 100, 101, 22, 26, 27, 136,
  96311. /* 340 */ 26, 27, 118, 16, 110, 68, 69, 70, 71, 72,
  96312. /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 118, 82,
  96313. /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96314. /* 370 */ 19, 214, 215, 150, 23, 23, 155, 94, 95, 22,
  96315. /* 380 */ 94, 95, 116, 160, 94, 95, 94, 60, 165, 62,
  96316. /* 390 */ 112, 26, 114, 115, 128, 23, 36, 174, 175, 88,
  96317. /* 400 */ 49, 50, 57, 120, 22, 94, 95, 23, 94, 95,
  96318. /* 410 */ 120, 51, 25, 136, 169, 170, 171, 194, 58, 68,
  96319. /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96320. /* 430 */ 79, 80, 23, 82, 83, 84, 85, 86, 87, 88,
  96321. /* 440 */ 89, 90, 91, 92, 19, 150, 12, 12, 23, 228,
  96322. /* 450 */ 105, 106, 107, 23, 233, 25, 165, 19, 150, 94,
  96323. /* 460 */ 165, 116, 28, 28, 112, 174, 114, 115, 108, 174,
  96324. /* 470 */ 175, 26, 27, 165, 49, 50, 231, 11, 44, 44,
  96325. /* 480 */ 46, 46, 174, 175, 112, 160, 114, 115, 50, 22,
  96326. /* 490 */ 23, 57, 25, 68, 69, 70, 71, 72, 73, 74,
  96327. /* 500 */ 75, 76, 77, 78, 79, 80, 119, 82, 83, 84,
  96328. /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 194,
  96329. /* 520 */ 225, 23, 23, 215, 19, 95, 105, 106, 107, 150,
  96330. /* 530 */ 23, 150, 27, 23, 67, 25, 150, 206, 207, 94,
  96331. /* 540 */ 95, 166, 104, 218, 165, 22, 165, 109, 49, 50,
  96332. /* 550 */ 120, 165, 25, 174, 175, 174, 175, 23, 21, 234,
  96333. /* 560 */ 174, 175, 22, 23, 239, 25, 25, 68, 69, 70,
  96334. /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96335. /* 580 */ 205, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96336. /* 590 */ 91, 92, 19, 22, 23, 216, 23, 222, 223, 224,
  96337. /* 600 */ 63, 220, 35, 150, 150, 163, 220, 67, 166, 167,
  96338. /* 610 */ 168, 150, 169, 170, 171, 161, 162, 25, 165, 165,
  96339. /* 620 */ 150, 113, 49, 50, 25, 117, 165, 174, 175, 35,
  96340. /* 630 */ 7, 8, 9, 160, 160, 165, 120, 100, 67, 247,
  96341. /* 640 */ 248, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  96342. /* 650 */ 77, 78, 79, 80, 193, 82, 83, 84, 85, 86,
  96343. /* 660 */ 87, 88, 89, 90, 91, 92, 19, 194, 194, 150,
  96344. /* 670 */ 135, 24, 137, 35, 231, 138, 150, 129, 130, 206,
  96345. /* 680 */ 207, 30, 27, 213, 165, 34, 118, 95, 0, 1,
  96346. /* 690 */ 2, 165, 218, 174, 175, 50, 49, 50, 22, 48,
  96347. /* 700 */ 174, 175, 22, 23, 23, 244, 222, 223, 224, 166,
  96348. /* 710 */ 167, 168, 120, 239, 23, 68, 69, 70, 71, 72,
  96349. /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  96350. /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96351. /* 740 */ 19, 150, 173, 165, 181, 182, 24, 67, 26, 104,
  96352. /* 750 */ 181, 188, 174, 175, 150, 39, 165, 150, 52, 150,
  96353. /* 760 */ 150, 150, 150, 144, 145, 174, 175, 249, 250, 165,
  96354. /* 770 */ 49, 50, 165, 52, 165, 165, 165, 165, 174, 175,
  96355. /* 780 */ 29, 174, 175, 174, 175, 174, 175, 160, 22, 68,
  96356. /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  96357. /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
  96358. /* 810 */ 89, 90, 91, 92, 19, 150, 94, 165, 150, 150,
  96359. /* 820 */ 160, 194, 150, 213, 160, 52, 174, 175, 23, 23,
  96360. /* 830 */ 165, 25, 22, 165, 165, 150, 150, 165, 52, 174,
  96361. /* 840 */ 175, 22, 174, 175, 49, 50, 174, 175, 190, 191,
  96362. /* 850 */ 165, 165, 240, 23, 194, 25, 187, 109, 194, 174,
  96363. /* 860 */ 175, 190, 191, 68, 69, 70, 71, 72, 73, 74,
  96364. /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
  96365. /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
  96366. /* 890 */ 22, 165, 150, 23, 150, 25, 150, 166, 91, 92,
  96367. /* 900 */ 174, 175, 22, 217, 165, 150, 102, 165, 150, 165,
  96368. /* 910 */ 150, 165, 150, 174, 175, 19, 174, 175, 49, 50,
  96369. /* 920 */ 165, 86, 87, 165, 23, 165, 25, 165, 24, 174,
  96370. /* 930 */ 175, 187, 174, 175, 174, 175, 205, 68, 69, 70,
  96371. /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  96372. /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  96373. /* 960 */ 91, 92, 19, 150, 150, 165, 150, 150, 166, 23,
  96374. /* 970 */ 150, 25, 160, 20, 174, 175, 1, 2, 165, 165,
  96375. /* 980 */ 104, 165, 165, 43, 150, 165, 240, 150, 49, 50,
  96376. /* 990 */ 174, 175, 49, 50, 23, 23, 25, 25, 53, 165,
  96377. /* 1000 */ 187, 187, 165, 23, 187, 25, 194, 205, 174, 175,
  96378. /* 1010 */ 71, 72, 69, 70, 71, 72, 73, 74, 75, 76,
  96379. /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
  96380. /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 98, 150, 165,
  96381. /* 1040 */ 150, 160, 150, 59, 25, 53, 104, 22, 174, 175,
  96382. /* 1050 */ 213, 138, 5, 165, 1, 165, 150, 165, 150, 150,
  96383. /* 1060 */ 240, 150, 174, 175, 174, 175, 49, 50, 118, 150,
  96384. /* 1070 */ 35, 165, 27, 165, 165, 194, 165, 108, 127, 76,
  96385. /* 1080 */ 174, 175, 174, 175, 165, 174, 175, 70, 71, 72,
  96386. /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 166, 82,
  96387. /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  96388. /* 1110 */ 19, 20, 193, 22, 150, 150, 150, 26, 27, 76,
  96389. /* 1120 */ 150, 22, 1, 150, 119, 121, 217, 20, 37, 165,
  96390. /* 1130 */ 165, 165, 16, 19, 20, 165, 22, 205, 165, 119,
  96391. /* 1140 */ 26, 27, 108, 128, 150, 150, 150, 56, 150, 22,
  96392. /* 1150 */ 150, 37, 150, 127, 160, 23, 150, 66, 193, 165,
  96393. /* 1160 */ 165, 165, 16, 165, 23, 165, 150, 165, 174, 175,
  96394. /* 1170 */ 56, 165, 150, 65, 174, 175, 15, 86, 87, 88,
  96395. /* 1180 */ 66, 165, 140, 150, 93, 94, 95, 165, 194, 98,
  96396. /* 1190 */ 174, 175, 22, 3, 164, 193, 174, 175, 165, 150,
  96397. /* 1200 */ 86, 87, 4, 180, 150, 248, 251, 93, 94, 95,
  96398. /* 1210 */ 216, 180, 98, 251, 165, 221, 150, 149, 6, 165,
  96399. /* 1220 */ 129, 130, 131, 132, 133, 134, 193, 150, 174, 175,
  96400. /* 1230 */ 116, 165, 19, 20, 150, 22, 149, 151, 150, 26,
  96401. /* 1240 */ 27, 149, 165, 129, 130, 131, 132, 133, 134, 165,
  96402. /* 1250 */ 37, 174, 175, 165, 149, 19, 20, 13, 22, 150,
  96403. /* 1260 */ 150, 150, 26, 27, 146, 147, 151, 150, 25, 56,
  96404. /* 1270 */ 152, 159, 154, 37, 165, 165, 165, 193, 160, 66,
  96405. /* 1280 */ 116, 193, 165, 174, 175, 174, 175, 194, 199, 150,
  96406. /* 1290 */ 200, 126, 56, 124, 123, 150, 201, 122, 150, 86,
  96407. /* 1300 */ 87, 150, 66, 193, 165, 202, 93, 94, 95, 150,
  96408. /* 1310 */ 165, 98, 194, 165, 125, 22, 165, 150, 150, 26,
  96409. /* 1320 */ 27, 135, 86, 87, 165, 174, 175, 203, 226, 93,
  96410. /* 1330 */ 94, 95, 165, 165, 98, 150, 218, 150, 193, 157,
  96411. /* 1340 */ 118, 157, 129, 130, 131, 132, 133, 134, 5, 104,
  96412. /* 1350 */ 165, 211, 165, 10, 11, 12, 13, 14, 150, 66,
  96413. /* 1360 */ 17, 174, 175, 210, 246, 129, 130, 131, 132, 133,
  96414. /* 1370 */ 134, 150, 210, 165, 31, 121, 33, 150, 150, 86,
  96415. /* 1380 */ 87, 176, 174, 175, 150, 42, 165, 94, 211, 210,
  96416. /* 1390 */ 150, 98, 165, 165, 211, 174, 175, 150, 55, 165,
  96417. /* 1400 */ 57, 150, 174, 175, 61, 165, 150, 64, 174, 175,
  96418. /* 1410 */ 150, 150, 165, 150, 174, 175, 165, 104, 150, 184,
  96419. /* 1420 */ 150, 165, 129, 130, 131, 165, 165, 150, 165, 150,
  96420. /* 1430 */ 150, 176, 150, 165, 47, 165, 150, 150, 176, 103,
  96421. /* 1440 */ 150, 22, 165, 178, 165, 165, 179, 165, 105, 106,
  96422. /* 1450 */ 107, 165, 165, 229, 111, 165, 92, 176, 229, 116,
  96423. /* 1460 */ 184, 176, 179, 156, 176, 176, 18, 157, 156, 237,
  96424. /* 1470 */ 45, 157, 156, 135, 157, 157, 238, 156, 68, 157,
  96425. /* 1480 */ 189, 189, 139, 219, 22, 157, 18, 192, 192, 192,
  96426. /* 1490 */ 192, 189, 219, 199, 157, 242, 40, 157, 199, 242,
  96427. /* 1500 */ 153, 157, 38, 245, 196, 166, 232, 198, 177, 177,
  96428. /* 1510 */ 232, 227, 209, 178, 166, 182, 166, 148, 177, 177,
  96429. /* 1520 */ 209, 196, 177, 199, 209, 199, 166, 208, 92, 195,
  96430. /* 1530 */ 174, 174, 183, 252, 183, 183, 252, 191, 252, 235,
  96431. /* 1540 */ 186, 241, 241, 252, 186, 252, 252, 252, 252, 252,
  96432. /* 1550 */ 252, 252, 252, 252, 252, 252, 236,
  96433. };
  96434. #define YY_SHIFT_USE_DFLT (-74)
  96435. #define YY_SHIFT_COUNT (418)
  96436. #define YY_SHIFT_MIN (-73)
  96437. #define YY_SHIFT_MAX (1468)
  96438. static const short yy_shift_ofst[] = {
  96439. /* 0 */ 975, 1114, 1343, 1114, 1213, 1213, 90, 90, 0, -19,
  96440. /* 10 */ 1213, 1213, 1213, 1213, 1213, 345, 445, 721, 1091, 1213,
  96441. /* 20 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
  96442. /* 30 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
  96443. /* 40 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
  96444. /* 50 */ 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
  96445. /* 60 */ 1213, 199, 445, 445, 835, 835, 365, 1164, 55, 647,
  96446. /* 70 */ 573, 499, 425, 351, 277, 203, 129, 795, 795, 795,
  96447. /* 80 */ 795, 795, 795, 795, 795, 795, 795, 795, 795, 795,
  96448. /* 90 */ 795, 795, 795, 795, 795, 869, 795, 943, 1017, 1017,
  96449. /* 100 */ -69, -45, -45, -45, -45, -45, -1, 58, 138, 100,
  96450. /* 110 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
  96451. /* 120 */ 445, 445, 445, 445, 445, 445, 537, 438, 445, 445,
  96452. /* 130 */ 445, 445, 445, 365, 807, 1436, -74, -74, -74, 1293,
  96453. /* 140 */ 73, 434, 434, 311, 314, 290, 283, 286, 540, 467,
  96454. /* 150 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
  96455. /* 160 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
  96456. /* 170 */ 445, 445, 445, 445, 445, 445, 445, 445, 445, 445,
  96457. /* 180 */ 445, 445, 65, 722, 722, 722, 688, 266, 1164, 1164,
  96458. /* 190 */ 1164, -74, -74, -74, 136, 168, 168, 234, 360, 360,
  96459. /* 200 */ 360, 430, 372, 435, 352, 278, 126, -36, -36, -36,
  96460. /* 210 */ -36, 421, 651, -36, -36, 592, 292, 212, 623, 158,
  96461. /* 220 */ 204, 204, 505, 158, 505, 144, 365, 154, 365, 154,
  96462. /* 230 */ 645, 154, 204, 154, 154, 535, 548, 548, 365, 387,
  96463. /* 240 */ 508, 233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
  96464. /* 250 */ 1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
  96465. /* 260 */ 1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
  96466. /* 270 */ 1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
  96467. /* 280 */ 1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
  96468. /* 290 */ 1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
  96469. /* 300 */ 1243, 1244, 1244, 1212, 1212, 1212, 1212, -74, -74, -74,
  96470. /* 310 */ -74, -74, -74, 939, 104, 680, 571, 327, 1, 980,
  96471. /* 320 */ 26, 972, 971, 946, 901, 870, 830, 806, 54, 21,
  96472. /* 330 */ -73, 510, 242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
  96473. /* 340 */ 1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
  96474. /* 350 */ 1121, 1005, 1099, 951, 1043, 1003, 969, 1045, 1035, 950,
  96475. /* 360 */ 1053, 1047, 1025, 942, 913, 992, 1019, 945, 984, 940,
  96476. /* 370 */ 876, 904, 953, 896, 748, 804, 880, 786, 868, 819,
  96477. /* 380 */ 805, 810, 773, 751, 766, 706, 716, 691, 681, 568,
  96478. /* 390 */ 655, 638, 676, 516, 541, 594, 599, 567, 541, 534,
  96479. /* 400 */ 507, 527, 498, 523, 466, 382, 409, 384, 357, 6,
  96480. /* 410 */ 240, 224, 143, 62, 18, 71, 39, 9, 5,
  96481. };
  96482. #define YY_REDUCE_USE_DFLT (-142)
  96483. #define YY_REDUCE_COUNT (312)
  96484. #define YY_REDUCE_MIN (-141)
  96485. #define YY_REDUCE_MAX (1369)
  96486. static const short yy_reduce_ofst[] = {
  96487. /* 0 */ -141, 994, 1118, 223, 157, -53, 93, 89, 83, 375,
  96488. /* 10 */ 386, 381, 379, 308, 295, 325, -47, 27, 1240, 1234,
  96489. /* 20 */ 1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
  96490. /* 30 */ 1016, 1000, 911, 908, 906, 890, 888, 874, 834, 816,
  96491. /* 40 */ 800, 760, 758, 755, 742, 739, 726, 685, 672, 668,
  96492. /* 50 */ 665, 652, 611, 609, 607, 604, 591, 578, 526, 519,
  96493. /* 60 */ 453, 474, 454, 461, 443, 245, 442, 473, 484, 484,
  96494. /* 70 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
  96495. /* 80 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
  96496. /* 90 */ 484, 484, 484, 484, 484, 484, 484, 484, 484, 484,
  96497. /* 100 */ 484, 484, 484, 484, 484, 484, 484, 130, 484, 484,
  96498. /* 110 */ 1145, 909, 1110, 1088, 1084, 1033, 1002, 965, 820, 837,
  96499. /* 120 */ 746, 686, 612, 817, 610, 919, 221, 563, 814, 813,
  96500. /* 130 */ 744, 669, 470, 543, 484, 484, 484, 484, 484, 291,
  96501. /* 140 */ 569, 671, 658, 970, 1290, 1287, 1286, 1282, 518, 518,
  96502. /* 150 */ 1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
  96503. /* 160 */ 1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
  96504. /* 170 */ 1049, 1006, 998, 996, 995, 973, 970, 966, 964, 892,
  96505. /* 180 */ 762, -52, 881, 932, 802, 731, 619, 812, 664, 660,
  96506. /* 190 */ 627, 392, 331, 124, 1358, 1357, 1356, 1354, 1352, 1351,
  96507. /* 200 */ 1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
  96508. /* 210 */ 1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
  96509. /* 220 */ 1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
  96510. /* 230 */ 1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
  96511. /* 240 */ 1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
  96512. /* 250 */ 1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
  96513. /* 260 */ 1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
  96514. /* 270 */ 1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
  96515. /* 280 */ 1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
  96516. /* 290 */ 1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
  96517. /* 300 */ 1112, 1115, 1086, 1105, 1092, 1087, 1068, 962, 955, 957,
  96518. /* 310 */ 1031, 1023, 1030,
  96519. };
  96520. static const YYACTIONTYPE yy_default[] = {
  96521. /* 0 */ 635, 870, 959, 959, 959, 870, 899, 899, 959, 759,
  96522. /* 10 */ 959, 959, 959, 959, 868, 959, 959, 933, 959, 959,
  96523. /* 20 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96524. /* 30 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96525. /* 40 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96526. /* 50 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96527. /* 60 */ 959, 959, 959, 959, 899, 899, 674, 763, 794, 959,
  96528. /* 70 */ 959, 959, 959, 959, 959, 959, 959, 932, 934, 809,
  96529. /* 80 */ 808, 802, 801, 912, 774, 799, 792, 785, 796, 871,
  96530. /* 90 */ 864, 865, 863, 867, 872, 959, 795, 831, 848, 830,
  96531. /* 100 */ 842, 847, 854, 846, 843, 833, 832, 666, 834, 835,
  96532. /* 110 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96533. /* 120 */ 959, 959, 959, 959, 959, 959, 661, 728, 959, 959,
  96534. /* 130 */ 959, 959, 959, 959, 836, 837, 851, 850, 849, 959,
  96535. /* 140 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96536. /* 150 */ 959, 939, 937, 959, 883, 959, 959, 959, 959, 959,
  96537. /* 160 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96538. /* 170 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96539. /* 180 */ 959, 641, 959, 759, 759, 759, 635, 959, 959, 959,
  96540. /* 190 */ 959, 951, 763, 753, 719, 959, 959, 959, 959, 959,
  96541. /* 200 */ 959, 959, 959, 959, 959, 959, 959, 804, 742, 922,
  96542. /* 210 */ 924, 959, 905, 740, 663, 761, 676, 751, 643, 798,
  96543. /* 220 */ 776, 776, 917, 798, 917, 700, 959, 788, 959, 788,
  96544. /* 230 */ 697, 788, 776, 788, 788, 866, 959, 959, 959, 760,
  96545. /* 240 */ 751, 959, 944, 767, 767, 936, 936, 767, 810, 732,
  96546. /* 250 */ 798, 739, 739, 739, 739, 767, 798, 810, 732, 732,
  96547. /* 260 */ 767, 658, 911, 909, 767, 767, 658, 767, 658, 767,
  96548. /* 270 */ 658, 876, 730, 730, 730, 715, 880, 880, 876, 730,
  96549. /* 280 */ 700, 730, 715, 730, 730, 780, 775, 780, 775, 780,
  96550. /* 290 */ 775, 767, 767, 959, 793, 781, 791, 789, 798, 959,
  96551. /* 300 */ 718, 651, 651, 640, 640, 640, 640, 956, 956, 951,
  96552. /* 310 */ 702, 702, 684, 959, 959, 959, 959, 959, 959, 959,
  96553. /* 320 */ 885, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96554. /* 330 */ 959, 959, 959, 959, 636, 946, 959, 959, 943, 959,
  96555. /* 340 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96556. /* 350 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 915,
  96557. /* 360 */ 959, 959, 959, 959, 959, 959, 908, 907, 959, 959,
  96558. /* 370 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96559. /* 380 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 959,
  96560. /* 390 */ 959, 959, 959, 959, 790, 959, 782, 959, 869, 959,
  96561. /* 400 */ 959, 959, 959, 959, 959, 959, 959, 959, 959, 745,
  96562. /* 410 */ 819, 959, 818, 822, 817, 668, 959, 649, 959, 632,
  96563. /* 420 */ 637, 955, 958, 957, 954, 953, 952, 947, 945, 942,
  96564. /* 430 */ 941, 940, 938, 935, 931, 889, 887, 894, 893, 892,
  96565. /* 440 */ 891, 890, 888, 886, 884, 805, 803, 800, 797, 930,
  96566. /* 450 */ 882, 741, 738, 737, 657, 948, 914, 923, 921, 811,
  96567. /* 460 */ 920, 919, 918, 916, 913, 900, 807, 806, 733, 874,
  96568. /* 470 */ 873, 660, 904, 903, 902, 906, 910, 901, 769, 659,
  96569. /* 480 */ 656, 665, 722, 721, 729, 727, 726, 725, 724, 723,
  96570. /* 490 */ 720, 667, 675, 686, 714, 699, 698, 879, 881, 878,
  96571. /* 500 */ 877, 707, 706, 712, 711, 710, 709, 708, 705, 704,
  96572. /* 510 */ 703, 696, 695, 701, 694, 717, 716, 713, 693, 736,
  96573. /* 520 */ 735, 734, 731, 692, 691, 690, 822, 689, 688, 828,
  96574. /* 530 */ 827, 815, 858, 756, 755, 754, 766, 765, 778, 777,
  96575. /* 540 */ 813, 812, 779, 764, 758, 757, 773, 772, 771, 770,
  96576. /* 550 */ 762, 752, 784, 787, 786, 783, 860, 768, 857, 929,
  96577. /* 560 */ 928, 927, 926, 925, 862, 861, 829, 826, 679, 680,
  96578. /* 570 */ 898, 896, 897, 895, 682, 681, 678, 677, 859, 747,
  96579. /* 580 */ 746, 855, 852, 844, 840, 856, 853, 845, 841, 839,
  96580. /* 590 */ 838, 824, 823, 821, 820, 816, 825, 670, 748, 744,
  96581. /* 600 */ 743, 814, 750, 749, 687, 685, 683, 664, 662, 655,
  96582. /* 610 */ 653, 652, 654, 650, 648, 647, 646, 645, 644, 673,
  96583. /* 620 */ 672, 671, 669, 668, 642, 639, 638, 634, 633, 631,
  96584. };
  96585. /* The next table maps tokens into fallback tokens. If a construct
  96586. ** like the following:
  96587. **
  96588. ** %fallback ID X Y Z.
  96589. **
  96590. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  96591. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  96592. ** but it does not parse, the type of the token is changed to ID and
  96593. ** the parse is retried before an error is thrown.
  96594. */
  96595. #ifdef YYFALLBACK
  96596. static const YYCODETYPE yyFallback[] = {
  96597. 0, /* $ => nothing */
  96598. 0, /* SEMI => nothing */
  96599. 26, /* EXPLAIN => ID */
  96600. 26, /* QUERY => ID */
  96601. 26, /* PLAN => ID */
  96602. 26, /* BEGIN => ID */
  96603. 0, /* TRANSACTION => nothing */
  96604. 26, /* DEFERRED => ID */
  96605. 26, /* IMMEDIATE => ID */
  96606. 26, /* EXCLUSIVE => ID */
  96607. 0, /* COMMIT => nothing */
  96608. 26, /* END => ID */
  96609. 26, /* ROLLBACK => ID */
  96610. 26, /* SAVEPOINT => ID */
  96611. 26, /* RELEASE => ID */
  96612. 0, /* TO => nothing */
  96613. 0, /* TABLE => nothing */
  96614. 0, /* CREATE => nothing */
  96615. 26, /* IF => ID */
  96616. 0, /* NOT => nothing */
  96617. 0, /* EXISTS => nothing */
  96618. 26, /* TEMP => ID */
  96619. 0, /* LP => nothing */
  96620. 0, /* RP => nothing */
  96621. 0, /* AS => nothing */
  96622. 0, /* COMMA => nothing */
  96623. 0, /* ID => nothing */
  96624. 0, /* INDEXED => nothing */
  96625. 26, /* ABORT => ID */
  96626. 26, /* ACTION => ID */
  96627. 26, /* AFTER => ID */
  96628. 26, /* ANALYZE => ID */
  96629. 26, /* ASC => ID */
  96630. 26, /* ATTACH => ID */
  96631. 26, /* BEFORE => ID */
  96632. 26, /* BY => ID */
  96633. 26, /* CASCADE => ID */
  96634. 26, /* CAST => ID */
  96635. 26, /* COLUMNKW => ID */
  96636. 26, /* CONFLICT => ID */
  96637. 26, /* DATABASE => ID */
  96638. 26, /* DESC => ID */
  96639. 26, /* DETACH => ID */
  96640. 26, /* EACH => ID */
  96641. 26, /* FAIL => ID */
  96642. 26, /* FOR => ID */
  96643. 26, /* IGNORE => ID */
  96644. 26, /* INITIALLY => ID */
  96645. 26, /* INSTEAD => ID */
  96646. 26, /* LIKE_KW => ID */
  96647. 26, /* MATCH => ID */
  96648. 26, /* NO => ID */
  96649. 26, /* KEY => ID */
  96650. 26, /* OF => ID */
  96651. 26, /* OFFSET => ID */
  96652. 26, /* PRAGMA => ID */
  96653. 26, /* RAISE => ID */
  96654. 26, /* REPLACE => ID */
  96655. 26, /* RESTRICT => ID */
  96656. 26, /* ROW => ID */
  96657. 26, /* TRIGGER => ID */
  96658. 26, /* VACUUM => ID */
  96659. 26, /* VIEW => ID */
  96660. 26, /* VIRTUAL => ID */
  96661. 26, /* REINDEX => ID */
  96662. 26, /* RENAME => ID */
  96663. 26, /* CTIME_KW => ID */
  96664. };
  96665. #endif /* YYFALLBACK */
  96666. /* The following structure represents a single element of the
  96667. ** parser's stack. Information stored includes:
  96668. **
  96669. ** + The state number for the parser at this level of the stack.
  96670. **
  96671. ** + The value of the token stored at this level of the stack.
  96672. ** (In other words, the "major" token.)
  96673. **
  96674. ** + The semantic value stored at this level of the stack. This is
  96675. ** the information used by the action routines in the grammar.
  96676. ** It is sometimes called the "minor" token.
  96677. */
  96678. struct yyStackEntry {
  96679. YYACTIONTYPE stateno; /* The state-number */
  96680. YYCODETYPE major; /* The major token value. This is the code
  96681. ** number for the token at this stack level */
  96682. YYMINORTYPE minor; /* The user-supplied minor token value. This
  96683. ** is the value of the token */
  96684. };
  96685. typedef struct yyStackEntry yyStackEntry;
  96686. /* The state of the parser is completely contained in an instance of
  96687. ** the following structure */
  96688. struct yyParser {
  96689. int yyidx; /* Index of top element in stack */
  96690. #ifdef YYTRACKMAXSTACKDEPTH
  96691. int yyidxMax; /* Maximum value of yyidx */
  96692. #endif
  96693. int yyerrcnt; /* Shifts left before out of the error */
  96694. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  96695. #if YYSTACKDEPTH<=0
  96696. int yystksz; /* Current side of the stack */
  96697. yyStackEntry *yystack; /* The parser's stack */
  96698. #else
  96699. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  96700. #endif
  96701. };
  96702. typedef struct yyParser yyParser;
  96703. #ifndef NDEBUG
  96704. static FILE *yyTraceFILE = 0;
  96705. static char *yyTracePrompt = 0;
  96706. #endif /* NDEBUG */
  96707. #ifndef NDEBUG
  96708. /*
  96709. ** Turn parser tracing on by giving a stream to which to write the trace
  96710. ** and a prompt to preface each trace message. Tracing is turned off
  96711. ** by making either argument NULL
  96712. **
  96713. ** Inputs:
  96714. ** <ul>
  96715. ** <li> A FILE* to which trace output should be written.
  96716. ** If NULL, then tracing is turned off.
  96717. ** <li> A prefix string written at the beginning of every
  96718. ** line of trace output. If NULL, then tracing is
  96719. ** turned off.
  96720. ** </ul>
  96721. **
  96722. ** Outputs:
  96723. ** None.
  96724. */
  96725. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  96726. yyTraceFILE = TraceFILE;
  96727. yyTracePrompt = zTracePrompt;
  96728. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  96729. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  96730. }
  96731. #endif /* NDEBUG */
  96732. #ifndef NDEBUG
  96733. /* For tracing shifts, the names of all terminals and nonterminals
  96734. ** are required. The following table supplies these names */
  96735. static const char *const yyTokenName[] = {
  96736. "$", "SEMI", "EXPLAIN", "QUERY",
  96737. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  96738. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  96739. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  96740. "TABLE", "CREATE", "IF", "NOT",
  96741. "EXISTS", "TEMP", "LP", "RP",
  96742. "AS", "COMMA", "ID", "INDEXED",
  96743. "ABORT", "ACTION", "AFTER", "ANALYZE",
  96744. "ASC", "ATTACH", "BEFORE", "BY",
  96745. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  96746. "DATABASE", "DESC", "DETACH", "EACH",
  96747. "FAIL", "FOR", "IGNORE", "INITIALLY",
  96748. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  96749. "KEY", "OF", "OFFSET", "PRAGMA",
  96750. "RAISE", "REPLACE", "RESTRICT", "ROW",
  96751. "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
  96752. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  96753. "OR", "AND", "IS", "BETWEEN",
  96754. "IN", "ISNULL", "NOTNULL", "NE",
  96755. "EQ", "GT", "LE", "LT",
  96756. "GE", "ESCAPE", "BITAND", "BITOR",
  96757. "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  96758. "STAR", "SLASH", "REM", "CONCAT",
  96759. "COLLATE", "BITNOT", "STRING", "JOIN_KW",
  96760. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  96761. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  96762. "ON", "INSERT", "DELETE", "UPDATE",
  96763. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  96764. "UNION", "ALL", "EXCEPT", "INTERSECT",
  96765. "SELECT", "DISTINCT", "DOT", "FROM",
  96766. "JOIN", "USING", "ORDER", "GROUP",
  96767. "HAVING", "LIMIT", "WHERE", "INTO",
  96768. "VALUES", "INTEGER", "FLOAT", "BLOB",
  96769. "REGISTER", "VARIABLE", "CASE", "WHEN",
  96770. "THEN", "ELSE", "INDEX", "ALTER",
  96771. "ADD", "error", "input", "cmdlist",
  96772. "ecmd", "explain", "cmdx", "cmd",
  96773. "transtype", "trans_opt", "nm", "savepoint_opt",
  96774. "create_table", "create_table_args", "createkw", "temp",
  96775. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  96776. "select", "column", "columnid", "type",
  96777. "carglist", "id", "ids", "typetoken",
  96778. "typename", "signed", "plus_num", "minus_num",
  96779. "carg", "ccons", "term", "expr",
  96780. "onconf", "sortorder", "autoinc", "idxlist_opt",
  96781. "refargs", "defer_subclause", "refarg", "refact",
  96782. "init_deferred_pred_opt", "conslist", "tcons", "idxlist",
  96783. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  96784. "ifexists", "fullname", "oneselect", "multiselect_op",
  96785. "distinct", "selcollist", "from", "where_opt",
  96786. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  96787. "sclp", "as", "seltablist", "stl_prefix",
  96788. "joinop", "indexed_opt", "on_opt", "using_opt",
  96789. "joinop2", "inscollist", "sortlist", "sortitem",
  96790. "nexprlist", "setlist", "insert_cmd", "inscollist_opt",
  96791. "itemlist", "exprlist", "likeop", "between_op",
  96792. "in_op", "case_operand", "case_exprlist", "case_else",
  96793. "uniqueflag", "collate", "nmnum", "plus_opt",
  96794. "number", "trigger_decl", "trigger_cmd_list", "trigger_time",
  96795. "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
  96796. "trnm", "tridxby", "database_kw_opt", "key_opt",
  96797. "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
  96798. "vtabarg", "vtabargtoken", "lp", "anylist",
  96799. };
  96800. #endif /* NDEBUG */
  96801. #ifndef NDEBUG
  96802. /* For tracing reduce actions, the names of all rules are required.
  96803. */
  96804. static const char *const yyRuleName[] = {
  96805. /* 0 */ "input ::= cmdlist",
  96806. /* 1 */ "cmdlist ::= cmdlist ecmd",
  96807. /* 2 */ "cmdlist ::= ecmd",
  96808. /* 3 */ "ecmd ::= SEMI",
  96809. /* 4 */ "ecmd ::= explain cmdx SEMI",
  96810. /* 5 */ "explain ::=",
  96811. /* 6 */ "explain ::= EXPLAIN",
  96812. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  96813. /* 8 */ "cmdx ::= cmd",
  96814. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  96815. /* 10 */ "trans_opt ::=",
  96816. /* 11 */ "trans_opt ::= TRANSACTION",
  96817. /* 12 */ "trans_opt ::= TRANSACTION nm",
  96818. /* 13 */ "transtype ::=",
  96819. /* 14 */ "transtype ::= DEFERRED",
  96820. /* 15 */ "transtype ::= IMMEDIATE",
  96821. /* 16 */ "transtype ::= EXCLUSIVE",
  96822. /* 17 */ "cmd ::= COMMIT trans_opt",
  96823. /* 18 */ "cmd ::= END trans_opt",
  96824. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  96825. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  96826. /* 21 */ "savepoint_opt ::=",
  96827. /* 22 */ "cmd ::= SAVEPOINT nm",
  96828. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  96829. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  96830. /* 25 */ "cmd ::= create_table create_table_args",
  96831. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  96832. /* 27 */ "createkw ::= CREATE",
  96833. /* 28 */ "ifnotexists ::=",
  96834. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  96835. /* 30 */ "temp ::= TEMP",
  96836. /* 31 */ "temp ::=",
  96837. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  96838. /* 33 */ "create_table_args ::= AS select",
  96839. /* 34 */ "columnlist ::= columnlist COMMA column",
  96840. /* 35 */ "columnlist ::= column",
  96841. /* 36 */ "column ::= columnid type carglist",
  96842. /* 37 */ "columnid ::= nm",
  96843. /* 38 */ "id ::= ID",
  96844. /* 39 */ "id ::= INDEXED",
  96845. /* 40 */ "ids ::= ID|STRING",
  96846. /* 41 */ "nm ::= id",
  96847. /* 42 */ "nm ::= STRING",
  96848. /* 43 */ "nm ::= JOIN_KW",
  96849. /* 44 */ "type ::=",
  96850. /* 45 */ "type ::= typetoken",
  96851. /* 46 */ "typetoken ::= typename",
  96852. /* 47 */ "typetoken ::= typename LP signed RP",
  96853. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  96854. /* 49 */ "typename ::= ids",
  96855. /* 50 */ "typename ::= typename ids",
  96856. /* 51 */ "signed ::= plus_num",
  96857. /* 52 */ "signed ::= minus_num",
  96858. /* 53 */ "carglist ::= carglist carg",
  96859. /* 54 */ "carglist ::=",
  96860. /* 55 */ "carg ::= CONSTRAINT nm ccons",
  96861. /* 56 */ "carg ::= ccons",
  96862. /* 57 */ "ccons ::= DEFAULT term",
  96863. /* 58 */ "ccons ::= DEFAULT LP expr RP",
  96864. /* 59 */ "ccons ::= DEFAULT PLUS term",
  96865. /* 60 */ "ccons ::= DEFAULT MINUS term",
  96866. /* 61 */ "ccons ::= DEFAULT id",
  96867. /* 62 */ "ccons ::= NULL onconf",
  96868. /* 63 */ "ccons ::= NOT NULL onconf",
  96869. /* 64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  96870. /* 65 */ "ccons ::= UNIQUE onconf",
  96871. /* 66 */ "ccons ::= CHECK LP expr RP",
  96872. /* 67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  96873. /* 68 */ "ccons ::= defer_subclause",
  96874. /* 69 */ "ccons ::= COLLATE ids",
  96875. /* 70 */ "autoinc ::=",
  96876. /* 71 */ "autoinc ::= AUTOINCR",
  96877. /* 72 */ "refargs ::=",
  96878. /* 73 */ "refargs ::= refargs refarg",
  96879. /* 74 */ "refarg ::= MATCH nm",
  96880. /* 75 */ "refarg ::= ON INSERT refact",
  96881. /* 76 */ "refarg ::= ON DELETE refact",
  96882. /* 77 */ "refarg ::= ON UPDATE refact",
  96883. /* 78 */ "refact ::= SET NULL",
  96884. /* 79 */ "refact ::= SET DEFAULT",
  96885. /* 80 */ "refact ::= CASCADE",
  96886. /* 81 */ "refact ::= RESTRICT",
  96887. /* 82 */ "refact ::= NO ACTION",
  96888. /* 83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  96889. /* 84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  96890. /* 85 */ "init_deferred_pred_opt ::=",
  96891. /* 86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  96892. /* 87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  96893. /* 88 */ "conslist_opt ::=",
  96894. /* 89 */ "conslist_opt ::= COMMA conslist",
  96895. /* 90 */ "conslist ::= conslist COMMA tcons",
  96896. /* 91 */ "conslist ::= conslist tcons",
  96897. /* 92 */ "conslist ::= tcons",
  96898. /* 93 */ "tcons ::= CONSTRAINT nm",
  96899. /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  96900. /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  96901. /* 96 */ "tcons ::= CHECK LP expr RP onconf",
  96902. /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  96903. /* 98 */ "defer_subclause_opt ::=",
  96904. /* 99 */ "defer_subclause_opt ::= defer_subclause",
  96905. /* 100 */ "onconf ::=",
  96906. /* 101 */ "onconf ::= ON CONFLICT resolvetype",
  96907. /* 102 */ "orconf ::=",
  96908. /* 103 */ "orconf ::= OR resolvetype",
  96909. /* 104 */ "resolvetype ::= raisetype",
  96910. /* 105 */ "resolvetype ::= IGNORE",
  96911. /* 106 */ "resolvetype ::= REPLACE",
  96912. /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
  96913. /* 108 */ "ifexists ::= IF EXISTS",
  96914. /* 109 */ "ifexists ::=",
  96915. /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  96916. /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
  96917. /* 112 */ "cmd ::= select",
  96918. /* 113 */ "select ::= oneselect",
  96919. /* 114 */ "select ::= select multiselect_op oneselect",
  96920. /* 115 */ "multiselect_op ::= UNION",
  96921. /* 116 */ "multiselect_op ::= UNION ALL",
  96922. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  96923. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  96924. /* 119 */ "distinct ::= DISTINCT",
  96925. /* 120 */ "distinct ::= ALL",
  96926. /* 121 */ "distinct ::=",
  96927. /* 122 */ "sclp ::= selcollist COMMA",
  96928. /* 123 */ "sclp ::=",
  96929. /* 124 */ "selcollist ::= sclp expr as",
  96930. /* 125 */ "selcollist ::= sclp STAR",
  96931. /* 126 */ "selcollist ::= sclp nm DOT STAR",
  96932. /* 127 */ "as ::= AS nm",
  96933. /* 128 */ "as ::= ids",
  96934. /* 129 */ "as ::=",
  96935. /* 130 */ "from ::=",
  96936. /* 131 */ "from ::= FROM seltablist",
  96937. /* 132 */ "stl_prefix ::= seltablist joinop",
  96938. /* 133 */ "stl_prefix ::=",
  96939. /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  96940. /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  96941. /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  96942. /* 137 */ "dbnm ::=",
  96943. /* 138 */ "dbnm ::= DOT nm",
  96944. /* 139 */ "fullname ::= nm dbnm",
  96945. /* 140 */ "joinop ::= COMMA|JOIN",
  96946. /* 141 */ "joinop ::= JOIN_KW JOIN",
  96947. /* 142 */ "joinop ::= JOIN_KW nm JOIN",
  96948. /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
  96949. /* 144 */ "on_opt ::= ON expr",
  96950. /* 145 */ "on_opt ::=",
  96951. /* 146 */ "indexed_opt ::=",
  96952. /* 147 */ "indexed_opt ::= INDEXED BY nm",
  96953. /* 148 */ "indexed_opt ::= NOT INDEXED",
  96954. /* 149 */ "using_opt ::= USING LP inscollist RP",
  96955. /* 150 */ "using_opt ::=",
  96956. /* 151 */ "orderby_opt ::=",
  96957. /* 152 */ "orderby_opt ::= ORDER BY sortlist",
  96958. /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
  96959. /* 154 */ "sortlist ::= sortitem sortorder",
  96960. /* 155 */ "sortitem ::= expr",
  96961. /* 156 */ "sortorder ::= ASC",
  96962. /* 157 */ "sortorder ::= DESC",
  96963. /* 158 */ "sortorder ::=",
  96964. /* 159 */ "groupby_opt ::=",
  96965. /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
  96966. /* 161 */ "having_opt ::=",
  96967. /* 162 */ "having_opt ::= HAVING expr",
  96968. /* 163 */ "limit_opt ::=",
  96969. /* 164 */ "limit_opt ::= LIMIT expr",
  96970. /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
  96971. /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
  96972. /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  96973. /* 168 */ "where_opt ::=",
  96974. /* 169 */ "where_opt ::= WHERE expr",
  96975. /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  96976. /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
  96977. /* 172 */ "setlist ::= nm EQ expr",
  96978. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
  96979. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  96980. /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  96981. /* 176 */ "insert_cmd ::= INSERT orconf",
  96982. /* 177 */ "insert_cmd ::= REPLACE",
  96983. /* 178 */ "itemlist ::= itemlist COMMA expr",
  96984. /* 179 */ "itemlist ::= expr",
  96985. /* 180 */ "inscollist_opt ::=",
  96986. /* 181 */ "inscollist_opt ::= LP inscollist RP",
  96987. /* 182 */ "inscollist ::= inscollist COMMA nm",
  96988. /* 183 */ "inscollist ::= nm",
  96989. /* 184 */ "expr ::= term",
  96990. /* 185 */ "expr ::= LP expr RP",
  96991. /* 186 */ "term ::= NULL",
  96992. /* 187 */ "expr ::= id",
  96993. /* 188 */ "expr ::= JOIN_KW",
  96994. /* 189 */ "expr ::= nm DOT nm",
  96995. /* 190 */ "expr ::= nm DOT nm DOT nm",
  96996. /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
  96997. /* 192 */ "term ::= STRING",
  96998. /* 193 */ "expr ::= REGISTER",
  96999. /* 194 */ "expr ::= VARIABLE",
  97000. /* 195 */ "expr ::= expr COLLATE ids",
  97001. /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
  97002. /* 197 */ "expr ::= ID LP distinct exprlist RP",
  97003. /* 198 */ "expr ::= ID LP STAR RP",
  97004. /* 199 */ "term ::= CTIME_KW",
  97005. /* 200 */ "expr ::= expr AND expr",
  97006. /* 201 */ "expr ::= expr OR expr",
  97007. /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
  97008. /* 203 */ "expr ::= expr EQ|NE expr",
  97009. /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  97010. /* 205 */ "expr ::= expr PLUS|MINUS expr",
  97011. /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
  97012. /* 207 */ "expr ::= expr CONCAT expr",
  97013. /* 208 */ "likeop ::= LIKE_KW",
  97014. /* 209 */ "likeop ::= NOT LIKE_KW",
  97015. /* 210 */ "likeop ::= MATCH",
  97016. /* 211 */ "likeop ::= NOT MATCH",
  97017. /* 212 */ "expr ::= expr likeop expr",
  97018. /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
  97019. /* 214 */ "expr ::= expr ISNULL|NOTNULL",
  97020. /* 215 */ "expr ::= expr NOT NULL",
  97021. /* 216 */ "expr ::= expr IS expr",
  97022. /* 217 */ "expr ::= expr IS NOT expr",
  97023. /* 218 */ "expr ::= NOT expr",
  97024. /* 219 */ "expr ::= BITNOT expr",
  97025. /* 220 */ "expr ::= MINUS expr",
  97026. /* 221 */ "expr ::= PLUS expr",
  97027. /* 222 */ "between_op ::= BETWEEN",
  97028. /* 223 */ "between_op ::= NOT BETWEEN",
  97029. /* 224 */ "expr ::= expr between_op expr AND expr",
  97030. /* 225 */ "in_op ::= IN",
  97031. /* 226 */ "in_op ::= NOT IN",
  97032. /* 227 */ "expr ::= expr in_op LP exprlist RP",
  97033. /* 228 */ "expr ::= LP select RP",
  97034. /* 229 */ "expr ::= expr in_op LP select RP",
  97035. /* 230 */ "expr ::= expr in_op nm dbnm",
  97036. /* 231 */ "expr ::= EXISTS LP select RP",
  97037. /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
  97038. /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  97039. /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
  97040. /* 235 */ "case_else ::= ELSE expr",
  97041. /* 236 */ "case_else ::=",
  97042. /* 237 */ "case_operand ::= expr",
  97043. /* 238 */ "case_operand ::=",
  97044. /* 239 */ "exprlist ::= nexprlist",
  97045. /* 240 */ "exprlist ::=",
  97046. /* 241 */ "nexprlist ::= nexprlist COMMA expr",
  97047. /* 242 */ "nexprlist ::= expr",
  97048. /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
  97049. /* 244 */ "uniqueflag ::= UNIQUE",
  97050. /* 245 */ "uniqueflag ::=",
  97051. /* 246 */ "idxlist_opt ::=",
  97052. /* 247 */ "idxlist_opt ::= LP idxlist RP",
  97053. /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  97054. /* 249 */ "idxlist ::= nm collate sortorder",
  97055. /* 250 */ "collate ::=",
  97056. /* 251 */ "collate ::= COLLATE ids",
  97057. /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
  97058. /* 253 */ "cmd ::= VACUUM",
  97059. /* 254 */ "cmd ::= VACUUM nm",
  97060. /* 255 */ "cmd ::= PRAGMA nm dbnm",
  97061. /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  97062. /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  97063. /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  97064. /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  97065. /* 260 */ "nmnum ::= plus_num",
  97066. /* 261 */ "nmnum ::= nm",
  97067. /* 262 */ "nmnum ::= ON",
  97068. /* 263 */ "nmnum ::= DELETE",
  97069. /* 264 */ "nmnum ::= DEFAULT",
  97070. /* 265 */ "plus_num ::= plus_opt number",
  97071. /* 266 */ "minus_num ::= MINUS number",
  97072. /* 267 */ "number ::= INTEGER|FLOAT",
  97073. /* 268 */ "plus_opt ::= PLUS",
  97074. /* 269 */ "plus_opt ::=",
  97075. /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  97076. /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  97077. /* 272 */ "trigger_time ::= BEFORE",
  97078. /* 273 */ "trigger_time ::= AFTER",
  97079. /* 274 */ "trigger_time ::= INSTEAD OF",
  97080. /* 275 */ "trigger_time ::=",
  97081. /* 276 */ "trigger_event ::= DELETE|INSERT",
  97082. /* 277 */ "trigger_event ::= UPDATE",
  97083. /* 278 */ "trigger_event ::= UPDATE OF inscollist",
  97084. /* 279 */ "foreach_clause ::=",
  97085. /* 280 */ "foreach_clause ::= FOR EACH ROW",
  97086. /* 281 */ "when_clause ::=",
  97087. /* 282 */ "when_clause ::= WHEN expr",
  97088. /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  97089. /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  97090. /* 285 */ "trnm ::= nm",
  97091. /* 286 */ "trnm ::= nm DOT nm",
  97092. /* 287 */ "tridxby ::=",
  97093. /* 288 */ "tridxby ::= INDEXED BY nm",
  97094. /* 289 */ "tridxby ::= NOT INDEXED",
  97095. /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  97096. /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
  97097. /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  97098. /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  97099. /* 294 */ "trigger_cmd ::= select",
  97100. /* 295 */ "expr ::= RAISE LP IGNORE RP",
  97101. /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  97102. /* 297 */ "raisetype ::= ROLLBACK",
  97103. /* 298 */ "raisetype ::= ABORT",
  97104. /* 299 */ "raisetype ::= FAIL",
  97105. /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
  97106. /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  97107. /* 302 */ "cmd ::= DETACH database_kw_opt expr",
  97108. /* 303 */ "key_opt ::=",
  97109. /* 304 */ "key_opt ::= KEY expr",
  97110. /* 305 */ "database_kw_opt ::= DATABASE",
  97111. /* 306 */ "database_kw_opt ::=",
  97112. /* 307 */ "cmd ::= REINDEX",
  97113. /* 308 */ "cmd ::= REINDEX nm dbnm",
  97114. /* 309 */ "cmd ::= ANALYZE",
  97115. /* 310 */ "cmd ::= ANALYZE nm dbnm",
  97116. /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  97117. /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  97118. /* 313 */ "add_column_fullname ::= fullname",
  97119. /* 314 */ "kwcolumn_opt ::=",
  97120. /* 315 */ "kwcolumn_opt ::= COLUMNKW",
  97121. /* 316 */ "cmd ::= create_vtab",
  97122. /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
  97123. /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
  97124. /* 319 */ "vtabarglist ::= vtabarg",
  97125. /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  97126. /* 321 */ "vtabarg ::=",
  97127. /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
  97128. /* 323 */ "vtabargtoken ::= ANY",
  97129. /* 324 */ "vtabargtoken ::= lp anylist RP",
  97130. /* 325 */ "lp ::= LP",
  97131. /* 326 */ "anylist ::=",
  97132. /* 327 */ "anylist ::= anylist LP anylist RP",
  97133. /* 328 */ "anylist ::= anylist ANY",
  97134. };
  97135. #endif /* NDEBUG */
  97136. #if YYSTACKDEPTH<=0
  97137. /*
  97138. ** Try to increase the size of the parser stack.
  97139. */
  97140. static void yyGrowStack(yyParser *p){
  97141. int newSize;
  97142. yyStackEntry *pNew;
  97143. newSize = p->yystksz*2 + 100;
  97144. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  97145. if( pNew ){
  97146. p->yystack = pNew;
  97147. p->yystksz = newSize;
  97148. #ifndef NDEBUG
  97149. if( yyTraceFILE ){
  97150. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  97151. yyTracePrompt, p->yystksz);
  97152. }
  97153. #endif
  97154. }
  97155. }
  97156. #endif
  97157. /*
  97158. ** This function allocates a new parser.
  97159. ** The only argument is a pointer to a function which works like
  97160. ** malloc.
  97161. **
  97162. ** Inputs:
  97163. ** A pointer to the function used to allocate memory.
  97164. **
  97165. ** Outputs:
  97166. ** A pointer to a parser. This pointer is used in subsequent calls
  97167. ** to sqlite3Parser and sqlite3ParserFree.
  97168. */
  97169. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  97170. yyParser *pParser;
  97171. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  97172. if( pParser ){
  97173. pParser->yyidx = -1;
  97174. #ifdef YYTRACKMAXSTACKDEPTH
  97175. pParser->yyidxMax = 0;
  97176. #endif
  97177. #if YYSTACKDEPTH<=0
  97178. pParser->yystack = NULL;
  97179. pParser->yystksz = 0;
  97180. yyGrowStack(pParser);
  97181. #endif
  97182. }
  97183. return pParser;
  97184. }
  97185. /* The following function deletes the value associated with a
  97186. ** symbol. The symbol can be either a terminal or nonterminal.
  97187. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  97188. ** the value.
  97189. */
  97190. static void yy_destructor(
  97191. yyParser *yypParser, /* The parser */
  97192. YYCODETYPE yymajor, /* Type code for object to destroy */
  97193. YYMINORTYPE *yypminor /* The object to be destroyed */
  97194. ){
  97195. sqlite3ParserARG_FETCH;
  97196. switch( yymajor ){
  97197. /* Here is inserted the actions which take place when a
  97198. ** terminal or non-terminal is destroyed. This can happen
  97199. ** when the symbol is popped from the stack during a
  97200. ** reduce or during error processing or when a parser is
  97201. ** being destroyed before it is finished parsing.
  97202. **
  97203. ** Note: during a reduce, the only symbols destroyed are those
  97204. ** which appear on the RHS of the rule, but which are not used
  97205. ** inside the C code.
  97206. */
  97207. case 160: /* select */
  97208. case 194: /* oneselect */
  97209. {
  97210. sqlite3SelectDelete(pParse->db, (yypminor->yy387));
  97211. }
  97212. break;
  97213. case 174: /* term */
  97214. case 175: /* expr */
  97215. {
  97216. sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
  97217. }
  97218. break;
  97219. case 179: /* idxlist_opt */
  97220. case 187: /* idxlist */
  97221. case 197: /* selcollist */
  97222. case 200: /* groupby_opt */
  97223. case 202: /* orderby_opt */
  97224. case 204: /* sclp */
  97225. case 214: /* sortlist */
  97226. case 216: /* nexprlist */
  97227. case 217: /* setlist */
  97228. case 220: /* itemlist */
  97229. case 221: /* exprlist */
  97230. case 226: /* case_exprlist */
  97231. {
  97232. sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
  97233. }
  97234. break;
  97235. case 193: /* fullname */
  97236. case 198: /* from */
  97237. case 206: /* seltablist */
  97238. case 207: /* stl_prefix */
  97239. {
  97240. sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
  97241. }
  97242. break;
  97243. case 199: /* where_opt */
  97244. case 201: /* having_opt */
  97245. case 210: /* on_opt */
  97246. case 215: /* sortitem */
  97247. case 225: /* case_operand */
  97248. case 227: /* case_else */
  97249. case 238: /* when_clause */
  97250. case 243: /* key_opt */
  97251. {
  97252. sqlite3ExprDelete(pParse->db, (yypminor->yy314));
  97253. }
  97254. break;
  97255. case 211: /* using_opt */
  97256. case 213: /* inscollist */
  97257. case 219: /* inscollist_opt */
  97258. {
  97259. sqlite3IdListDelete(pParse->db, (yypminor->yy384));
  97260. }
  97261. break;
  97262. case 234: /* trigger_cmd_list */
  97263. case 239: /* trigger_cmd */
  97264. {
  97265. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
  97266. }
  97267. break;
  97268. case 236: /* trigger_event */
  97269. {
  97270. sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
  97271. }
  97272. break;
  97273. default: break; /* If no destructor action specified: do nothing */
  97274. }
  97275. }
  97276. /*
  97277. ** Pop the parser's stack once.
  97278. **
  97279. ** If there is a destructor routine associated with the token which
  97280. ** is popped from the stack, then call it.
  97281. **
  97282. ** Return the major token number for the symbol popped.
  97283. */
  97284. static int yy_pop_parser_stack(yyParser *pParser){
  97285. YYCODETYPE yymajor;
  97286. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  97287. /* There is no mechanism by which the parser stack can be popped below
  97288. ** empty in SQLite. */
  97289. if( NEVER(pParser->yyidx<0) ) return 0;
  97290. #ifndef NDEBUG
  97291. if( yyTraceFILE && pParser->yyidx>=0 ){
  97292. fprintf(yyTraceFILE,"%sPopping %s\n",
  97293. yyTracePrompt,
  97294. yyTokenName[yytos->major]);
  97295. }
  97296. #endif
  97297. yymajor = yytos->major;
  97298. yy_destructor(pParser, yymajor, &yytos->minor);
  97299. pParser->yyidx--;
  97300. return yymajor;
  97301. }
  97302. /*
  97303. ** Deallocate and destroy a parser. Destructors are all called for
  97304. ** all stack elements before shutting the parser down.
  97305. **
  97306. ** Inputs:
  97307. ** <ul>
  97308. ** <li> A pointer to the parser. This should be a pointer
  97309. ** obtained from sqlite3ParserAlloc.
  97310. ** <li> A pointer to a function used to reclaim memory obtained
  97311. ** from malloc.
  97312. ** </ul>
  97313. */
  97314. SQLITE_PRIVATE void sqlite3ParserFree(
  97315. void *p, /* The parser to be deleted */
  97316. void (*freeProc)(void*) /* Function used to reclaim memory */
  97317. ){
  97318. yyParser *pParser = (yyParser*)p;
  97319. /* In SQLite, we never try to destroy a parser that was not successfully
  97320. ** created in the first place. */
  97321. if( NEVER(pParser==0) ) return;
  97322. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  97323. #if YYSTACKDEPTH<=0
  97324. free(pParser->yystack);
  97325. #endif
  97326. (*freeProc)((void*)pParser);
  97327. }
  97328. /*
  97329. ** Return the peak depth of the stack for a parser.
  97330. */
  97331. #ifdef YYTRACKMAXSTACKDEPTH
  97332. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  97333. yyParser *pParser = (yyParser*)p;
  97334. return pParser->yyidxMax;
  97335. }
  97336. #endif
  97337. /*
  97338. ** Find the appropriate action for a parser given the terminal
  97339. ** look-ahead token iLookAhead.
  97340. **
  97341. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  97342. ** independent of the look-ahead. If it is, return the action, otherwise
  97343. ** return YY_NO_ACTION.
  97344. */
  97345. static int yy_find_shift_action(
  97346. yyParser *pParser, /* The parser */
  97347. YYCODETYPE iLookAhead /* The look-ahead token */
  97348. ){
  97349. int i;
  97350. int stateno = pParser->yystack[pParser->yyidx].stateno;
  97351. if( stateno>YY_SHIFT_COUNT
  97352. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  97353. return yy_default[stateno];
  97354. }
  97355. assert( iLookAhead!=YYNOCODE );
  97356. i += iLookAhead;
  97357. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  97358. if( iLookAhead>0 ){
  97359. #ifdef YYFALLBACK
  97360. YYCODETYPE iFallback; /* Fallback token */
  97361. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  97362. && (iFallback = yyFallback[iLookAhead])!=0 ){
  97363. #ifndef NDEBUG
  97364. if( yyTraceFILE ){
  97365. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  97366. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  97367. }
  97368. #endif
  97369. return yy_find_shift_action(pParser, iFallback);
  97370. }
  97371. #endif
  97372. #ifdef YYWILDCARD
  97373. {
  97374. int j = i - iLookAhead + YYWILDCARD;
  97375. if(
  97376. #if YY_SHIFT_MIN+YYWILDCARD<0
  97377. j>=0 &&
  97378. #endif
  97379. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  97380. j<YY_ACTTAB_COUNT &&
  97381. #endif
  97382. yy_lookahead[j]==YYWILDCARD
  97383. ){
  97384. #ifndef NDEBUG
  97385. if( yyTraceFILE ){
  97386. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  97387. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  97388. }
  97389. #endif /* NDEBUG */
  97390. return yy_action[j];
  97391. }
  97392. }
  97393. #endif /* YYWILDCARD */
  97394. }
  97395. return yy_default[stateno];
  97396. }else{
  97397. return yy_action[i];
  97398. }
  97399. }
  97400. /*
  97401. ** Find the appropriate action for a parser given the non-terminal
  97402. ** look-ahead token iLookAhead.
  97403. **
  97404. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  97405. ** independent of the look-ahead. If it is, return the action, otherwise
  97406. ** return YY_NO_ACTION.
  97407. */
  97408. static int yy_find_reduce_action(
  97409. int stateno, /* Current state number */
  97410. YYCODETYPE iLookAhead /* The look-ahead token */
  97411. ){
  97412. int i;
  97413. #ifdef YYERRORSYMBOL
  97414. if( stateno>YY_REDUCE_COUNT ){
  97415. return yy_default[stateno];
  97416. }
  97417. #else
  97418. assert( stateno<=YY_REDUCE_COUNT );
  97419. #endif
  97420. i = yy_reduce_ofst[stateno];
  97421. assert( i!=YY_REDUCE_USE_DFLT );
  97422. assert( iLookAhead!=YYNOCODE );
  97423. i += iLookAhead;
  97424. #ifdef YYERRORSYMBOL
  97425. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  97426. return yy_default[stateno];
  97427. }
  97428. #else
  97429. assert( i>=0 && i<YY_ACTTAB_COUNT );
  97430. assert( yy_lookahead[i]==iLookAhead );
  97431. #endif
  97432. return yy_action[i];
  97433. }
  97434. /*
  97435. ** The following routine is called if the stack overflows.
  97436. */
  97437. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  97438. sqlite3ParserARG_FETCH;
  97439. yypParser->yyidx--;
  97440. #ifndef NDEBUG
  97441. if( yyTraceFILE ){
  97442. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  97443. }
  97444. #endif
  97445. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  97446. /* Here code is inserted which will execute if the parser
  97447. ** stack every overflows */
  97448. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  97449. sqlite3ErrorMsg(pParse, "parser stack overflow");
  97450. pParse->parseError = 1;
  97451. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  97452. }
  97453. /*
  97454. ** Perform a shift action.
  97455. */
  97456. static void yy_shift(
  97457. yyParser *yypParser, /* The parser to be shifted */
  97458. int yyNewState, /* The new state to shift in */
  97459. int yyMajor, /* The major token to shift in */
  97460. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  97461. ){
  97462. yyStackEntry *yytos;
  97463. yypParser->yyidx++;
  97464. #ifdef YYTRACKMAXSTACKDEPTH
  97465. if( yypParser->yyidx>yypParser->yyidxMax ){
  97466. yypParser->yyidxMax = yypParser->yyidx;
  97467. }
  97468. #endif
  97469. #if YYSTACKDEPTH>0
  97470. if( yypParser->yyidx>=YYSTACKDEPTH ){
  97471. yyStackOverflow(yypParser, yypMinor);
  97472. return;
  97473. }
  97474. #else
  97475. if( yypParser->yyidx>=yypParser->yystksz ){
  97476. yyGrowStack(yypParser);
  97477. if( yypParser->yyidx>=yypParser->yystksz ){
  97478. yyStackOverflow(yypParser, yypMinor);
  97479. return;
  97480. }
  97481. }
  97482. #endif
  97483. yytos = &yypParser->yystack[yypParser->yyidx];
  97484. yytos->stateno = (YYACTIONTYPE)yyNewState;
  97485. yytos->major = (YYCODETYPE)yyMajor;
  97486. yytos->minor = *yypMinor;
  97487. #ifndef NDEBUG
  97488. if( yyTraceFILE && yypParser->yyidx>0 ){
  97489. int i;
  97490. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  97491. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  97492. for(i=1; i<=yypParser->yyidx; i++)
  97493. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  97494. fprintf(yyTraceFILE,"\n");
  97495. }
  97496. #endif
  97497. }
  97498. /* The following table contains information about every rule that
  97499. ** is used during the reduce.
  97500. */
  97501. static const struct {
  97502. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  97503. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  97504. } yyRuleInfo[] = {
  97505. { 142, 1 },
  97506. { 143, 2 },
  97507. { 143, 1 },
  97508. { 144, 1 },
  97509. { 144, 3 },
  97510. { 145, 0 },
  97511. { 145, 1 },
  97512. { 145, 3 },
  97513. { 146, 1 },
  97514. { 147, 3 },
  97515. { 149, 0 },
  97516. { 149, 1 },
  97517. { 149, 2 },
  97518. { 148, 0 },
  97519. { 148, 1 },
  97520. { 148, 1 },
  97521. { 148, 1 },
  97522. { 147, 2 },
  97523. { 147, 2 },
  97524. { 147, 2 },
  97525. { 151, 1 },
  97526. { 151, 0 },
  97527. { 147, 2 },
  97528. { 147, 3 },
  97529. { 147, 5 },
  97530. { 147, 2 },
  97531. { 152, 6 },
  97532. { 154, 1 },
  97533. { 156, 0 },
  97534. { 156, 3 },
  97535. { 155, 1 },
  97536. { 155, 0 },
  97537. { 153, 4 },
  97538. { 153, 2 },
  97539. { 158, 3 },
  97540. { 158, 1 },
  97541. { 161, 3 },
  97542. { 162, 1 },
  97543. { 165, 1 },
  97544. { 165, 1 },
  97545. { 166, 1 },
  97546. { 150, 1 },
  97547. { 150, 1 },
  97548. { 150, 1 },
  97549. { 163, 0 },
  97550. { 163, 1 },
  97551. { 167, 1 },
  97552. { 167, 4 },
  97553. { 167, 6 },
  97554. { 168, 1 },
  97555. { 168, 2 },
  97556. { 169, 1 },
  97557. { 169, 1 },
  97558. { 164, 2 },
  97559. { 164, 0 },
  97560. { 172, 3 },
  97561. { 172, 1 },
  97562. { 173, 2 },
  97563. { 173, 4 },
  97564. { 173, 3 },
  97565. { 173, 3 },
  97566. { 173, 2 },
  97567. { 173, 2 },
  97568. { 173, 3 },
  97569. { 173, 5 },
  97570. { 173, 2 },
  97571. { 173, 4 },
  97572. { 173, 4 },
  97573. { 173, 1 },
  97574. { 173, 2 },
  97575. { 178, 0 },
  97576. { 178, 1 },
  97577. { 180, 0 },
  97578. { 180, 2 },
  97579. { 182, 2 },
  97580. { 182, 3 },
  97581. { 182, 3 },
  97582. { 182, 3 },
  97583. { 183, 2 },
  97584. { 183, 2 },
  97585. { 183, 1 },
  97586. { 183, 1 },
  97587. { 183, 2 },
  97588. { 181, 3 },
  97589. { 181, 2 },
  97590. { 184, 0 },
  97591. { 184, 2 },
  97592. { 184, 2 },
  97593. { 159, 0 },
  97594. { 159, 2 },
  97595. { 185, 3 },
  97596. { 185, 2 },
  97597. { 185, 1 },
  97598. { 186, 2 },
  97599. { 186, 7 },
  97600. { 186, 5 },
  97601. { 186, 5 },
  97602. { 186, 10 },
  97603. { 188, 0 },
  97604. { 188, 1 },
  97605. { 176, 0 },
  97606. { 176, 3 },
  97607. { 189, 0 },
  97608. { 189, 2 },
  97609. { 190, 1 },
  97610. { 190, 1 },
  97611. { 190, 1 },
  97612. { 147, 4 },
  97613. { 192, 2 },
  97614. { 192, 0 },
  97615. { 147, 8 },
  97616. { 147, 4 },
  97617. { 147, 1 },
  97618. { 160, 1 },
  97619. { 160, 3 },
  97620. { 195, 1 },
  97621. { 195, 2 },
  97622. { 195, 1 },
  97623. { 194, 9 },
  97624. { 196, 1 },
  97625. { 196, 1 },
  97626. { 196, 0 },
  97627. { 204, 2 },
  97628. { 204, 0 },
  97629. { 197, 3 },
  97630. { 197, 2 },
  97631. { 197, 4 },
  97632. { 205, 2 },
  97633. { 205, 1 },
  97634. { 205, 0 },
  97635. { 198, 0 },
  97636. { 198, 2 },
  97637. { 207, 2 },
  97638. { 207, 0 },
  97639. { 206, 7 },
  97640. { 206, 7 },
  97641. { 206, 7 },
  97642. { 157, 0 },
  97643. { 157, 2 },
  97644. { 193, 2 },
  97645. { 208, 1 },
  97646. { 208, 2 },
  97647. { 208, 3 },
  97648. { 208, 4 },
  97649. { 210, 2 },
  97650. { 210, 0 },
  97651. { 209, 0 },
  97652. { 209, 3 },
  97653. { 209, 2 },
  97654. { 211, 4 },
  97655. { 211, 0 },
  97656. { 202, 0 },
  97657. { 202, 3 },
  97658. { 214, 4 },
  97659. { 214, 2 },
  97660. { 215, 1 },
  97661. { 177, 1 },
  97662. { 177, 1 },
  97663. { 177, 0 },
  97664. { 200, 0 },
  97665. { 200, 3 },
  97666. { 201, 0 },
  97667. { 201, 2 },
  97668. { 203, 0 },
  97669. { 203, 2 },
  97670. { 203, 4 },
  97671. { 203, 4 },
  97672. { 147, 5 },
  97673. { 199, 0 },
  97674. { 199, 2 },
  97675. { 147, 7 },
  97676. { 217, 5 },
  97677. { 217, 3 },
  97678. { 147, 8 },
  97679. { 147, 5 },
  97680. { 147, 6 },
  97681. { 218, 2 },
  97682. { 218, 1 },
  97683. { 220, 3 },
  97684. { 220, 1 },
  97685. { 219, 0 },
  97686. { 219, 3 },
  97687. { 213, 3 },
  97688. { 213, 1 },
  97689. { 175, 1 },
  97690. { 175, 3 },
  97691. { 174, 1 },
  97692. { 175, 1 },
  97693. { 175, 1 },
  97694. { 175, 3 },
  97695. { 175, 5 },
  97696. { 174, 1 },
  97697. { 174, 1 },
  97698. { 175, 1 },
  97699. { 175, 1 },
  97700. { 175, 3 },
  97701. { 175, 6 },
  97702. { 175, 5 },
  97703. { 175, 4 },
  97704. { 174, 1 },
  97705. { 175, 3 },
  97706. { 175, 3 },
  97707. { 175, 3 },
  97708. { 175, 3 },
  97709. { 175, 3 },
  97710. { 175, 3 },
  97711. { 175, 3 },
  97712. { 175, 3 },
  97713. { 222, 1 },
  97714. { 222, 2 },
  97715. { 222, 1 },
  97716. { 222, 2 },
  97717. { 175, 3 },
  97718. { 175, 5 },
  97719. { 175, 2 },
  97720. { 175, 3 },
  97721. { 175, 3 },
  97722. { 175, 4 },
  97723. { 175, 2 },
  97724. { 175, 2 },
  97725. { 175, 2 },
  97726. { 175, 2 },
  97727. { 223, 1 },
  97728. { 223, 2 },
  97729. { 175, 5 },
  97730. { 224, 1 },
  97731. { 224, 2 },
  97732. { 175, 5 },
  97733. { 175, 3 },
  97734. { 175, 5 },
  97735. { 175, 4 },
  97736. { 175, 4 },
  97737. { 175, 5 },
  97738. { 226, 5 },
  97739. { 226, 4 },
  97740. { 227, 2 },
  97741. { 227, 0 },
  97742. { 225, 1 },
  97743. { 225, 0 },
  97744. { 221, 1 },
  97745. { 221, 0 },
  97746. { 216, 3 },
  97747. { 216, 1 },
  97748. { 147, 11 },
  97749. { 228, 1 },
  97750. { 228, 0 },
  97751. { 179, 0 },
  97752. { 179, 3 },
  97753. { 187, 5 },
  97754. { 187, 3 },
  97755. { 229, 0 },
  97756. { 229, 2 },
  97757. { 147, 4 },
  97758. { 147, 1 },
  97759. { 147, 2 },
  97760. { 147, 3 },
  97761. { 147, 5 },
  97762. { 147, 6 },
  97763. { 147, 5 },
  97764. { 147, 6 },
  97765. { 230, 1 },
  97766. { 230, 1 },
  97767. { 230, 1 },
  97768. { 230, 1 },
  97769. { 230, 1 },
  97770. { 170, 2 },
  97771. { 171, 2 },
  97772. { 232, 1 },
  97773. { 231, 1 },
  97774. { 231, 0 },
  97775. { 147, 5 },
  97776. { 233, 11 },
  97777. { 235, 1 },
  97778. { 235, 1 },
  97779. { 235, 2 },
  97780. { 235, 0 },
  97781. { 236, 1 },
  97782. { 236, 1 },
  97783. { 236, 3 },
  97784. { 237, 0 },
  97785. { 237, 3 },
  97786. { 238, 0 },
  97787. { 238, 2 },
  97788. { 234, 3 },
  97789. { 234, 2 },
  97790. { 240, 1 },
  97791. { 240, 3 },
  97792. { 241, 0 },
  97793. { 241, 3 },
  97794. { 241, 2 },
  97795. { 239, 7 },
  97796. { 239, 8 },
  97797. { 239, 5 },
  97798. { 239, 5 },
  97799. { 239, 1 },
  97800. { 175, 4 },
  97801. { 175, 6 },
  97802. { 191, 1 },
  97803. { 191, 1 },
  97804. { 191, 1 },
  97805. { 147, 4 },
  97806. { 147, 6 },
  97807. { 147, 3 },
  97808. { 243, 0 },
  97809. { 243, 2 },
  97810. { 242, 1 },
  97811. { 242, 0 },
  97812. { 147, 1 },
  97813. { 147, 3 },
  97814. { 147, 1 },
  97815. { 147, 3 },
  97816. { 147, 6 },
  97817. { 147, 6 },
  97818. { 244, 1 },
  97819. { 245, 0 },
  97820. { 245, 1 },
  97821. { 147, 1 },
  97822. { 147, 4 },
  97823. { 246, 7 },
  97824. { 247, 1 },
  97825. { 247, 3 },
  97826. { 248, 0 },
  97827. { 248, 2 },
  97828. { 249, 1 },
  97829. { 249, 3 },
  97830. { 250, 1 },
  97831. { 251, 0 },
  97832. { 251, 4 },
  97833. { 251, 2 },
  97834. };
  97835. static void yy_accept(yyParser*); /* Forward Declaration */
  97836. /*
  97837. ** Perform a reduce action and the shift that must immediately
  97838. ** follow the reduce.
  97839. */
  97840. static void yy_reduce(
  97841. yyParser *yypParser, /* The parser */
  97842. int yyruleno /* Number of the rule by which to reduce */
  97843. ){
  97844. int yygoto; /* The next state */
  97845. int yyact; /* The next action */
  97846. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  97847. yyStackEntry *yymsp; /* The top of the parser's stack */
  97848. int yysize; /* Amount to pop the stack */
  97849. sqlite3ParserARG_FETCH;
  97850. yymsp = &yypParser->yystack[yypParser->yyidx];
  97851. #ifndef NDEBUG
  97852. if( yyTraceFILE && yyruleno>=0
  97853. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  97854. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  97855. yyRuleName[yyruleno]);
  97856. }
  97857. #endif /* NDEBUG */
  97858. /* Silence complaints from purify about yygotominor being uninitialized
  97859. ** in some cases when it is copied into the stack after the following
  97860. ** switch. yygotominor is uninitialized when a rule reduces that does
  97861. ** not set the value of its left-hand side nonterminal. Leaving the
  97862. ** value of the nonterminal uninitialized is utterly harmless as long
  97863. ** as the value is never used. So really the only thing this code
  97864. ** accomplishes is to quieten purify.
  97865. **
  97866. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  97867. ** without this code, their parser segfaults. I'm not sure what there
  97868. ** parser is doing to make this happen. This is the second bug report
  97869. ** from wireshark this week. Clearly they are stressing Lemon in ways
  97870. ** that it has not been previously stressed... (SQLite ticket #2172)
  97871. */
  97872. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  97873. yygotominor = yyzerominor;
  97874. switch( yyruleno ){
  97875. /* Beginning here are the reduction cases. A typical example
  97876. ** follows:
  97877. ** case 0:
  97878. ** #line <lineno> <grammarfile>
  97879. ** { ... } // User supplied code
  97880. ** #line <lineno> <thisfile>
  97881. ** break;
  97882. */
  97883. case 5: /* explain ::= */
  97884. { sqlite3BeginParse(pParse, 0); }
  97885. break;
  97886. case 6: /* explain ::= EXPLAIN */
  97887. { sqlite3BeginParse(pParse, 1); }
  97888. break;
  97889. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  97890. { sqlite3BeginParse(pParse, 2); }
  97891. break;
  97892. case 8: /* cmdx ::= cmd */
  97893. { sqlite3FinishCoding(pParse); }
  97894. break;
  97895. case 9: /* cmd ::= BEGIN transtype trans_opt */
  97896. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
  97897. break;
  97898. case 13: /* transtype ::= */
  97899. {yygotominor.yy4 = TK_DEFERRED;}
  97900. break;
  97901. case 14: /* transtype ::= DEFERRED */
  97902. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  97903. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  97904. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  97905. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  97906. {yygotominor.yy4 = yymsp[0].major;}
  97907. break;
  97908. case 17: /* cmd ::= COMMIT trans_opt */
  97909. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  97910. {sqlite3CommitTransaction(pParse);}
  97911. break;
  97912. case 19: /* cmd ::= ROLLBACK trans_opt */
  97913. {sqlite3RollbackTransaction(pParse);}
  97914. break;
  97915. case 22: /* cmd ::= SAVEPOINT nm */
  97916. {
  97917. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  97918. }
  97919. break;
  97920. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  97921. {
  97922. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  97923. }
  97924. break;
  97925. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  97926. {
  97927. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  97928. }
  97929. break;
  97930. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  97931. {
  97932. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
  97933. }
  97934. break;
  97935. case 27: /* createkw ::= CREATE */
  97936. {
  97937. pParse->db->lookaside.bEnabled = 0;
  97938. yygotominor.yy0 = yymsp[0].minor.yy0;
  97939. }
  97940. break;
  97941. case 28: /* ifnotexists ::= */
  97942. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  97943. case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
  97944. case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
  97945. case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
  97946. case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
  97947. case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
  97948. case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
  97949. case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
  97950. case 121: /* distinct ::= */ yytestcase(yyruleno==121);
  97951. case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
  97952. case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
  97953. {yygotominor.yy4 = 0;}
  97954. break;
  97955. case 29: /* ifnotexists ::= IF NOT EXISTS */
  97956. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  97957. case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
  97958. case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
  97959. case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
  97960. case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
  97961. case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
  97962. case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
  97963. {yygotominor.yy4 = 1;}
  97964. break;
  97965. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  97966. {
  97967. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  97968. }
  97969. break;
  97970. case 33: /* create_table_args ::= AS select */
  97971. {
  97972. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
  97973. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
  97974. }
  97975. break;
  97976. case 36: /* column ::= columnid type carglist */
  97977. {
  97978. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  97979. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  97980. }
  97981. break;
  97982. case 37: /* columnid ::= nm */
  97983. {
  97984. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  97985. yygotominor.yy0 = yymsp[0].minor.yy0;
  97986. }
  97987. break;
  97988. case 38: /* id ::= ID */
  97989. case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
  97990. case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
  97991. case 41: /* nm ::= id */ yytestcase(yyruleno==41);
  97992. case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
  97993. case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
  97994. case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
  97995. case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
  97996. case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
  97997. case 128: /* as ::= ids */ yytestcase(yyruleno==128);
  97998. case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
  97999. case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
  98000. case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
  98001. case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
  98002. case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
  98003. case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
  98004. case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
  98005. case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
  98006. case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
  98007. case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
  98008. case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
  98009. case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
  98010. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  98011. break;
  98012. case 45: /* type ::= typetoken */
  98013. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  98014. break;
  98015. case 47: /* typetoken ::= typename LP signed RP */
  98016. {
  98017. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  98018. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  98019. }
  98020. break;
  98021. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  98022. {
  98023. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  98024. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  98025. }
  98026. break;
  98027. case 50: /* typename ::= typename ids */
  98028. {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);}
  98029. break;
  98030. case 57: /* ccons ::= DEFAULT term */
  98031. case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
  98032. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
  98033. break;
  98034. case 58: /* ccons ::= DEFAULT LP expr RP */
  98035. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
  98036. break;
  98037. case 60: /* ccons ::= DEFAULT MINUS term */
  98038. {
  98039. ExprSpan v;
  98040. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
  98041. v.zStart = yymsp[-1].minor.yy0.z;
  98042. v.zEnd = yymsp[0].minor.yy118.zEnd;
  98043. sqlite3AddDefaultValue(pParse,&v);
  98044. }
  98045. break;
  98046. case 61: /* ccons ::= DEFAULT id */
  98047. {
  98048. ExprSpan v;
  98049. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  98050. sqlite3AddDefaultValue(pParse,&v);
  98051. }
  98052. break;
  98053. case 63: /* ccons ::= NOT NULL onconf */
  98054. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
  98055. break;
  98056. case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  98057. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
  98058. break;
  98059. case 65: /* ccons ::= UNIQUE onconf */
  98060. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
  98061. break;
  98062. case 66: /* ccons ::= CHECK LP expr RP */
  98063. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
  98064. break;
  98065. case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  98066. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
  98067. break;
  98068. case 68: /* ccons ::= defer_subclause */
  98069. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
  98070. break;
  98071. case 69: /* ccons ::= COLLATE ids */
  98072. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  98073. break;
  98074. case 72: /* refargs ::= */
  98075. { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
  98076. break;
  98077. case 73: /* refargs ::= refargs refarg */
  98078. { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
  98079. break;
  98080. case 74: /* refarg ::= MATCH nm */
  98081. case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
  98082. { yygotominor.yy215.value = 0; yygotominor.yy215.mask = 0x000000; }
  98083. break;
  98084. case 76: /* refarg ::= ON DELETE refact */
  98085. { yygotominor.yy215.value = yymsp[0].minor.yy4; yygotominor.yy215.mask = 0x0000ff; }
  98086. break;
  98087. case 77: /* refarg ::= ON UPDATE refact */
  98088. { yygotominor.yy215.value = yymsp[0].minor.yy4<<8; yygotominor.yy215.mask = 0x00ff00; }
  98089. break;
  98090. case 78: /* refact ::= SET NULL */
  98091. { yygotominor.yy4 = OE_SetNull; /* EV: R-33326-45252 */}
  98092. break;
  98093. case 79: /* refact ::= SET DEFAULT */
  98094. { yygotominor.yy4 = OE_SetDflt; /* EV: R-33326-45252 */}
  98095. break;
  98096. case 80: /* refact ::= CASCADE */
  98097. { yygotominor.yy4 = OE_Cascade; /* EV: R-33326-45252 */}
  98098. break;
  98099. case 81: /* refact ::= RESTRICT */
  98100. { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
  98101. break;
  98102. case 82: /* refact ::= NO ACTION */
  98103. { yygotominor.yy4 = OE_None; /* EV: R-33326-45252 */}
  98104. break;
  98105. case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  98106. case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
  98107. case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
  98108. case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
  98109. {yygotominor.yy4 = yymsp[0].minor.yy4;}
  98110. break;
  98111. case 88: /* conslist_opt ::= */
  98112. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  98113. break;
  98114. case 89: /* conslist_opt ::= COMMA conslist */
  98115. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  98116. break;
  98117. case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  98118. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
  98119. break;
  98120. case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
  98121. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
  98122. break;
  98123. case 96: /* tcons ::= CHECK LP expr RP onconf */
  98124. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
  98125. break;
  98126. case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  98127. {
  98128. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
  98129. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
  98130. }
  98131. break;
  98132. case 100: /* onconf ::= */
  98133. {yygotominor.yy4 = OE_Default;}
  98134. break;
  98135. case 102: /* orconf ::= */
  98136. {yygotominor.yy210 = OE_Default;}
  98137. break;
  98138. case 103: /* orconf ::= OR resolvetype */
  98139. {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
  98140. break;
  98141. case 105: /* resolvetype ::= IGNORE */
  98142. {yygotominor.yy4 = OE_Ignore;}
  98143. break;
  98144. case 106: /* resolvetype ::= REPLACE */
  98145. {yygotominor.yy4 = OE_Replace;}
  98146. break;
  98147. case 107: /* cmd ::= DROP TABLE ifexists fullname */
  98148. {
  98149. sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
  98150. }
  98151. break;
  98152. case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  98153. {
  98154. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
  98155. }
  98156. break;
  98157. case 111: /* cmd ::= DROP VIEW ifexists fullname */
  98158. {
  98159. sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
  98160. }
  98161. break;
  98162. case 112: /* cmd ::= select */
  98163. {
  98164. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  98165. sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
  98166. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
  98167. }
  98168. break;
  98169. case 113: /* select ::= oneselect */
  98170. {yygotominor.yy387 = yymsp[0].minor.yy387;}
  98171. break;
  98172. case 114: /* select ::= select multiselect_op oneselect */
  98173. {
  98174. if( yymsp[0].minor.yy387 ){
  98175. yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
  98176. yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
  98177. }else{
  98178. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
  98179. }
  98180. yygotominor.yy387 = yymsp[0].minor.yy387;
  98181. }
  98182. break;
  98183. case 116: /* multiselect_op ::= UNION ALL */
  98184. {yygotominor.yy4 = TK_ALL;}
  98185. break;
  98186. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  98187. {
  98188. yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
  98189. }
  98190. break;
  98191. case 122: /* sclp ::= selcollist COMMA */
  98192. case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
  98193. {yygotominor.yy322 = yymsp[-1].minor.yy322;}
  98194. break;
  98195. case 123: /* sclp ::= */
  98196. case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
  98197. case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
  98198. case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
  98199. case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
  98200. {yygotominor.yy322 = 0;}
  98201. break;
  98202. case 124: /* selcollist ::= sclp expr as */
  98203. {
  98204. yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
  98205. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
  98206. sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
  98207. }
  98208. break;
  98209. case 125: /* selcollist ::= sclp STAR */
  98210. {
  98211. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  98212. yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
  98213. }
  98214. break;
  98215. case 126: /* selcollist ::= sclp nm DOT STAR */
  98216. {
  98217. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  98218. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98219. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  98220. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
  98221. }
  98222. break;
  98223. case 129: /* as ::= */
  98224. {yygotominor.yy0.n = 0;}
  98225. break;
  98226. case 130: /* from ::= */
  98227. {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
  98228. break;
  98229. case 131: /* from ::= FROM seltablist */
  98230. {
  98231. yygotominor.yy259 = yymsp[0].minor.yy259;
  98232. sqlite3SrcListShiftJoinType(yygotominor.yy259);
  98233. }
  98234. break;
  98235. case 132: /* stl_prefix ::= seltablist joinop */
  98236. {
  98237. yygotominor.yy259 = yymsp[-1].minor.yy259;
  98238. if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
  98239. }
  98240. break;
  98241. case 133: /* stl_prefix ::= */
  98242. {yygotominor.yy259 = 0;}
  98243. break;
  98244. case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  98245. {
  98246. yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  98247. sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
  98248. }
  98249. break;
  98250. case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  98251. {
  98252. yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  98253. }
  98254. break;
  98255. case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  98256. {
  98257. if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
  98258. yygotominor.yy259 = yymsp[-4].minor.yy259;
  98259. }else{
  98260. Select *pSubquery;
  98261. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
  98262. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
  98263. yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  98264. }
  98265. }
  98266. break;
  98267. case 137: /* dbnm ::= */
  98268. case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
  98269. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  98270. break;
  98271. case 139: /* fullname ::= nm dbnm */
  98272. {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  98273. break;
  98274. case 140: /* joinop ::= COMMA|JOIN */
  98275. { yygotominor.yy4 = JT_INNER; }
  98276. break;
  98277. case 141: /* joinop ::= JOIN_KW JOIN */
  98278. { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  98279. break;
  98280. case 142: /* joinop ::= JOIN_KW nm JOIN */
  98281. { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  98282. break;
  98283. case 143: /* joinop ::= JOIN_KW nm nm JOIN */
  98284. { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  98285. break;
  98286. case 144: /* on_opt ::= ON expr */
  98287. case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
  98288. case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
  98289. case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
  98290. case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
  98291. case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
  98292. {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
  98293. break;
  98294. case 145: /* on_opt ::= */
  98295. case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
  98296. case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
  98297. case 236: /* case_else ::= */ yytestcase(yyruleno==236);
  98298. case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
  98299. {yygotominor.yy314 = 0;}
  98300. break;
  98301. case 148: /* indexed_opt ::= NOT INDEXED */
  98302. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  98303. break;
  98304. case 149: /* using_opt ::= USING LP inscollist RP */
  98305. case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
  98306. {yygotominor.yy384 = yymsp[-1].minor.yy384;}
  98307. break;
  98308. case 150: /* using_opt ::= */
  98309. case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
  98310. {yygotominor.yy384 = 0;}
  98311. break;
  98312. case 152: /* orderby_opt ::= ORDER BY sortlist */
  98313. case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
  98314. case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
  98315. {yygotominor.yy322 = yymsp[0].minor.yy322;}
  98316. break;
  98317. case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
  98318. {
  98319. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
  98320. if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
  98321. }
  98322. break;
  98323. case 154: /* sortlist ::= sortitem sortorder */
  98324. {
  98325. yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
  98326. if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
  98327. }
  98328. break;
  98329. case 156: /* sortorder ::= ASC */
  98330. case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
  98331. {yygotominor.yy4 = SQLITE_SO_ASC;}
  98332. break;
  98333. case 157: /* sortorder ::= DESC */
  98334. {yygotominor.yy4 = SQLITE_SO_DESC;}
  98335. break;
  98336. case 163: /* limit_opt ::= */
  98337. {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
  98338. break;
  98339. case 164: /* limit_opt ::= LIMIT expr */
  98340. {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
  98341. break;
  98342. case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
  98343. {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
  98344. break;
  98345. case 166: /* limit_opt ::= LIMIT expr COMMA expr */
  98346. {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
  98347. break;
  98348. case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  98349. {
  98350. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
  98351. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
  98352. }
  98353. break;
  98354. case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  98355. {
  98356. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
  98357. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
  98358. sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
  98359. }
  98360. break;
  98361. case 171: /* setlist ::= setlist COMMA nm EQ expr */
  98362. {
  98363. yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
  98364. sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
  98365. }
  98366. break;
  98367. case 172: /* setlist ::= nm EQ expr */
  98368. {
  98369. yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
  98370. sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
  98371. }
  98372. break;
  98373. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
  98374. {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
  98375. break;
  98376. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  98377. {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
  98378. break;
  98379. case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  98380. {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
  98381. break;
  98382. case 176: /* insert_cmd ::= INSERT orconf */
  98383. {yygotominor.yy210 = yymsp[0].minor.yy210;}
  98384. break;
  98385. case 177: /* insert_cmd ::= REPLACE */
  98386. {yygotominor.yy210 = OE_Replace;}
  98387. break;
  98388. case 178: /* itemlist ::= itemlist COMMA expr */
  98389. case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
  98390. {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
  98391. break;
  98392. case 179: /* itemlist ::= expr */
  98393. case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
  98394. {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
  98395. break;
  98396. case 182: /* inscollist ::= inscollist COMMA nm */
  98397. {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
  98398. break;
  98399. case 183: /* inscollist ::= nm */
  98400. {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  98401. break;
  98402. case 184: /* expr ::= term */
  98403. {yygotominor.yy118 = yymsp[0].minor.yy118;}
  98404. break;
  98405. case 185: /* expr ::= LP expr RP */
  98406. {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  98407. break;
  98408. case 186: /* term ::= NULL */
  98409. case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
  98410. case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
  98411. {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  98412. break;
  98413. case 187: /* expr ::= id */
  98414. case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
  98415. {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
  98416. break;
  98417. case 189: /* expr ::= nm DOT nm */
  98418. {
  98419. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98420. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  98421. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  98422. spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  98423. }
  98424. break;
  98425. case 190: /* expr ::= nm DOT nm DOT nm */
  98426. {
  98427. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  98428. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  98429. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  98430. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  98431. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  98432. spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  98433. }
  98434. break;
  98435. case 193: /* expr ::= REGISTER */
  98436. {
  98437. /* When doing a nested parse, one can include terms in an expression
  98438. ** that look like this: #1 #2 ... These terms refer to registers
  98439. ** in the virtual machine. #N is the N-th register. */
  98440. if( pParse->nested==0 ){
  98441. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  98442. yygotominor.yy118.pExpr = 0;
  98443. }else{
  98444. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  98445. if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
  98446. }
  98447. spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98448. }
  98449. break;
  98450. case 194: /* expr ::= VARIABLE */
  98451. {
  98452. spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  98453. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
  98454. spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98455. }
  98456. break;
  98457. case 195: /* expr ::= expr COLLATE ids */
  98458. {
  98459. yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
  98460. yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
  98461. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98462. }
  98463. break;
  98464. case 196: /* expr ::= CAST LP expr AS typetoken RP */
  98465. {
  98466. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
  98467. spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  98468. }
  98469. break;
  98470. case 197: /* expr ::= ID LP distinct exprlist RP */
  98471. {
  98472. if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  98473. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  98474. }
  98475. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
  98476. spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  98477. if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
  98478. yygotominor.yy118.pExpr->flags |= EP_Distinct;
  98479. }
  98480. }
  98481. break;
  98482. case 198: /* expr ::= ID LP STAR RP */
  98483. {
  98484. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  98485. spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  98486. }
  98487. break;
  98488. case 199: /* term ::= CTIME_KW */
  98489. {
  98490. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  98491. ** treated as functions that return constants */
  98492. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  98493. if( yygotominor.yy118.pExpr ){
  98494. yygotominor.yy118.pExpr->op = TK_CONST_FUNC;
  98495. }
  98496. spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  98497. }
  98498. break;
  98499. case 200: /* expr ::= expr AND expr */
  98500. case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
  98501. case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
  98502. case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
  98503. case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
  98504. case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
  98505. case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
  98506. case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
  98507. {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
  98508. break;
  98509. case 208: /* likeop ::= LIKE_KW */
  98510. case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
  98511. {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
  98512. break;
  98513. case 209: /* likeop ::= NOT LIKE_KW */
  98514. case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
  98515. {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
  98516. break;
  98517. case 212: /* expr ::= expr likeop expr */
  98518. {
  98519. ExprList *pList;
  98520. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
  98521. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
  98522. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
  98523. if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
  98524. yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
  98525. yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
  98526. if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
  98527. }
  98528. break;
  98529. case 213: /* expr ::= expr likeop expr ESCAPE expr */
  98530. {
  98531. ExprList *pList;
  98532. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
  98533. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
  98534. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
  98535. yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
  98536. if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
  98537. yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
  98538. yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
  98539. if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
  98540. }
  98541. break;
  98542. case 214: /* expr ::= expr ISNULL|NOTNULL */
  98543. {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
  98544. break;
  98545. case 215: /* expr ::= expr NOT NULL */
  98546. {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
  98547. break;
  98548. case 216: /* expr ::= expr IS expr */
  98549. {
  98550. spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
  98551. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
  98552. }
  98553. break;
  98554. case 217: /* expr ::= expr IS NOT expr */
  98555. {
  98556. spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
  98557. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
  98558. }
  98559. break;
  98560. case 218: /* expr ::= NOT expr */
  98561. case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
  98562. {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
  98563. break;
  98564. case 220: /* expr ::= MINUS expr */
  98565. {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
  98566. break;
  98567. case 221: /* expr ::= PLUS expr */
  98568. {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
  98569. break;
  98570. case 224: /* expr ::= expr between_op expr AND expr */
  98571. {
  98572. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
  98573. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
  98574. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
  98575. if( yygotominor.yy118.pExpr ){
  98576. yygotominor.yy118.pExpr->x.pList = pList;
  98577. }else{
  98578. sqlite3ExprListDelete(pParse->db, pList);
  98579. }
  98580. if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
  98581. yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
  98582. yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
  98583. }
  98584. break;
  98585. case 227: /* expr ::= expr in_op LP exprlist RP */
  98586. {
  98587. if( yymsp[-1].minor.yy322==0 ){
  98588. /* Expressions of the form
  98589. **
  98590. ** expr1 IN ()
  98591. ** expr1 NOT IN ()
  98592. **
  98593. ** simplify to constants 0 (false) and 1 (true), respectively,
  98594. ** regardless of the value of expr1.
  98595. */
  98596. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
  98597. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
  98598. }else{
  98599. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
  98600. if( yygotominor.yy118.pExpr ){
  98601. yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
  98602. sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
  98603. }else{
  98604. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
  98605. }
  98606. if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
  98607. }
  98608. yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
  98609. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98610. }
  98611. break;
  98612. case 228: /* expr ::= LP select RP */
  98613. {
  98614. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  98615. if( yygotominor.yy118.pExpr ){
  98616. yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
  98617. ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
  98618. sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
  98619. }else{
  98620. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
  98621. }
  98622. yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
  98623. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98624. }
  98625. break;
  98626. case 229: /* expr ::= expr in_op LP select RP */
  98627. {
  98628. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
  98629. if( yygotominor.yy118.pExpr ){
  98630. yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
  98631. ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
  98632. sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
  98633. }else{
  98634. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
  98635. }
  98636. if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
  98637. yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
  98638. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98639. }
  98640. break;
  98641. case 230: /* expr ::= expr in_op nm dbnm */
  98642. {
  98643. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  98644. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
  98645. if( yygotominor.yy118.pExpr ){
  98646. yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  98647. ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
  98648. sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
  98649. }else{
  98650. sqlite3SrcListDelete(pParse->db, pSrc);
  98651. }
  98652. if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
  98653. yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
  98654. yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
  98655. }
  98656. break;
  98657. case 231: /* expr ::= EXISTS LP select RP */
  98658. {
  98659. Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  98660. if( p ){
  98661. p->x.pSelect = yymsp[-1].minor.yy387;
  98662. ExprSetProperty(p, EP_xIsSelect);
  98663. sqlite3ExprSetHeight(pParse, p);
  98664. }else{
  98665. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
  98666. }
  98667. yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
  98668. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98669. }
  98670. break;
  98671. case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
  98672. {
  98673. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
  98674. if( yygotominor.yy118.pExpr ){
  98675. yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
  98676. sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
  98677. }else{
  98678. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
  98679. }
  98680. yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
  98681. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98682. }
  98683. break;
  98684. case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  98685. {
  98686. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
  98687. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
  98688. }
  98689. break;
  98690. case 234: /* case_exprlist ::= WHEN expr THEN expr */
  98691. {
  98692. yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
  98693. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
  98694. }
  98695. break;
  98696. case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
  98697. {
  98698. sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
  98699. sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
  98700. &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
  98701. }
  98702. break;
  98703. case 244: /* uniqueflag ::= UNIQUE */
  98704. case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
  98705. {yygotominor.yy4 = OE_Abort;}
  98706. break;
  98707. case 245: /* uniqueflag ::= */
  98708. {yygotominor.yy4 = OE_None;}
  98709. break;
  98710. case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
  98711. {
  98712. Expr *p = 0;
  98713. if( yymsp[-1].minor.yy0.n>0 ){
  98714. p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
  98715. sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
  98716. }
  98717. yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
  98718. sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
  98719. sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
  98720. if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
  98721. }
  98722. break;
  98723. case 249: /* idxlist ::= nm collate sortorder */
  98724. {
  98725. Expr *p = 0;
  98726. if( yymsp[-1].minor.yy0.n>0 ){
  98727. p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
  98728. sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
  98729. }
  98730. yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
  98731. sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
  98732. sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
  98733. if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
  98734. }
  98735. break;
  98736. case 250: /* collate ::= */
  98737. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  98738. break;
  98739. case 252: /* cmd ::= DROP INDEX ifexists fullname */
  98740. {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
  98741. break;
  98742. case 253: /* cmd ::= VACUUM */
  98743. case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
  98744. {sqlite3Vacuum(pParse);}
  98745. break;
  98746. case 255: /* cmd ::= PRAGMA nm dbnm */
  98747. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  98748. break;
  98749. case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  98750. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  98751. break;
  98752. case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  98753. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  98754. break;
  98755. case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  98756. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  98757. break;
  98758. case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  98759. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  98760. break;
  98761. case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  98762. {
  98763. Token all;
  98764. all.z = yymsp[-3].minor.yy0.z;
  98765. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  98766. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
  98767. }
  98768. break;
  98769. case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  98770. {
  98771. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
  98772. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  98773. }
  98774. break;
  98775. case 272: /* trigger_time ::= BEFORE */
  98776. case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
  98777. { yygotominor.yy4 = TK_BEFORE; }
  98778. break;
  98779. case 273: /* trigger_time ::= AFTER */
  98780. { yygotominor.yy4 = TK_AFTER; }
  98781. break;
  98782. case 274: /* trigger_time ::= INSTEAD OF */
  98783. { yygotominor.yy4 = TK_INSTEAD;}
  98784. break;
  98785. case 276: /* trigger_event ::= DELETE|INSERT */
  98786. case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
  98787. {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
  98788. break;
  98789. case 278: /* trigger_event ::= UPDATE OF inscollist */
  98790. {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
  98791. break;
  98792. case 281: /* when_clause ::= */
  98793. case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
  98794. { yygotominor.yy314 = 0; }
  98795. break;
  98796. case 282: /* when_clause ::= WHEN expr */
  98797. case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
  98798. { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
  98799. break;
  98800. case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  98801. {
  98802. assert( yymsp[-2].minor.yy203!=0 );
  98803. yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
  98804. yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
  98805. yygotominor.yy203 = yymsp[-2].minor.yy203;
  98806. }
  98807. break;
  98808. case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
  98809. {
  98810. assert( yymsp[-1].minor.yy203!=0 );
  98811. yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
  98812. yygotominor.yy203 = yymsp[-1].minor.yy203;
  98813. }
  98814. break;
  98815. case 286: /* trnm ::= nm DOT nm */
  98816. {
  98817. yygotominor.yy0 = yymsp[0].minor.yy0;
  98818. sqlite3ErrorMsg(pParse,
  98819. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  98820. "statements within triggers");
  98821. }
  98822. break;
  98823. case 288: /* tridxby ::= INDEXED BY nm */
  98824. {
  98825. sqlite3ErrorMsg(pParse,
  98826. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  98827. "within triggers");
  98828. }
  98829. break;
  98830. case 289: /* tridxby ::= NOT INDEXED */
  98831. {
  98832. sqlite3ErrorMsg(pParse,
  98833. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  98834. "within triggers");
  98835. }
  98836. break;
  98837. case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  98838. { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
  98839. break;
  98840. case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
  98841. {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
  98842. break;
  98843. case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  98844. {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
  98845. break;
  98846. case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  98847. {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
  98848. break;
  98849. case 294: /* trigger_cmd ::= select */
  98850. {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
  98851. break;
  98852. case 295: /* expr ::= RAISE LP IGNORE RP */
  98853. {
  98854. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  98855. if( yygotominor.yy118.pExpr ){
  98856. yygotominor.yy118.pExpr->affinity = OE_Ignore;
  98857. }
  98858. yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
  98859. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98860. }
  98861. break;
  98862. case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
  98863. {
  98864. yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  98865. if( yygotominor.yy118.pExpr ) {
  98866. yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
  98867. }
  98868. yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
  98869. yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  98870. }
  98871. break;
  98872. case 297: /* raisetype ::= ROLLBACK */
  98873. {yygotominor.yy4 = OE_Rollback;}
  98874. break;
  98875. case 299: /* raisetype ::= FAIL */
  98876. {yygotominor.yy4 = OE_Fail;}
  98877. break;
  98878. case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
  98879. {
  98880. sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
  98881. }
  98882. break;
  98883. case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  98884. {
  98885. sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
  98886. }
  98887. break;
  98888. case 302: /* cmd ::= DETACH database_kw_opt expr */
  98889. {
  98890. sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
  98891. }
  98892. break;
  98893. case 307: /* cmd ::= REINDEX */
  98894. {sqlite3Reindex(pParse, 0, 0);}
  98895. break;
  98896. case 308: /* cmd ::= REINDEX nm dbnm */
  98897. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  98898. break;
  98899. case 309: /* cmd ::= ANALYZE */
  98900. {sqlite3Analyze(pParse, 0, 0);}
  98901. break;
  98902. case 310: /* cmd ::= ANALYZE nm dbnm */
  98903. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  98904. break;
  98905. case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  98906. {
  98907. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
  98908. }
  98909. break;
  98910. case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  98911. {
  98912. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  98913. }
  98914. break;
  98915. case 313: /* add_column_fullname ::= fullname */
  98916. {
  98917. pParse->db->lookaside.bEnabled = 0;
  98918. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
  98919. }
  98920. break;
  98921. case 316: /* cmd ::= create_vtab */
  98922. {sqlite3VtabFinishParse(pParse,0);}
  98923. break;
  98924. case 317: /* cmd ::= create_vtab LP vtabarglist RP */
  98925. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  98926. break;
  98927. case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
  98928. {
  98929. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
  98930. }
  98931. break;
  98932. case 321: /* vtabarg ::= */
  98933. {sqlite3VtabArgInit(pParse);}
  98934. break;
  98935. case 323: /* vtabargtoken ::= ANY */
  98936. case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
  98937. case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
  98938. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  98939. break;
  98940. default:
  98941. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  98942. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  98943. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  98944. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  98945. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  98946. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  98947. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  98948. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  98949. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  98950. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  98951. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  98952. /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
  98953. /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
  98954. /* (44) type ::= */ yytestcase(yyruleno==44);
  98955. /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
  98956. /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
  98957. /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
  98958. /* (54) carglist ::= */ yytestcase(yyruleno==54);
  98959. /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
  98960. /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
  98961. /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
  98962. /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
  98963. /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
  98964. /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
  98965. /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
  98966. /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
  98967. /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
  98968. /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
  98969. /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
  98970. /* (287) tridxby ::= */ yytestcase(yyruleno==287);
  98971. /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
  98972. /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
  98973. /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
  98974. /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
  98975. /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
  98976. /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
  98977. /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
  98978. /* (326) anylist ::= */ yytestcase(yyruleno==326);
  98979. /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
  98980. /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
  98981. break;
  98982. };
  98983. yygoto = yyRuleInfo[yyruleno].lhs;
  98984. yysize = yyRuleInfo[yyruleno].nrhs;
  98985. yypParser->yyidx -= yysize;
  98986. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  98987. if( yyact < YYNSTATE ){
  98988. #ifdef NDEBUG
  98989. /* If we are not debugging and the reduce action popped at least
  98990. ** one element off the stack, then we can push the new element back
  98991. ** onto the stack here, and skip the stack overflow test in yy_shift().
  98992. ** That gives a significant speed improvement. */
  98993. if( yysize ){
  98994. yypParser->yyidx++;
  98995. yymsp -= yysize-1;
  98996. yymsp->stateno = (YYACTIONTYPE)yyact;
  98997. yymsp->major = (YYCODETYPE)yygoto;
  98998. yymsp->minor = yygotominor;
  98999. }else
  99000. #endif
  99001. {
  99002. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  99003. }
  99004. }else{
  99005. assert( yyact == YYNSTATE + YYNRULE + 1 );
  99006. yy_accept(yypParser);
  99007. }
  99008. }
  99009. /*
  99010. ** The following code executes when the parse fails
  99011. */
  99012. #ifndef YYNOERRORRECOVERY
  99013. static void yy_parse_failed(
  99014. yyParser *yypParser /* The parser */
  99015. ){
  99016. sqlite3ParserARG_FETCH;
  99017. #ifndef NDEBUG
  99018. if( yyTraceFILE ){
  99019. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  99020. }
  99021. #endif
  99022. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  99023. /* Here code is inserted which will be executed whenever the
  99024. ** parser fails */
  99025. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99026. }
  99027. #endif /* YYNOERRORRECOVERY */
  99028. /*
  99029. ** The following code executes when a syntax error first occurs.
  99030. */
  99031. static void yy_syntax_error(
  99032. yyParser *yypParser, /* The parser */
  99033. int yymajor, /* The major type of the error token */
  99034. YYMINORTYPE yyminor /* The minor type of the error token */
  99035. ){
  99036. sqlite3ParserARG_FETCH;
  99037. #define TOKEN (yyminor.yy0)
  99038. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  99039. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  99040. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  99041. pParse->parseError = 1;
  99042. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99043. }
  99044. /*
  99045. ** The following is executed when the parser accepts
  99046. */
  99047. static void yy_accept(
  99048. yyParser *yypParser /* The parser */
  99049. ){
  99050. sqlite3ParserARG_FETCH;
  99051. #ifndef NDEBUG
  99052. if( yyTraceFILE ){
  99053. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  99054. }
  99055. #endif
  99056. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  99057. /* Here code is inserted which will be executed whenever the
  99058. ** parser accepts */
  99059. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  99060. }
  99061. /* The main parser program.
  99062. ** The first argument is a pointer to a structure obtained from
  99063. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  99064. ** The second argument is the major token number. The third is
  99065. ** the minor token. The fourth optional argument is whatever the
  99066. ** user wants (and specified in the grammar) and is available for
  99067. ** use by the action routines.
  99068. **
  99069. ** Inputs:
  99070. ** <ul>
  99071. ** <li> A pointer to the parser (an opaque structure.)
  99072. ** <li> The major token number.
  99073. ** <li> The minor token number.
  99074. ** <li> An option argument of a grammar-specified type.
  99075. ** </ul>
  99076. **
  99077. ** Outputs:
  99078. ** None.
  99079. */
  99080. SQLITE_PRIVATE void sqlite3Parser(
  99081. void *yyp, /* The parser */
  99082. int yymajor, /* The major token code number */
  99083. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  99084. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  99085. ){
  99086. YYMINORTYPE yyminorunion;
  99087. int yyact; /* The parser action. */
  99088. int yyendofinput; /* True if we are at the end of input */
  99089. #ifdef YYERRORSYMBOL
  99090. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  99091. #endif
  99092. yyParser *yypParser; /* The parser */
  99093. /* (re)initialize the parser, if necessary */
  99094. yypParser = (yyParser*)yyp;
  99095. if( yypParser->yyidx<0 ){
  99096. #if YYSTACKDEPTH<=0
  99097. if( yypParser->yystksz <=0 ){
  99098. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  99099. yyminorunion = yyzerominor;
  99100. yyStackOverflow(yypParser, &yyminorunion);
  99101. return;
  99102. }
  99103. #endif
  99104. yypParser->yyidx = 0;
  99105. yypParser->yyerrcnt = -1;
  99106. yypParser->yystack[0].stateno = 0;
  99107. yypParser->yystack[0].major = 0;
  99108. }
  99109. yyminorunion.yy0 = yyminor;
  99110. yyendofinput = (yymajor==0);
  99111. sqlite3ParserARG_STORE;
  99112. #ifndef NDEBUG
  99113. if( yyTraceFILE ){
  99114. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  99115. }
  99116. #endif
  99117. do{
  99118. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  99119. if( yyact<YYNSTATE ){
  99120. assert( !yyendofinput ); /* Impossible to shift the $ token */
  99121. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  99122. yypParser->yyerrcnt--;
  99123. yymajor = YYNOCODE;
  99124. }else if( yyact < YYNSTATE + YYNRULE ){
  99125. yy_reduce(yypParser,yyact-YYNSTATE);
  99126. }else{
  99127. assert( yyact == YY_ERROR_ACTION );
  99128. #ifdef YYERRORSYMBOL
  99129. int yymx;
  99130. #endif
  99131. #ifndef NDEBUG
  99132. if( yyTraceFILE ){
  99133. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  99134. }
  99135. #endif
  99136. #ifdef YYERRORSYMBOL
  99137. /* A syntax error has occurred.
  99138. ** The response to an error depends upon whether or not the
  99139. ** grammar defines an error token "ERROR".
  99140. **
  99141. ** This is what we do if the grammar does define ERROR:
  99142. **
  99143. ** * Call the %syntax_error function.
  99144. **
  99145. ** * Begin popping the stack until we enter a state where
  99146. ** it is legal to shift the error symbol, then shift
  99147. ** the error symbol.
  99148. **
  99149. ** * Set the error count to three.
  99150. **
  99151. ** * Begin accepting and shifting new tokens. No new error
  99152. ** processing will occur until three tokens have been
  99153. ** shifted successfully.
  99154. **
  99155. */
  99156. if( yypParser->yyerrcnt<0 ){
  99157. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99158. }
  99159. yymx = yypParser->yystack[yypParser->yyidx].major;
  99160. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  99161. #ifndef NDEBUG
  99162. if( yyTraceFILE ){
  99163. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  99164. yyTracePrompt,yyTokenName[yymajor]);
  99165. }
  99166. #endif
  99167. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  99168. yymajor = YYNOCODE;
  99169. }else{
  99170. while(
  99171. yypParser->yyidx >= 0 &&
  99172. yymx != YYERRORSYMBOL &&
  99173. (yyact = yy_find_reduce_action(
  99174. yypParser->yystack[yypParser->yyidx].stateno,
  99175. YYERRORSYMBOL)) >= YYNSTATE
  99176. ){
  99177. yy_pop_parser_stack(yypParser);
  99178. }
  99179. if( yypParser->yyidx < 0 || yymajor==0 ){
  99180. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99181. yy_parse_failed(yypParser);
  99182. yymajor = YYNOCODE;
  99183. }else if( yymx!=YYERRORSYMBOL ){
  99184. YYMINORTYPE u2;
  99185. u2.YYERRSYMDT = 0;
  99186. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  99187. }
  99188. }
  99189. yypParser->yyerrcnt = 3;
  99190. yyerrorhit = 1;
  99191. #elif defined(YYNOERRORRECOVERY)
  99192. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  99193. ** do any kind of error recovery. Instead, simply invoke the syntax
  99194. ** error routine and continue going as if nothing had happened.
  99195. **
  99196. ** Applications can set this macro (for example inside %include) if
  99197. ** they intend to abandon the parse upon the first syntax error seen.
  99198. */
  99199. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99200. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99201. yymajor = YYNOCODE;
  99202. #else /* YYERRORSYMBOL is not defined */
  99203. /* This is what we do if the grammar does not define ERROR:
  99204. **
  99205. ** * Report an error message, and throw away the input token.
  99206. **
  99207. ** * If the input token is $, then fail the parse.
  99208. **
  99209. ** As before, subsequent error messages are suppressed until
  99210. ** three input tokens have been successfully shifted.
  99211. */
  99212. if( yypParser->yyerrcnt<=0 ){
  99213. yy_syntax_error(yypParser,yymajor,yyminorunion);
  99214. }
  99215. yypParser->yyerrcnt = 3;
  99216. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  99217. if( yyendofinput ){
  99218. yy_parse_failed(yypParser);
  99219. }
  99220. yymajor = YYNOCODE;
  99221. #endif
  99222. }
  99223. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  99224. return;
  99225. }
  99226. /************** End of parse.c ***********************************************/
  99227. /************** Begin file tokenize.c ****************************************/
  99228. /*
  99229. ** 2001 September 15
  99230. **
  99231. ** The author disclaims copyright to this source code. In place of
  99232. ** a legal notice, here is a blessing:
  99233. **
  99234. ** May you do good and not evil.
  99235. ** May you find forgiveness for yourself and forgive others.
  99236. ** May you share freely, never taking more than you give.
  99237. **
  99238. *************************************************************************
  99239. ** An tokenizer for SQL
  99240. **
  99241. ** This file contains C code that splits an SQL input string up into
  99242. ** individual tokens and sends those tokens one-by-one over to the
  99243. ** parser for analysis.
  99244. */
  99245. /*
  99246. ** The charMap() macro maps alphabetic characters into their
  99247. ** lower-case ASCII equivalent. On ASCII machines, this is just
  99248. ** an upper-to-lower case map. On EBCDIC machines we also need
  99249. ** to adjust the encoding. Only alphabetic characters and underscores
  99250. ** need to be translated.
  99251. */
  99252. #ifdef SQLITE_ASCII
  99253. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  99254. #endif
  99255. #ifdef SQLITE_EBCDIC
  99256. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  99257. const unsigned char ebcdicToAscii[] = {
  99258. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  99259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  99260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  99261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  99262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  99263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  99264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  99265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  99266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  99267. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  99268. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  99269. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  99270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  99271. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  99272. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  99273. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  99274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  99275. };
  99276. #endif
  99277. /*
  99278. ** The sqlite3KeywordCode function looks up an identifier to determine if
  99279. ** it is a keyword. If it is a keyword, the token code of that keyword is
  99280. ** returned. If the input is not a keyword, TK_ID is returned.
  99281. **
  99282. ** The implementation of this routine was generated by a program,
  99283. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  99284. ** The output of the mkkeywordhash.c program is written into a file
  99285. ** named keywordhash.h and then included into this source file by
  99286. ** the #include below.
  99287. */
  99288. /************** Include keywordhash.h in the middle of tokenize.c ************/
  99289. /************** Begin file keywordhash.h *************************************/
  99290. /***** This file contains automatically generated code ******
  99291. **
  99292. ** The code in this file has been automatically generated by
  99293. **
  99294. ** sqlite/tool/mkkeywordhash.c
  99295. **
  99296. ** The code in this file implements a function that determines whether
  99297. ** or not a given identifier is really an SQL keyword. The same thing
  99298. ** might be implemented more directly using a hand-written hash table.
  99299. ** But by using this automatically generated code, the size of the code
  99300. ** is substantially reduced. This is important for embedded applications
  99301. ** on platforms with limited memory.
  99302. */
  99303. /* Hash score: 175 */
  99304. static int keywordCode(const char *z, int n){
  99305. /* zText[] encodes 811 bytes of keywords in 541 bytes */
  99306. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  99307. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  99308. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  99309. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  99310. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  99311. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  99312. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  99313. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  99314. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  99315. /* INITIALLY */
  99316. static const char zText[540] = {
  99317. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  99318. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  99319. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  99320. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  99321. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  99322. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  99323. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  99324. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  99325. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  99326. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  99327. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  99328. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  99329. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  99330. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  99331. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  99332. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  99333. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  99334. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  99335. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  99336. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  99337. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  99338. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  99339. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  99340. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  99341. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  99342. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  99343. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  99344. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  99345. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  99346. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  99347. };
  99348. static const unsigned char aHash[127] = {
  99349. 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
  99350. 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
  99351. 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
  99352. 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
  99353. 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
  99354. 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
  99355. 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
  99356. 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
  99357. 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
  99358. 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
  99359. };
  99360. static const unsigned char aNext[121] = {
  99361. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  99362. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  99363. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  99364. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
  99365. 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
  99366. 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
  99367. 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
  99368. 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
  99369. 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
  99370. 35, 64, 0, 0,
  99371. };
  99372. static const unsigned char aLen[121] = {
  99373. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  99374. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  99375. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  99376. 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
  99377. 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
  99378. 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
  99379. 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
  99380. 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
  99381. 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
  99382. 6, 4, 9, 3,
  99383. };
  99384. static const unsigned short int aOffset[121] = {
  99385. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  99386. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  99387. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  99388. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
  99389. 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
  99390. 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
  99391. 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
  99392. 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
  99393. 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
  99394. 521, 527, 531, 536,
  99395. };
  99396. static const unsigned char aCode[121] = {
  99397. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  99398. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  99399. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  99400. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  99401. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  99402. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  99403. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  99404. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  99405. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  99406. TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
  99407. TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
  99408. TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  99409. TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
  99410. TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
  99411. TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
  99412. TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  99413. TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
  99414. TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
  99415. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  99416. TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
  99417. TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  99418. TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
  99419. TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  99420. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  99421. TK_ALL,
  99422. };
  99423. int h, i;
  99424. if( n<2 ) return TK_ID;
  99425. h = ((charMap(z[0])*4) ^
  99426. (charMap(z[n-1])*3) ^
  99427. n) % 127;
  99428. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  99429. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  99430. testcase( i==0 ); /* REINDEX */
  99431. testcase( i==1 ); /* INDEXED */
  99432. testcase( i==2 ); /* INDEX */
  99433. testcase( i==3 ); /* DESC */
  99434. testcase( i==4 ); /* ESCAPE */
  99435. testcase( i==5 ); /* EACH */
  99436. testcase( i==6 ); /* CHECK */
  99437. testcase( i==7 ); /* KEY */
  99438. testcase( i==8 ); /* BEFORE */
  99439. testcase( i==9 ); /* FOREIGN */
  99440. testcase( i==10 ); /* FOR */
  99441. testcase( i==11 ); /* IGNORE */
  99442. testcase( i==12 ); /* REGEXP */
  99443. testcase( i==13 ); /* EXPLAIN */
  99444. testcase( i==14 ); /* INSTEAD */
  99445. testcase( i==15 ); /* ADD */
  99446. testcase( i==16 ); /* DATABASE */
  99447. testcase( i==17 ); /* AS */
  99448. testcase( i==18 ); /* SELECT */
  99449. testcase( i==19 ); /* TABLE */
  99450. testcase( i==20 ); /* LEFT */
  99451. testcase( i==21 ); /* THEN */
  99452. testcase( i==22 ); /* END */
  99453. testcase( i==23 ); /* DEFERRABLE */
  99454. testcase( i==24 ); /* ELSE */
  99455. testcase( i==25 ); /* EXCEPT */
  99456. testcase( i==26 ); /* TRANSACTION */
  99457. testcase( i==27 ); /* ACTION */
  99458. testcase( i==28 ); /* ON */
  99459. testcase( i==29 ); /* NATURAL */
  99460. testcase( i==30 ); /* ALTER */
  99461. testcase( i==31 ); /* RAISE */
  99462. testcase( i==32 ); /* EXCLUSIVE */
  99463. testcase( i==33 ); /* EXISTS */
  99464. testcase( i==34 ); /* SAVEPOINT */
  99465. testcase( i==35 ); /* INTERSECT */
  99466. testcase( i==36 ); /* TRIGGER */
  99467. testcase( i==37 ); /* REFERENCES */
  99468. testcase( i==38 ); /* CONSTRAINT */
  99469. testcase( i==39 ); /* INTO */
  99470. testcase( i==40 ); /* OFFSET */
  99471. testcase( i==41 ); /* OF */
  99472. testcase( i==42 ); /* SET */
  99473. testcase( i==43 ); /* TEMPORARY */
  99474. testcase( i==44 ); /* TEMP */
  99475. testcase( i==45 ); /* OR */
  99476. testcase( i==46 ); /* UNIQUE */
  99477. testcase( i==47 ); /* QUERY */
  99478. testcase( i==48 ); /* ATTACH */
  99479. testcase( i==49 ); /* HAVING */
  99480. testcase( i==50 ); /* GROUP */
  99481. testcase( i==51 ); /* UPDATE */
  99482. testcase( i==52 ); /* BEGIN */
  99483. testcase( i==53 ); /* INNER */
  99484. testcase( i==54 ); /* RELEASE */
  99485. testcase( i==55 ); /* BETWEEN */
  99486. testcase( i==56 ); /* NOTNULL */
  99487. testcase( i==57 ); /* NOT */
  99488. testcase( i==58 ); /* NO */
  99489. testcase( i==59 ); /* NULL */
  99490. testcase( i==60 ); /* LIKE */
  99491. testcase( i==61 ); /* CASCADE */
  99492. testcase( i==62 ); /* ASC */
  99493. testcase( i==63 ); /* DELETE */
  99494. testcase( i==64 ); /* CASE */
  99495. testcase( i==65 ); /* COLLATE */
  99496. testcase( i==66 ); /* CREATE */
  99497. testcase( i==67 ); /* CURRENT_DATE */
  99498. testcase( i==68 ); /* DETACH */
  99499. testcase( i==69 ); /* IMMEDIATE */
  99500. testcase( i==70 ); /* JOIN */
  99501. testcase( i==71 ); /* INSERT */
  99502. testcase( i==72 ); /* MATCH */
  99503. testcase( i==73 ); /* PLAN */
  99504. testcase( i==74 ); /* ANALYZE */
  99505. testcase( i==75 ); /* PRAGMA */
  99506. testcase( i==76 ); /* ABORT */
  99507. testcase( i==77 ); /* VALUES */
  99508. testcase( i==78 ); /* VIRTUAL */
  99509. testcase( i==79 ); /* LIMIT */
  99510. testcase( i==80 ); /* WHEN */
  99511. testcase( i==81 ); /* WHERE */
  99512. testcase( i==82 ); /* RENAME */
  99513. testcase( i==83 ); /* AFTER */
  99514. testcase( i==84 ); /* REPLACE */
  99515. testcase( i==85 ); /* AND */
  99516. testcase( i==86 ); /* DEFAULT */
  99517. testcase( i==87 ); /* AUTOINCREMENT */
  99518. testcase( i==88 ); /* TO */
  99519. testcase( i==89 ); /* IN */
  99520. testcase( i==90 ); /* CAST */
  99521. testcase( i==91 ); /* COLUMN */
  99522. testcase( i==92 ); /* COMMIT */
  99523. testcase( i==93 ); /* CONFLICT */
  99524. testcase( i==94 ); /* CROSS */
  99525. testcase( i==95 ); /* CURRENT_TIMESTAMP */
  99526. testcase( i==96 ); /* CURRENT_TIME */
  99527. testcase( i==97 ); /* PRIMARY */
  99528. testcase( i==98 ); /* DEFERRED */
  99529. testcase( i==99 ); /* DISTINCT */
  99530. testcase( i==100 ); /* IS */
  99531. testcase( i==101 ); /* DROP */
  99532. testcase( i==102 ); /* FAIL */
  99533. testcase( i==103 ); /* FROM */
  99534. testcase( i==104 ); /* FULL */
  99535. testcase( i==105 ); /* GLOB */
  99536. testcase( i==106 ); /* BY */
  99537. testcase( i==107 ); /* IF */
  99538. testcase( i==108 ); /* ISNULL */
  99539. testcase( i==109 ); /* ORDER */
  99540. testcase( i==110 ); /* RESTRICT */
  99541. testcase( i==111 ); /* OUTER */
  99542. testcase( i==112 ); /* RIGHT */
  99543. testcase( i==113 ); /* ROLLBACK */
  99544. testcase( i==114 ); /* ROW */
  99545. testcase( i==115 ); /* UNION */
  99546. testcase( i==116 ); /* USING */
  99547. testcase( i==117 ); /* VACUUM */
  99548. testcase( i==118 ); /* VIEW */
  99549. testcase( i==119 ); /* INITIALLY */
  99550. testcase( i==120 ); /* ALL */
  99551. return aCode[i];
  99552. }
  99553. }
  99554. return TK_ID;
  99555. }
  99556. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  99557. return keywordCode((char*)z, n);
  99558. }
  99559. #define SQLITE_N_KEYWORD 121
  99560. /************** End of keywordhash.h *****************************************/
  99561. /************** Continuing where we left off in tokenize.c *******************/
  99562. /*
  99563. ** If X is a character that can be used in an identifier then
  99564. ** IdChar(X) will be true. Otherwise it is false.
  99565. **
  99566. ** For ASCII, any character with the high-order bit set is
  99567. ** allowed in an identifier. For 7-bit characters,
  99568. ** sqlite3IsIdChar[X] must be 1.
  99569. **
  99570. ** For EBCDIC, the rules are more complex but have the same
  99571. ** end result.
  99572. **
  99573. ** Ticket #1066. the SQL standard does not allow '$' in the
  99574. ** middle of identfiers. But many SQL implementations do.
  99575. ** SQLite will allow '$' in identifiers for compatibility.
  99576. ** But the feature is undocumented.
  99577. */
  99578. #ifdef SQLITE_ASCII
  99579. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  99580. #endif
  99581. #ifdef SQLITE_EBCDIC
  99582. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  99583. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  99584. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  99585. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  99586. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  99587. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  99588. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  99589. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  99590. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  99591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  99592. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  99593. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  99594. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  99595. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  99596. };
  99597. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  99598. #endif
  99599. /*
  99600. ** Return the length of the token that begins at z[0].
  99601. ** Store the token type in *tokenType before returning.
  99602. */
  99603. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  99604. int i, c;
  99605. switch( *z ){
  99606. case ' ': case '\t': case '\n': case '\f': case '\r': {
  99607. testcase( z[0]==' ' );
  99608. testcase( z[0]=='\t' );
  99609. testcase( z[0]=='\n' );
  99610. testcase( z[0]=='\f' );
  99611. testcase( z[0]=='\r' );
  99612. for(i=1; sqlite3Isspace(z[i]); i++){}
  99613. *tokenType = TK_SPACE;
  99614. return i;
  99615. }
  99616. case '-': {
  99617. if( z[1]=='-' ){
  99618. /* IMP: R-15891-05542 -- syntax diagram for comments */
  99619. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  99620. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  99621. return i;
  99622. }
  99623. *tokenType = TK_MINUS;
  99624. return 1;
  99625. }
  99626. case '(': {
  99627. *tokenType = TK_LP;
  99628. return 1;
  99629. }
  99630. case ')': {
  99631. *tokenType = TK_RP;
  99632. return 1;
  99633. }
  99634. case ';': {
  99635. *tokenType = TK_SEMI;
  99636. return 1;
  99637. }
  99638. case '+': {
  99639. *tokenType = TK_PLUS;
  99640. return 1;
  99641. }
  99642. case '*': {
  99643. *tokenType = TK_STAR;
  99644. return 1;
  99645. }
  99646. case '/': {
  99647. if( z[1]!='*' || z[2]==0 ){
  99648. *tokenType = TK_SLASH;
  99649. return 1;
  99650. }
  99651. /* IMP: R-15891-05542 -- syntax diagram for comments */
  99652. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  99653. if( c ) i++;
  99654. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  99655. return i;
  99656. }
  99657. case '%': {
  99658. *tokenType = TK_REM;
  99659. return 1;
  99660. }
  99661. case '=': {
  99662. *tokenType = TK_EQ;
  99663. return 1 + (z[1]=='=');
  99664. }
  99665. case '<': {
  99666. if( (c=z[1])=='=' ){
  99667. *tokenType = TK_LE;
  99668. return 2;
  99669. }else if( c=='>' ){
  99670. *tokenType = TK_NE;
  99671. return 2;
  99672. }else if( c=='<' ){
  99673. *tokenType = TK_LSHIFT;
  99674. return 2;
  99675. }else{
  99676. *tokenType = TK_LT;
  99677. return 1;
  99678. }
  99679. }
  99680. case '>': {
  99681. if( (c=z[1])=='=' ){
  99682. *tokenType = TK_GE;
  99683. return 2;
  99684. }else if( c=='>' ){
  99685. *tokenType = TK_RSHIFT;
  99686. return 2;
  99687. }else{
  99688. *tokenType = TK_GT;
  99689. return 1;
  99690. }
  99691. }
  99692. case '!': {
  99693. if( z[1]!='=' ){
  99694. *tokenType = TK_ILLEGAL;
  99695. return 2;
  99696. }else{
  99697. *tokenType = TK_NE;
  99698. return 2;
  99699. }
  99700. }
  99701. case '|': {
  99702. if( z[1]!='|' ){
  99703. *tokenType = TK_BITOR;
  99704. return 1;
  99705. }else{
  99706. *tokenType = TK_CONCAT;
  99707. return 2;
  99708. }
  99709. }
  99710. case ',': {
  99711. *tokenType = TK_COMMA;
  99712. return 1;
  99713. }
  99714. case '&': {
  99715. *tokenType = TK_BITAND;
  99716. return 1;
  99717. }
  99718. case '~': {
  99719. *tokenType = TK_BITNOT;
  99720. return 1;
  99721. }
  99722. case '`':
  99723. case '\'':
  99724. case '"': {
  99725. int delim = z[0];
  99726. testcase( delim=='`' );
  99727. testcase( delim=='\'' );
  99728. testcase( delim=='"' );
  99729. for(i=1; (c=z[i])!=0; i++){
  99730. if( c==delim ){
  99731. if( z[i+1]==delim ){
  99732. i++;
  99733. }else{
  99734. break;
  99735. }
  99736. }
  99737. }
  99738. if( c=='\'' ){
  99739. *tokenType = TK_STRING;
  99740. return i+1;
  99741. }else if( c!=0 ){
  99742. *tokenType = TK_ID;
  99743. return i+1;
  99744. }else{
  99745. *tokenType = TK_ILLEGAL;
  99746. return i;
  99747. }
  99748. }
  99749. case '.': {
  99750. #ifndef SQLITE_OMIT_FLOATING_POINT
  99751. if( !sqlite3Isdigit(z[1]) )
  99752. #endif
  99753. {
  99754. *tokenType = TK_DOT;
  99755. return 1;
  99756. }
  99757. /* If the next character is a digit, this is a floating point
  99758. ** number that begins with ".". Fall thru into the next case */
  99759. }
  99760. case '0': case '1': case '2': case '3': case '4':
  99761. case '5': case '6': case '7': case '8': case '9': {
  99762. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  99763. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  99764. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  99765. testcase( z[0]=='9' );
  99766. *tokenType = TK_INTEGER;
  99767. for(i=0; sqlite3Isdigit(z[i]); i++){}
  99768. #ifndef SQLITE_OMIT_FLOATING_POINT
  99769. if( z[i]=='.' ){
  99770. i++;
  99771. while( sqlite3Isdigit(z[i]) ){ i++; }
  99772. *tokenType = TK_FLOAT;
  99773. }
  99774. if( (z[i]=='e' || z[i]=='E') &&
  99775. ( sqlite3Isdigit(z[i+1])
  99776. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  99777. )
  99778. ){
  99779. i += 2;
  99780. while( sqlite3Isdigit(z[i]) ){ i++; }
  99781. *tokenType = TK_FLOAT;
  99782. }
  99783. #endif
  99784. while( IdChar(z[i]) ){
  99785. *tokenType = TK_ILLEGAL;
  99786. i++;
  99787. }
  99788. return i;
  99789. }
  99790. case '[': {
  99791. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  99792. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  99793. return i;
  99794. }
  99795. case '?': {
  99796. *tokenType = TK_VARIABLE;
  99797. for(i=1; sqlite3Isdigit(z[i]); i++){}
  99798. return i;
  99799. }
  99800. case '#': {
  99801. for(i=1; sqlite3Isdigit(z[i]); i++){}
  99802. if( i>1 ){
  99803. /* Parameters of the form #NNN (where NNN is a number) are used
  99804. ** internally by sqlite3NestedParse. */
  99805. *tokenType = TK_REGISTER;
  99806. return i;
  99807. }
  99808. /* Fall through into the next case if the '#' is not followed by
  99809. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  99810. }
  99811. #ifndef SQLITE_OMIT_TCL_VARIABLE
  99812. case '$':
  99813. #endif
  99814. case '@': /* For compatibility with MS SQL Server */
  99815. case ':': {
  99816. int n = 0;
  99817. testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
  99818. *tokenType = TK_VARIABLE;
  99819. for(i=1; (c=z[i])!=0; i++){
  99820. if( IdChar(c) ){
  99821. n++;
  99822. #ifndef SQLITE_OMIT_TCL_VARIABLE
  99823. }else if( c=='(' && n>0 ){
  99824. do{
  99825. i++;
  99826. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  99827. if( c==')' ){
  99828. i++;
  99829. }else{
  99830. *tokenType = TK_ILLEGAL;
  99831. }
  99832. break;
  99833. }else if( c==':' && z[i+1]==':' ){
  99834. i++;
  99835. #endif
  99836. }else{
  99837. break;
  99838. }
  99839. }
  99840. if( n==0 ) *tokenType = TK_ILLEGAL;
  99841. return i;
  99842. }
  99843. #ifndef SQLITE_OMIT_BLOB_LITERAL
  99844. case 'x': case 'X': {
  99845. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  99846. if( z[1]=='\'' ){
  99847. *tokenType = TK_BLOB;
  99848. for(i=2; (c=z[i])!=0 && c!='\''; i++){
  99849. if( !sqlite3Isxdigit(c) ){
  99850. *tokenType = TK_ILLEGAL;
  99851. }
  99852. }
  99853. if( i%2 || !c ) *tokenType = TK_ILLEGAL;
  99854. if( c ) i++;
  99855. return i;
  99856. }
  99857. /* Otherwise fall through to the next case */
  99858. }
  99859. #endif
  99860. default: {
  99861. if( !IdChar(*z) ){
  99862. break;
  99863. }
  99864. for(i=1; IdChar(z[i]); i++){}
  99865. *tokenType = keywordCode((char*)z, i);
  99866. return i;
  99867. }
  99868. }
  99869. *tokenType = TK_ILLEGAL;
  99870. return 1;
  99871. }
  99872. /*
  99873. ** Run the parser on the given SQL string. The parser structure is
  99874. ** passed in. An SQLITE_ status code is returned. If an error occurs
  99875. ** then an and attempt is made to write an error message into
  99876. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  99877. ** error message.
  99878. */
  99879. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  99880. int nErr = 0; /* Number of errors encountered */
  99881. int i; /* Loop counter */
  99882. void *pEngine; /* The LEMON-generated LALR(1) parser */
  99883. int tokenType; /* type of the next token */
  99884. int lastTokenParsed = -1; /* type of the previous token */
  99885. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  99886. sqlite3 *db = pParse->db; /* The database connection */
  99887. int mxSqlLen; /* Max length of an SQL string */
  99888. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  99889. if( db->activeVdbeCnt==0 ){
  99890. db->u1.isInterrupted = 0;
  99891. }
  99892. pParse->rc = SQLITE_OK;
  99893. pParse->zTail = zSql;
  99894. i = 0;
  99895. assert( pzErrMsg!=0 );
  99896. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  99897. if( pEngine==0 ){
  99898. db->mallocFailed = 1;
  99899. return SQLITE_NOMEM;
  99900. }
  99901. assert( pParse->pNewTable==0 );
  99902. assert( pParse->pNewTrigger==0 );
  99903. assert( pParse->nVar==0 );
  99904. assert( pParse->nVarExpr==0 );
  99905. assert( pParse->nVarExprAlloc==0 );
  99906. assert( pParse->apVarExpr==0 );
  99907. enableLookaside = db->lookaside.bEnabled;
  99908. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  99909. while( !db->mallocFailed && zSql[i]!=0 ){
  99910. assert( i>=0 );
  99911. pParse->sLastToken.z = &zSql[i];
  99912. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  99913. i += pParse->sLastToken.n;
  99914. if( i>mxSqlLen ){
  99915. pParse->rc = SQLITE_TOOBIG;
  99916. break;
  99917. }
  99918. switch( tokenType ){
  99919. case TK_SPACE: {
  99920. if( db->u1.isInterrupted ){
  99921. sqlite3ErrorMsg(pParse, "interrupt");
  99922. pParse->rc = SQLITE_INTERRUPT;
  99923. goto abort_parse;
  99924. }
  99925. break;
  99926. }
  99927. case TK_ILLEGAL: {
  99928. sqlite3DbFree(db, *pzErrMsg);
  99929. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  99930. &pParse->sLastToken);
  99931. nErr++;
  99932. goto abort_parse;
  99933. }
  99934. case TK_SEMI: {
  99935. pParse->zTail = &zSql[i];
  99936. /* Fall thru into the default case */
  99937. }
  99938. default: {
  99939. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  99940. lastTokenParsed = tokenType;
  99941. if( pParse->rc!=SQLITE_OK ){
  99942. goto abort_parse;
  99943. }
  99944. break;
  99945. }
  99946. }
  99947. }
  99948. abort_parse:
  99949. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  99950. if( lastTokenParsed!=TK_SEMI ){
  99951. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  99952. pParse->zTail = &zSql[i];
  99953. }
  99954. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  99955. }
  99956. #ifdef YYTRACKMAXSTACKDEPTH
  99957. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  99958. sqlite3ParserStackPeak(pEngine)
  99959. );
  99960. #endif /* YYDEBUG */
  99961. sqlite3ParserFree(pEngine, sqlite3_free);
  99962. db->lookaside.bEnabled = enableLookaside;
  99963. if( db->mallocFailed ){
  99964. pParse->rc = SQLITE_NOMEM;
  99965. }
  99966. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  99967. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  99968. }
  99969. assert( pzErrMsg!=0 );
  99970. if( pParse->zErrMsg ){
  99971. *pzErrMsg = pParse->zErrMsg;
  99972. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  99973. pParse->zErrMsg = 0;
  99974. nErr++;
  99975. }
  99976. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  99977. sqlite3VdbeDelete(pParse->pVdbe);
  99978. pParse->pVdbe = 0;
  99979. }
  99980. #ifndef SQLITE_OMIT_SHARED_CACHE
  99981. if( pParse->nested==0 ){
  99982. sqlite3DbFree(db, pParse->aTableLock);
  99983. pParse->aTableLock = 0;
  99984. pParse->nTableLock = 0;
  99985. }
  99986. #endif
  99987. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99988. sqlite3_free(pParse->apVtabLock);
  99989. #endif
  99990. if( !IN_DECLARE_VTAB ){
  99991. /* If the pParse->declareVtab flag is set, do not delete any table
  99992. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  99993. ** will take responsibility for freeing the Table structure.
  99994. */
  99995. sqlite3DeleteTable(db, pParse->pNewTable);
  99996. }
  99997. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  99998. sqlite3DbFree(db, pParse->apVarExpr);
  99999. sqlite3DbFree(db, pParse->aAlias);
  100000. while( pParse->pAinc ){
  100001. AutoincInfo *p = pParse->pAinc;
  100002. pParse->pAinc = p->pNext;
  100003. sqlite3DbFree(db, p);
  100004. }
  100005. while( pParse->pZombieTab ){
  100006. Table *p = pParse->pZombieTab;
  100007. pParse->pZombieTab = p->pNextZombie;
  100008. sqlite3DeleteTable(db, p);
  100009. }
  100010. if( nErr>0 && pParse->rc==SQLITE_OK ){
  100011. pParse->rc = SQLITE_ERROR;
  100012. }
  100013. return nErr;
  100014. }
  100015. /************** End of tokenize.c ********************************************/
  100016. /************** Begin file complete.c ****************************************/
  100017. /*
  100018. ** 2001 September 15
  100019. **
  100020. ** The author disclaims copyright to this source code. In place of
  100021. ** a legal notice, here is a blessing:
  100022. **
  100023. ** May you do good and not evil.
  100024. ** May you find forgiveness for yourself and forgive others.
  100025. ** May you share freely, never taking more than you give.
  100026. **
  100027. *************************************************************************
  100028. ** An tokenizer for SQL
  100029. **
  100030. ** This file contains C code that implements the sqlite3_complete() API.
  100031. ** This code used to be part of the tokenizer.c source file. But by
  100032. ** separating it out, the code will be automatically omitted from
  100033. ** static links that do not use it.
  100034. */
  100035. #ifndef SQLITE_OMIT_COMPLETE
  100036. /*
  100037. ** This is defined in tokenize.c. We just have to import the definition.
  100038. */
  100039. #ifndef SQLITE_AMALGAMATION
  100040. #ifdef SQLITE_ASCII
  100041. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  100042. #endif
  100043. #ifdef SQLITE_EBCDIC
  100044. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  100045. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  100046. #endif
  100047. #endif /* SQLITE_AMALGAMATION */
  100048. /*
  100049. ** Token types used by the sqlite3_complete() routine. See the header
  100050. ** comments on that procedure for additional information.
  100051. */
  100052. #define tkSEMI 0
  100053. #define tkWS 1
  100054. #define tkOTHER 2
  100055. #ifndef SQLITE_OMIT_TRIGGER
  100056. #define tkEXPLAIN 3
  100057. #define tkCREATE 4
  100058. #define tkTEMP 5
  100059. #define tkTRIGGER 6
  100060. #define tkEND 7
  100061. #endif
  100062. /*
  100063. ** Return TRUE if the given SQL string ends in a semicolon.
  100064. **
  100065. ** Special handling is require for CREATE TRIGGER statements.
  100066. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  100067. ** must end with ";END;".
  100068. **
  100069. ** This implementation uses a state machine with 8 states:
  100070. **
  100071. ** (0) INVALID We have not yet seen a non-whitespace character.
  100072. **
  100073. ** (1) START At the beginning or end of an SQL statement. This routine
  100074. ** returns 1 if it ends in the START state and 0 if it ends
  100075. ** in any other state.
  100076. **
  100077. ** (2) NORMAL We are in the middle of statement which ends with a single
  100078. ** semicolon.
  100079. **
  100080. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  100081. ** a statement.
  100082. **
  100083. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  100084. ** statement, possibly preceeded by EXPLAIN and/or followed by
  100085. ** TEMP or TEMPORARY
  100086. **
  100087. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  100088. ** ended by a semicolon, the keyword END, and another semicolon.
  100089. **
  100090. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  100091. ** the end of a trigger definition.
  100092. **
  100093. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  100094. ** of a trigger difinition.
  100095. **
  100096. ** Transitions between states above are determined by tokens extracted
  100097. ** from the input. The following tokens are significant:
  100098. **
  100099. ** (0) tkSEMI A semicolon.
  100100. ** (1) tkWS Whitespace.
  100101. ** (2) tkOTHER Any other SQL token.
  100102. ** (3) tkEXPLAIN The "explain" keyword.
  100103. ** (4) tkCREATE The "create" keyword.
  100104. ** (5) tkTEMP The "temp" or "temporary" keyword.
  100105. ** (6) tkTRIGGER The "trigger" keyword.
  100106. ** (7) tkEND The "end" keyword.
  100107. **
  100108. ** Whitespace never causes a state transition and is always ignored.
  100109. ** This means that a SQL string of all whitespace is invalid.
  100110. **
  100111. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  100112. ** to recognize the end of a trigger can be omitted. All we have to do
  100113. ** is look for a semicolon that is not part of an string or comment.
  100114. */
  100115. SQLITE_API int sqlite3_complete(const char *zSql){
  100116. u8 state = 0; /* Current state, using numbers defined in header comment */
  100117. u8 token; /* Value of the next token */
  100118. #ifndef SQLITE_OMIT_TRIGGER
  100119. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  100120. ** statement. This is the normal case.
  100121. */
  100122. static const u8 trans[8][8] = {
  100123. /* Token: */
  100124. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  100125. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  100126. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  100127. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  100128. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  100129. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  100130. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  100131. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  100132. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  100133. };
  100134. #else
  100135. /* If triggers are not supported by this compile then the statement machine
  100136. ** used to detect the end of a statement is much simplier
  100137. */
  100138. static const u8 trans[3][3] = {
  100139. /* Token: */
  100140. /* State: ** SEMI WS OTHER */
  100141. /* 0 INVALID: */ { 1, 0, 2, },
  100142. /* 1 START: */ { 1, 1, 2, },
  100143. /* 2 NORMAL: */ { 1, 2, 2, },
  100144. };
  100145. #endif /* SQLITE_OMIT_TRIGGER */
  100146. while( *zSql ){
  100147. switch( *zSql ){
  100148. case ';': { /* A semicolon */
  100149. token = tkSEMI;
  100150. break;
  100151. }
  100152. case ' ':
  100153. case '\r':
  100154. case '\t':
  100155. case '\n':
  100156. case '\f': { /* White space is ignored */
  100157. token = tkWS;
  100158. break;
  100159. }
  100160. case '/': { /* C-style comments */
  100161. if( zSql[1]!='*' ){
  100162. token = tkOTHER;
  100163. break;
  100164. }
  100165. zSql += 2;
  100166. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  100167. if( zSql[0]==0 ) return 0;
  100168. zSql++;
  100169. token = tkWS;
  100170. break;
  100171. }
  100172. case '-': { /* SQL-style comments from "--" to end of line */
  100173. if( zSql[1]!='-' ){
  100174. token = tkOTHER;
  100175. break;
  100176. }
  100177. while( *zSql && *zSql!='\n' ){ zSql++; }
  100178. if( *zSql==0 ) return state==1;
  100179. token = tkWS;
  100180. break;
  100181. }
  100182. case '[': { /* Microsoft-style identifiers in [...] */
  100183. zSql++;
  100184. while( *zSql && *zSql!=']' ){ zSql++; }
  100185. if( *zSql==0 ) return 0;
  100186. token = tkOTHER;
  100187. break;
  100188. }
  100189. case '`': /* Grave-accent quoted symbols used by MySQL */
  100190. case '"': /* single- and double-quoted strings */
  100191. case '\'': {
  100192. int c = *zSql;
  100193. zSql++;
  100194. while( *zSql && *zSql!=c ){ zSql++; }
  100195. if( *zSql==0 ) return 0;
  100196. token = tkOTHER;
  100197. break;
  100198. }
  100199. default: {
  100200. #ifdef SQLITE_EBCDIC
  100201. unsigned char c;
  100202. #endif
  100203. if( IdChar((u8)*zSql) ){
  100204. /* Keywords and unquoted identifiers */
  100205. int nId;
  100206. for(nId=1; IdChar(zSql[nId]); nId++){}
  100207. #ifdef SQLITE_OMIT_TRIGGER
  100208. token = tkOTHER;
  100209. #else
  100210. switch( *zSql ){
  100211. case 'c': case 'C': {
  100212. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  100213. token = tkCREATE;
  100214. }else{
  100215. token = tkOTHER;
  100216. }
  100217. break;
  100218. }
  100219. case 't': case 'T': {
  100220. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  100221. token = tkTRIGGER;
  100222. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  100223. token = tkTEMP;
  100224. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  100225. token = tkTEMP;
  100226. }else{
  100227. token = tkOTHER;
  100228. }
  100229. break;
  100230. }
  100231. case 'e': case 'E': {
  100232. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  100233. token = tkEND;
  100234. }else
  100235. #ifndef SQLITE_OMIT_EXPLAIN
  100236. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  100237. token = tkEXPLAIN;
  100238. }else
  100239. #endif
  100240. {
  100241. token = tkOTHER;
  100242. }
  100243. break;
  100244. }
  100245. default: {
  100246. token = tkOTHER;
  100247. break;
  100248. }
  100249. }
  100250. #endif /* SQLITE_OMIT_TRIGGER */
  100251. zSql += nId-1;
  100252. }else{
  100253. /* Operators and special symbols */
  100254. token = tkOTHER;
  100255. }
  100256. break;
  100257. }
  100258. }
  100259. state = trans[state][token];
  100260. zSql++;
  100261. }
  100262. return state==1;
  100263. }
  100264. #ifndef SQLITE_OMIT_UTF16
  100265. /*
  100266. ** This routine is the same as the sqlite3_complete() routine described
  100267. ** above, except that the parameter is required to be UTF-16 encoded, not
  100268. ** UTF-8.
  100269. */
  100270. SQLITE_API int sqlite3_complete16(const void *zSql){
  100271. sqlite3_value *pVal;
  100272. char const *zSql8;
  100273. int rc = SQLITE_NOMEM;
  100274. #ifndef SQLITE_OMIT_AUTOINIT
  100275. rc = sqlite3_initialize();
  100276. if( rc ) return rc;
  100277. #endif
  100278. pVal = sqlite3ValueNew(0);
  100279. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  100280. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  100281. if( zSql8 ){
  100282. rc = sqlite3_complete(zSql8);
  100283. }else{
  100284. rc = SQLITE_NOMEM;
  100285. }
  100286. sqlite3ValueFree(pVal);
  100287. return sqlite3ApiExit(0, rc);
  100288. }
  100289. #endif /* SQLITE_OMIT_UTF16 */
  100290. #endif /* SQLITE_OMIT_COMPLETE */
  100291. /************** End of complete.c ********************************************/
  100292. /************** Begin file main.c ********************************************/
  100293. /*
  100294. ** 2001 September 15
  100295. **
  100296. ** The author disclaims copyright to this source code. In place of
  100297. ** a legal notice, here is a blessing:
  100298. **
  100299. ** May you do good and not evil.
  100300. ** May you find forgiveness for yourself and forgive others.
  100301. ** May you share freely, never taking more than you give.
  100302. **
  100303. *************************************************************************
  100304. ** Main file for the SQLite library. The routines in this file
  100305. ** implement the programmer interface to the library. Routines in
  100306. ** other files are for internal use by SQLite and should not be
  100307. ** accessed by users of the library.
  100308. */
  100309. #ifdef SQLITE_ENABLE_FTS3
  100310. /************** Include fts3.h in the middle of main.c ***********************/
  100311. /************** Begin file fts3.h ********************************************/
  100312. /*
  100313. ** 2006 Oct 10
  100314. **
  100315. ** The author disclaims copyright to this source code. In place of
  100316. ** a legal notice, here is a blessing:
  100317. **
  100318. ** May you do good and not evil.
  100319. ** May you find forgiveness for yourself and forgive others.
  100320. ** May you share freely, never taking more than you give.
  100321. **
  100322. ******************************************************************************
  100323. **
  100324. ** This header file is used by programs that want to link against the
  100325. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  100326. */
  100327. #if 0
  100328. extern "C" {
  100329. #endif /* __cplusplus */
  100330. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  100331. #if 0
  100332. } /* extern "C" */
  100333. #endif /* __cplusplus */
  100334. /************** End of fts3.h ************************************************/
  100335. /************** Continuing where we left off in main.c ***********************/
  100336. #endif
  100337. #ifdef SQLITE_ENABLE_RTREE
  100338. /************** Include rtree.h in the middle of main.c **********************/
  100339. /************** Begin file rtree.h *******************************************/
  100340. /*
  100341. ** 2008 May 26
  100342. **
  100343. ** The author disclaims copyright to this source code. In place of
  100344. ** a legal notice, here is a blessing:
  100345. **
  100346. ** May you do good and not evil.
  100347. ** May you find forgiveness for yourself and forgive others.
  100348. ** May you share freely, never taking more than you give.
  100349. **
  100350. ******************************************************************************
  100351. **
  100352. ** This header file is used by programs that want to link against the
  100353. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  100354. */
  100355. #if 0
  100356. extern "C" {
  100357. #endif /* __cplusplus */
  100358. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  100359. #if 0
  100360. } /* extern "C" */
  100361. #endif /* __cplusplus */
  100362. /************** End of rtree.h ***********************************************/
  100363. /************** Continuing where we left off in main.c ***********************/
  100364. #endif
  100365. #ifdef SQLITE_ENABLE_ICU
  100366. /************** Include sqliteicu.h in the middle of main.c ******************/
  100367. /************** Begin file sqliteicu.h ***************************************/
  100368. /*
  100369. ** 2008 May 26
  100370. **
  100371. ** The author disclaims copyright to this source code. In place of
  100372. ** a legal notice, here is a blessing:
  100373. **
  100374. ** May you do good and not evil.
  100375. ** May you find forgiveness for yourself and forgive others.
  100376. ** May you share freely, never taking more than you give.
  100377. **
  100378. ******************************************************************************
  100379. **
  100380. ** This header file is used by programs that want to link against the
  100381. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  100382. */
  100383. #if 0
  100384. extern "C" {
  100385. #endif /* __cplusplus */
  100386. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  100387. #if 0
  100388. } /* extern "C" */
  100389. #endif /* __cplusplus */
  100390. /************** End of sqliteicu.h *******************************************/
  100391. /************** Continuing where we left off in main.c ***********************/
  100392. #endif
  100393. #ifndef SQLITE_AMALGAMATION
  100394. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  100395. ** contains the text of SQLITE_VERSION macro.
  100396. */
  100397. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  100398. #endif
  100399. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  100400. ** a pointer to the to the sqlite3_version[] string constant.
  100401. */
  100402. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  100403. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  100404. ** pointer to a string constant whose value is the same as the
  100405. ** SQLITE_SOURCE_ID C preprocessor macro.
  100406. */
  100407. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  100408. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  100409. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  100410. */
  100411. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  100412. /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
  100413. ** zero if and only if SQLite was compiled mutexing code omitted due to
  100414. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  100415. */
  100416. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  100417. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  100418. /*
  100419. ** If the following function pointer is not NULL and if
  100420. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  100421. ** I/O active are written using this function. These messages
  100422. ** are intended for debugging activity only.
  100423. */
  100424. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  100425. #endif
  100426. /*
  100427. ** If the following global variable points to a string which is the
  100428. ** name of a directory, then that directory will be used to store
  100429. ** temporary files.
  100430. **
  100431. ** See also the "PRAGMA temp_store_directory" SQL command.
  100432. */
  100433. SQLITE_API char *sqlite3_temp_directory = 0;
  100434. /*
  100435. ** Initialize SQLite.
  100436. **
  100437. ** This routine must be called to initialize the memory allocation,
  100438. ** VFS, and mutex subsystems prior to doing any serious work with
  100439. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  100440. ** this routine will be called automatically by key routines such as
  100441. ** sqlite3_open().
  100442. **
  100443. ** This routine is a no-op except on its very first call for the process,
  100444. ** or for the first call after a call to sqlite3_shutdown.
  100445. **
  100446. ** The first thread to call this routine runs the initialization to
  100447. ** completion. If subsequent threads call this routine before the first
  100448. ** thread has finished the initialization process, then the subsequent
  100449. ** threads must block until the first thread finishes with the initialization.
  100450. **
  100451. ** The first thread might call this routine recursively. Recursive
  100452. ** calls to this routine should not block, of course. Otherwise the
  100453. ** initialization process would never complete.
  100454. **
  100455. ** Let X be the first thread to enter this routine. Let Y be some other
  100456. ** thread. Then while the initial invocation of this routine by X is
  100457. ** incomplete, it is required that:
  100458. **
  100459. ** * Calls to this routine from Y must block until the outer-most
  100460. ** call by X completes.
  100461. **
  100462. ** * Recursive calls to this routine from thread X return immediately
  100463. ** without blocking.
  100464. */
  100465. SQLITE_API int sqlite3_initialize(void){
  100466. sqlite3_mutex *pMaster; /* The main static mutex */
  100467. int rc; /* Result code */
  100468. #ifdef SQLITE_OMIT_WSD
  100469. rc = sqlite3_wsd_init(4096, 24);
  100470. if( rc!=SQLITE_OK ){
  100471. return rc;
  100472. }
  100473. #endif
  100474. /* If SQLite is already completely initialized, then this call
  100475. ** to sqlite3_initialize() should be a no-op. But the initialization
  100476. ** must be complete. So isInit must not be set until the very end
  100477. ** of this routine.
  100478. */
  100479. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  100480. /* Make sure the mutex subsystem is initialized. If unable to
  100481. ** initialize the mutex subsystem, return early with the error.
  100482. ** If the system is so sick that we are unable to allocate a mutex,
  100483. ** there is not much SQLite is going to be able to do.
  100484. **
  100485. ** The mutex subsystem must take care of serializing its own
  100486. ** initialization.
  100487. */
  100488. rc = sqlite3MutexInit();
  100489. if( rc ) return rc;
  100490. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  100491. ** This operation is protected by the STATIC_MASTER mutex. Note that
  100492. ** MutexAlloc() is called for a static mutex prior to initializing the
  100493. ** malloc subsystem - this implies that the allocation of a static
  100494. ** mutex must not require support from the malloc subsystem.
  100495. */
  100496. pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  100497. sqlite3_mutex_enter(pMaster);
  100498. sqlite3GlobalConfig.isMutexInit = 1;
  100499. if( !sqlite3GlobalConfig.isMallocInit ){
  100500. rc = sqlite3MallocInit();
  100501. }
  100502. if( rc==SQLITE_OK ){
  100503. sqlite3GlobalConfig.isMallocInit = 1;
  100504. if( !sqlite3GlobalConfig.pInitMutex ){
  100505. sqlite3GlobalConfig.pInitMutex =
  100506. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  100507. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  100508. rc = SQLITE_NOMEM;
  100509. }
  100510. }
  100511. }
  100512. if( rc==SQLITE_OK ){
  100513. sqlite3GlobalConfig.nRefInitMutex++;
  100514. }
  100515. sqlite3_mutex_leave(pMaster);
  100516. /* If rc is not SQLITE_OK at this point, then either the malloc
  100517. ** subsystem could not be initialized or the system failed to allocate
  100518. ** the pInitMutex mutex. Return an error in either case. */
  100519. if( rc!=SQLITE_OK ){
  100520. return rc;
  100521. }
  100522. /* Do the rest of the initialization under the recursive mutex so
  100523. ** that we will be able to handle recursive calls into
  100524. ** sqlite3_initialize(). The recursive calls normally come through
  100525. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  100526. ** recursive calls might also be possible.
  100527. **
  100528. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  100529. ** to the xInit method, so the xInit method need not be threadsafe.
  100530. **
  100531. ** The following mutex is what serializes access to the appdef pcache xInit
  100532. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  100533. ** call to sqlite3PcacheInitialize().
  100534. */
  100535. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  100536. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  100537. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  100538. sqlite3GlobalConfig.inProgress = 1;
  100539. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  100540. sqlite3RegisterGlobalFunctions();
  100541. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  100542. rc = sqlite3PcacheInitialize();
  100543. }
  100544. if( rc==SQLITE_OK ){
  100545. sqlite3GlobalConfig.isPCacheInit = 1;
  100546. rc = sqlite3OsInit();
  100547. }
  100548. if( rc==SQLITE_OK ){
  100549. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  100550. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  100551. sqlite3GlobalConfig.isInit = 1;
  100552. }
  100553. sqlite3GlobalConfig.inProgress = 0;
  100554. }
  100555. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  100556. /* Go back under the static mutex and clean up the recursive
  100557. ** mutex to prevent a resource leak.
  100558. */
  100559. sqlite3_mutex_enter(pMaster);
  100560. sqlite3GlobalConfig.nRefInitMutex--;
  100561. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  100562. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  100563. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  100564. sqlite3GlobalConfig.pInitMutex = 0;
  100565. }
  100566. sqlite3_mutex_leave(pMaster);
  100567. /* The following is just a sanity check to make sure SQLite has
  100568. ** been compiled correctly. It is important to run this code, but
  100569. ** we don't want to run it too often and soak up CPU cycles for no
  100570. ** reason. So we run it once during initialization.
  100571. */
  100572. #ifndef NDEBUG
  100573. #ifndef SQLITE_OMIT_FLOATING_POINT
  100574. /* This section of code's only "output" is via assert() statements. */
  100575. if ( rc==SQLITE_OK ){
  100576. u64 x = (((u64)1)<<63)-1;
  100577. double y;
  100578. assert(sizeof(x)==8);
  100579. assert(sizeof(x)==sizeof(y));
  100580. memcpy(&y, &x, 8);
  100581. assert( sqlite3IsNaN(y) );
  100582. }
  100583. #endif
  100584. #endif
  100585. return rc;
  100586. }
  100587. /*
  100588. ** Undo the effects of sqlite3_initialize(). Must not be called while
  100589. ** there are outstanding database connections or memory allocations or
  100590. ** while any part of SQLite is otherwise in use in any thread. This
  100591. ** routine is not threadsafe. But it is safe to invoke this routine
  100592. ** on when SQLite is already shut down. If SQLite is already shut down
  100593. ** when this routine is invoked, then this routine is a harmless no-op.
  100594. */
  100595. SQLITE_API int sqlite3_shutdown(void){
  100596. if( sqlite3GlobalConfig.isInit ){
  100597. sqlite3_os_end();
  100598. sqlite3_reset_auto_extension();
  100599. sqlite3GlobalConfig.isInit = 0;
  100600. }
  100601. if( sqlite3GlobalConfig.isPCacheInit ){
  100602. sqlite3PcacheShutdown();
  100603. sqlite3GlobalConfig.isPCacheInit = 0;
  100604. }
  100605. if( sqlite3GlobalConfig.isMallocInit ){
  100606. sqlite3MallocEnd();
  100607. sqlite3GlobalConfig.isMallocInit = 0;
  100608. }
  100609. if( sqlite3GlobalConfig.isMutexInit ){
  100610. sqlite3MutexEnd();
  100611. sqlite3GlobalConfig.isMutexInit = 0;
  100612. }
  100613. return SQLITE_OK;
  100614. }
  100615. /*
  100616. ** This API allows applications to modify the global configuration of
  100617. ** the SQLite library at run-time.
  100618. **
  100619. ** This routine should only be called when there are no outstanding
  100620. ** database connections or memory allocations. This routine is not
  100621. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  100622. ** behavior.
  100623. */
  100624. SQLITE_API int sqlite3_config(int op, ...){
  100625. va_list ap;
  100626. int rc = SQLITE_OK;
  100627. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  100628. ** the SQLite library is in use. */
  100629. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  100630. va_start(ap, op);
  100631. switch( op ){
  100632. /* Mutex configuration options are only available in a threadsafe
  100633. ** compile.
  100634. */
  100635. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  100636. case SQLITE_CONFIG_SINGLETHREAD: {
  100637. /* Disable all mutexing */
  100638. sqlite3GlobalConfig.bCoreMutex = 0;
  100639. sqlite3GlobalConfig.bFullMutex = 0;
  100640. break;
  100641. }
  100642. case SQLITE_CONFIG_MULTITHREAD: {
  100643. /* Disable mutexing of database connections */
  100644. /* Enable mutexing of core data structures */
  100645. sqlite3GlobalConfig.bCoreMutex = 1;
  100646. sqlite3GlobalConfig.bFullMutex = 0;
  100647. break;
  100648. }
  100649. case SQLITE_CONFIG_SERIALIZED: {
  100650. /* Enable all mutexing */
  100651. sqlite3GlobalConfig.bCoreMutex = 1;
  100652. sqlite3GlobalConfig.bFullMutex = 1;
  100653. break;
  100654. }
  100655. case SQLITE_CONFIG_MUTEX: {
  100656. /* Specify an alternative mutex implementation */
  100657. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  100658. break;
  100659. }
  100660. case SQLITE_CONFIG_GETMUTEX: {
  100661. /* Retrieve the current mutex implementation */
  100662. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  100663. break;
  100664. }
  100665. #endif
  100666. case SQLITE_CONFIG_MALLOC: {
  100667. /* Specify an alternative malloc implementation */
  100668. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  100669. break;
  100670. }
  100671. case SQLITE_CONFIG_GETMALLOC: {
  100672. /* Retrieve the current malloc() implementation */
  100673. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  100674. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  100675. break;
  100676. }
  100677. case SQLITE_CONFIG_MEMSTATUS: {
  100678. /* Enable or disable the malloc status collection */
  100679. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  100680. break;
  100681. }
  100682. case SQLITE_CONFIG_SCRATCH: {
  100683. /* Designate a buffer for scratch memory space */
  100684. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  100685. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  100686. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  100687. break;
  100688. }
  100689. case SQLITE_CONFIG_PAGECACHE: {
  100690. /* Designate a buffer for page cache memory space */
  100691. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  100692. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  100693. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  100694. break;
  100695. }
  100696. case SQLITE_CONFIG_PCACHE: {
  100697. /* Specify an alternative page cache implementation */
  100698. sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
  100699. break;
  100700. }
  100701. case SQLITE_CONFIG_GETPCACHE: {
  100702. if( sqlite3GlobalConfig.pcache.xInit==0 ){
  100703. sqlite3PCacheSetDefault();
  100704. }
  100705. *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
  100706. break;
  100707. }
  100708. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  100709. case SQLITE_CONFIG_HEAP: {
  100710. /* Designate a buffer for heap memory space */
  100711. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  100712. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  100713. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  100714. if( sqlite3GlobalConfig.mnReq<1 ){
  100715. sqlite3GlobalConfig.mnReq = 1;
  100716. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  100717. /* cap min request size at 2^12 */
  100718. sqlite3GlobalConfig.mnReq = (1<<12);
  100719. }
  100720. if( sqlite3GlobalConfig.pHeap==0 ){
  100721. /* If the heap pointer is NULL, then restore the malloc implementation
  100722. ** back to NULL pointers too. This will cause the malloc to go
  100723. ** back to its default implementation when sqlite3_initialize() is
  100724. ** run.
  100725. */
  100726. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  100727. }else{
  100728. /* The heap pointer is not NULL, then install one of the
  100729. ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
  100730. ** ENABLE_MEMSYS5 is defined, return an error.
  100731. */
  100732. #ifdef SQLITE_ENABLE_MEMSYS3
  100733. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  100734. #endif
  100735. #ifdef SQLITE_ENABLE_MEMSYS5
  100736. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  100737. #endif
  100738. }
  100739. break;
  100740. }
  100741. #endif
  100742. case SQLITE_CONFIG_LOOKASIDE: {
  100743. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  100744. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  100745. break;
  100746. }
  100747. /* Record a pointer to the logger funcction and its first argument.
  100748. ** The default is NULL. Logging is disabled if the function pointer is
  100749. ** NULL.
  100750. */
  100751. case SQLITE_CONFIG_LOG: {
  100752. /* MSVC is picky about pulling func ptrs from va lists.
  100753. ** http://support.microsoft.com/kb/47961
  100754. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  100755. */
  100756. typedef void(*LOGFUNC_t)(void*,int,const char*);
  100757. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  100758. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  100759. break;
  100760. }
  100761. default: {
  100762. rc = SQLITE_ERROR;
  100763. break;
  100764. }
  100765. }
  100766. va_end(ap);
  100767. return rc;
  100768. }
  100769. /*
  100770. ** Set up the lookaside buffers for a database connection.
  100771. ** Return SQLITE_OK on success.
  100772. ** If lookaside is already active, return SQLITE_BUSY.
  100773. **
  100774. ** The sz parameter is the number of bytes in each lookaside slot.
  100775. ** The cnt parameter is the number of slots. If pStart is NULL the
  100776. ** space for the lookaside memory is obtained from sqlite3_malloc().
  100777. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  100778. ** the lookaside memory.
  100779. */
  100780. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  100781. void *pStart;
  100782. if( db->lookaside.nOut ){
  100783. return SQLITE_BUSY;
  100784. }
  100785. /* Free any existing lookaside buffer for this handle before
  100786. ** allocating a new one so we don't have to have space for
  100787. ** both at the same time.
  100788. */
  100789. if( db->lookaside.bMalloced ){
  100790. sqlite3_free(db->lookaside.pStart);
  100791. }
  100792. /* The size of a lookaside slot needs to be larger than a pointer
  100793. ** to be useful.
  100794. */
  100795. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  100796. if( cnt<0 ) cnt = 0;
  100797. if( sz==0 || cnt==0 ){
  100798. sz = 0;
  100799. pStart = 0;
  100800. }else if( pBuf==0 ){
  100801. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  100802. sqlite3BeginBenignMalloc();
  100803. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  100804. sqlite3EndBenignMalloc();
  100805. }else{
  100806. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  100807. pStart = pBuf;
  100808. }
  100809. db->lookaside.pStart = pStart;
  100810. db->lookaside.pFree = 0;
  100811. db->lookaside.sz = (u16)sz;
  100812. if( pStart ){
  100813. int i;
  100814. LookasideSlot *p;
  100815. assert( sz > (int)sizeof(LookasideSlot*) );
  100816. p = (LookasideSlot*)pStart;
  100817. for(i=cnt-1; i>=0; i--){
  100818. p->pNext = db->lookaside.pFree;
  100819. db->lookaside.pFree = p;
  100820. p = (LookasideSlot*)&((u8*)p)[sz];
  100821. }
  100822. db->lookaside.pEnd = p;
  100823. db->lookaside.bEnabled = 1;
  100824. db->lookaside.bMalloced = pBuf==0 ?1:0;
  100825. }else{
  100826. db->lookaside.pEnd = 0;
  100827. db->lookaside.bEnabled = 0;
  100828. db->lookaside.bMalloced = 0;
  100829. }
  100830. return SQLITE_OK;
  100831. }
  100832. /*
  100833. ** Return the mutex associated with a database connection.
  100834. */
  100835. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  100836. return db->mutex;
  100837. }
  100838. /*
  100839. ** Configuration settings for an individual database connection
  100840. */
  100841. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  100842. va_list ap;
  100843. int rc;
  100844. va_start(ap, op);
  100845. switch( op ){
  100846. case SQLITE_DBCONFIG_LOOKASIDE: {
  100847. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  100848. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  100849. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  100850. rc = setupLookaside(db, pBuf, sz, cnt);
  100851. break;
  100852. }
  100853. default: {
  100854. static const struct {
  100855. int op; /* The opcode */
  100856. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  100857. } aFlagOp[] = {
  100858. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  100859. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  100860. };
  100861. unsigned int i;
  100862. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  100863. for(i=0; i<ArraySize(aFlagOp); i++){
  100864. if( aFlagOp[i].op==op ){
  100865. int onoff = va_arg(ap, int);
  100866. int *pRes = va_arg(ap, int*);
  100867. int oldFlags = db->flags;
  100868. if( onoff>0 ){
  100869. db->flags |= aFlagOp[i].mask;
  100870. }else if( onoff==0 ){
  100871. db->flags &= ~aFlagOp[i].mask;
  100872. }
  100873. if( oldFlags!=db->flags ){
  100874. sqlite3ExpirePreparedStatements(db);
  100875. }
  100876. if( pRes ){
  100877. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  100878. }
  100879. rc = SQLITE_OK;
  100880. break;
  100881. }
  100882. }
  100883. break;
  100884. }
  100885. }
  100886. va_end(ap);
  100887. return rc;
  100888. }
  100889. /*
  100890. ** Return true if the buffer z[0..n-1] contains all spaces.
  100891. */
  100892. static int allSpaces(const char *z, int n){
  100893. while( n>0 && z[n-1]==' ' ){ n--; }
  100894. return n==0;
  100895. }
  100896. /*
  100897. ** This is the default collating function named "BINARY" which is always
  100898. ** available.
  100899. **
  100900. ** If the padFlag argument is not NULL then space padding at the end
  100901. ** of strings is ignored. This implements the RTRIM collation.
  100902. */
  100903. static int binCollFunc(
  100904. void *padFlag,
  100905. int nKey1, const void *pKey1,
  100906. int nKey2, const void *pKey2
  100907. ){
  100908. int rc, n;
  100909. n = nKey1<nKey2 ? nKey1 : nKey2;
  100910. rc = memcmp(pKey1, pKey2, n);
  100911. if( rc==0 ){
  100912. if( padFlag
  100913. && allSpaces(((char*)pKey1)+n, nKey1-n)
  100914. && allSpaces(((char*)pKey2)+n, nKey2-n)
  100915. ){
  100916. /* Leave rc unchanged at 0 */
  100917. }else{
  100918. rc = nKey1 - nKey2;
  100919. }
  100920. }
  100921. return rc;
  100922. }
  100923. /*
  100924. ** Another built-in collating sequence: NOCASE.
  100925. **
  100926. ** This collating sequence is intended to be used for "case independant
  100927. ** comparison". SQLite's knowledge of upper and lower case equivalents
  100928. ** extends only to the 26 characters used in the English language.
  100929. **
  100930. ** At the moment there is only a UTF-8 implementation.
  100931. */
  100932. static int nocaseCollatingFunc(
  100933. void *NotUsed,
  100934. int nKey1, const void *pKey1,
  100935. int nKey2, const void *pKey2
  100936. ){
  100937. int r = sqlite3StrNICmp(
  100938. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  100939. UNUSED_PARAMETER(NotUsed);
  100940. if( 0==r ){
  100941. r = nKey1-nKey2;
  100942. }
  100943. return r;
  100944. }
  100945. /*
  100946. ** Return the ROWID of the most recent insert
  100947. */
  100948. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  100949. return db->lastRowid;
  100950. }
  100951. /*
  100952. ** Return the number of changes in the most recent call to sqlite3_exec().
  100953. */
  100954. SQLITE_API int sqlite3_changes(sqlite3 *db){
  100955. return db->nChange;
  100956. }
  100957. /*
  100958. ** Return the number of changes since the database handle was opened.
  100959. */
  100960. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  100961. return db->nTotalChange;
  100962. }
  100963. /*
  100964. ** Close all open savepoints. This function only manipulates fields of the
  100965. ** database handle object, it does not close any savepoints that may be open
  100966. ** at the b-tree/pager level.
  100967. */
  100968. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  100969. while( db->pSavepoint ){
  100970. Savepoint *pTmp = db->pSavepoint;
  100971. db->pSavepoint = pTmp->pNext;
  100972. sqlite3DbFree(db, pTmp);
  100973. }
  100974. db->nSavepoint = 0;
  100975. db->nStatement = 0;
  100976. db->isTransactionSavepoint = 0;
  100977. }
  100978. /*
  100979. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  100980. ** if this is not the last copy of the function, do not invoke it. Multiple
  100981. ** copies of a single function are created when create_function() is called
  100982. ** with SQLITE_ANY as the encoding.
  100983. */
  100984. static void functionDestroy(sqlite3 *db, FuncDef *p){
  100985. FuncDestructor *pDestructor = p->pDestructor;
  100986. if( pDestructor ){
  100987. pDestructor->nRef--;
  100988. if( pDestructor->nRef==0 ){
  100989. pDestructor->xDestroy(pDestructor->pUserData);
  100990. sqlite3DbFree(db, pDestructor);
  100991. }
  100992. }
  100993. }
  100994. /*
  100995. ** Close an existing SQLite database
  100996. */
  100997. SQLITE_API int sqlite3_close(sqlite3 *db){
  100998. HashElem *i; /* Hash table iterator */
  100999. int j;
  101000. if( !db ){
  101001. return SQLITE_OK;
  101002. }
  101003. if( !sqlite3SafetyCheckSickOrOk(db) ){
  101004. return SQLITE_MISUSE_BKPT;
  101005. }
  101006. sqlite3_mutex_enter(db->mutex);
  101007. /* Force xDestroy calls on all virtual tables */
  101008. sqlite3ResetInternalSchema(db, -1);
  101009. /* If a transaction is open, the ResetInternalSchema() call above
  101010. ** will not have called the xDisconnect() method on any virtual
  101011. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  101012. ** call will do so. We need to do this before the check for active
  101013. ** SQL statements below, as the v-table implementation may be storing
  101014. ** some prepared statements internally.
  101015. */
  101016. sqlite3VtabRollback(db);
  101017. /* If there are any outstanding VMs, return SQLITE_BUSY. */
  101018. if( db->pVdbe ){
  101019. sqlite3Error(db, SQLITE_BUSY,
  101020. "unable to close due to unfinalised statements");
  101021. sqlite3_mutex_leave(db->mutex);
  101022. return SQLITE_BUSY;
  101023. }
  101024. assert( sqlite3SafetyCheckSickOrOk(db) );
  101025. for(j=0; j<db->nDb; j++){
  101026. Btree *pBt = db->aDb[j].pBt;
  101027. if( pBt && sqlite3BtreeIsInBackup(pBt) ){
  101028. sqlite3Error(db, SQLITE_BUSY,
  101029. "unable to close due to unfinished backup operation");
  101030. sqlite3_mutex_leave(db->mutex);
  101031. return SQLITE_BUSY;
  101032. }
  101033. }
  101034. /* Free any outstanding Savepoint structures. */
  101035. sqlite3CloseSavepoints(db);
  101036. for(j=0; j<db->nDb; j++){
  101037. struct Db *pDb = &db->aDb[j];
  101038. if( pDb->pBt ){
  101039. sqlite3BtreeClose(pDb->pBt);
  101040. pDb->pBt = 0;
  101041. if( j!=1 ){
  101042. pDb->pSchema = 0;
  101043. }
  101044. }
  101045. }
  101046. sqlite3ResetInternalSchema(db, -1);
  101047. /* Tell the code in notify.c that the connection no longer holds any
  101048. ** locks and does not require any further unlock-notify callbacks.
  101049. */
  101050. sqlite3ConnectionClosed(db);
  101051. assert( db->nDb<=2 );
  101052. assert( db->aDb==db->aDbStatic );
  101053. for(j=0; j<ArraySize(db->aFunc.a); j++){
  101054. FuncDef *pNext, *pHash, *p;
  101055. for(p=db->aFunc.a[j]; p; p=pHash){
  101056. pHash = p->pHash;
  101057. while( p ){
  101058. functionDestroy(db, p);
  101059. pNext = p->pNext;
  101060. sqlite3DbFree(db, p);
  101061. p = pNext;
  101062. }
  101063. }
  101064. }
  101065. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  101066. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  101067. /* Invoke any destructors registered for collation sequence user data. */
  101068. for(j=0; j<3; j++){
  101069. if( pColl[j].xDel ){
  101070. pColl[j].xDel(pColl[j].pUser);
  101071. }
  101072. }
  101073. sqlite3DbFree(db, pColl);
  101074. }
  101075. sqlite3HashClear(&db->aCollSeq);
  101076. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101077. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  101078. Module *pMod = (Module *)sqliteHashData(i);
  101079. if( pMod->xDestroy ){
  101080. pMod->xDestroy(pMod->pAux);
  101081. }
  101082. sqlite3DbFree(db, pMod);
  101083. }
  101084. sqlite3HashClear(&db->aModule);
  101085. #endif
  101086. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  101087. if( db->pErr ){
  101088. sqlite3ValueFree(db->pErr);
  101089. }
  101090. sqlite3CloseExtensions(db);
  101091. db->magic = SQLITE_MAGIC_ERROR;
  101092. /* The temp-database schema is allocated differently from the other schema
  101093. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  101094. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  101095. ** the same sqliteMalloc() as the one that allocates the database
  101096. ** structure?
  101097. */
  101098. sqlite3DbFree(db, db->aDb[1].pSchema);
  101099. sqlite3_mutex_leave(db->mutex);
  101100. db->magic = SQLITE_MAGIC_CLOSED;
  101101. sqlite3_mutex_free(db->mutex);
  101102. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  101103. if( db->lookaside.bMalloced ){
  101104. sqlite3_free(db->lookaside.pStart);
  101105. }
  101106. sqlite3_free(db);
  101107. return SQLITE_OK;
  101108. }
  101109. /*
  101110. ** Rollback all database files.
  101111. */
  101112. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
  101113. int i;
  101114. int inTrans = 0;
  101115. assert( sqlite3_mutex_held(db->mutex) );
  101116. sqlite3BeginBenignMalloc();
  101117. for(i=0; i<db->nDb; i++){
  101118. if( db->aDb[i].pBt ){
  101119. if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
  101120. inTrans = 1;
  101121. }
  101122. sqlite3BtreeRollback(db->aDb[i].pBt);
  101123. db->aDb[i].inTrans = 0;
  101124. }
  101125. }
  101126. sqlite3VtabRollback(db);
  101127. sqlite3EndBenignMalloc();
  101128. if( db->flags&SQLITE_InternChanges ){
  101129. sqlite3ExpirePreparedStatements(db);
  101130. sqlite3ResetInternalSchema(db, -1);
  101131. }
  101132. /* Any deferred constraint violations have now been resolved. */
  101133. db->nDeferredCons = 0;
  101134. /* If one has been configured, invoke the rollback-hook callback */
  101135. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  101136. db->xRollbackCallback(db->pRollbackArg);
  101137. }
  101138. }
  101139. /*
  101140. ** Return a static string that describes the kind of error specified in the
  101141. ** argument.
  101142. */
  101143. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  101144. static const char* const aMsg[] = {
  101145. /* SQLITE_OK */ "not an error",
  101146. /* SQLITE_ERROR */ "SQL logic error or missing database",
  101147. /* SQLITE_INTERNAL */ 0,
  101148. /* SQLITE_PERM */ "access permission denied",
  101149. /* SQLITE_ABORT */ "callback requested query abort",
  101150. /* SQLITE_BUSY */ "database is locked",
  101151. /* SQLITE_LOCKED */ "database table is locked",
  101152. /* SQLITE_NOMEM */ "out of memory",
  101153. /* SQLITE_READONLY */ "attempt to write a readonly database",
  101154. /* SQLITE_INTERRUPT */ "interrupted",
  101155. /* SQLITE_IOERR */ "disk I/O error",
  101156. /* SQLITE_CORRUPT */ "database disk image is malformed",
  101157. /* SQLITE_NOTFOUND */ "unknown operation",
  101158. /* SQLITE_FULL */ "database or disk is full",
  101159. /* SQLITE_CANTOPEN */ "unable to open database file",
  101160. /* SQLITE_PROTOCOL */ "locking protocol",
  101161. /* SQLITE_EMPTY */ "table contains no data",
  101162. /* SQLITE_SCHEMA */ "database schema has changed",
  101163. /* SQLITE_TOOBIG */ "string or blob too big",
  101164. /* SQLITE_CONSTRAINT */ "constraint failed",
  101165. /* SQLITE_MISMATCH */ "datatype mismatch",
  101166. /* SQLITE_MISUSE */ "library routine called out of sequence",
  101167. /* SQLITE_NOLFS */ "large file support is disabled",
  101168. /* SQLITE_AUTH */ "authorization denied",
  101169. /* SQLITE_FORMAT */ "auxiliary database format error",
  101170. /* SQLITE_RANGE */ "bind or column index out of range",
  101171. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  101172. };
  101173. rc &= 0xff;
  101174. if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
  101175. return aMsg[rc];
  101176. }else{
  101177. return "unknown error";
  101178. }
  101179. }
  101180. /*
  101181. ** This routine implements a busy callback that sleeps and tries
  101182. ** again until a timeout value is reached. The timeout value is
  101183. ** an integer number of milliseconds passed in as the first
  101184. ** argument.
  101185. */
  101186. static int sqliteDefaultBusyCallback(
  101187. void *ptr, /* Database connection */
  101188. int count /* Number of times table has been busy */
  101189. ){
  101190. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  101191. static const u8 delays[] =
  101192. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  101193. static const u8 totals[] =
  101194. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  101195. # define NDELAY ArraySize(delays)
  101196. sqlite3 *db = (sqlite3 *)ptr;
  101197. int timeout = db->busyTimeout;
  101198. int delay, prior;
  101199. assert( count>=0 );
  101200. if( count < NDELAY ){
  101201. delay = delays[count];
  101202. prior = totals[count];
  101203. }else{
  101204. delay = delays[NDELAY-1];
  101205. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  101206. }
  101207. if( prior + delay > timeout ){
  101208. delay = timeout - prior;
  101209. if( delay<=0 ) return 0;
  101210. }
  101211. sqlite3OsSleep(db->pVfs, delay*1000);
  101212. return 1;
  101213. #else
  101214. sqlite3 *db = (sqlite3 *)ptr;
  101215. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  101216. if( (count+1)*1000 > timeout ){
  101217. return 0;
  101218. }
  101219. sqlite3OsSleep(db->pVfs, 1000000);
  101220. return 1;
  101221. #endif
  101222. }
  101223. /*
  101224. ** Invoke the given busy handler.
  101225. **
  101226. ** This routine is called when an operation failed with a lock.
  101227. ** If this routine returns non-zero, the lock is retried. If it
  101228. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  101229. */
  101230. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  101231. int rc;
  101232. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  101233. rc = p->xFunc(p->pArg, p->nBusy);
  101234. if( rc==0 ){
  101235. p->nBusy = -1;
  101236. }else{
  101237. p->nBusy++;
  101238. }
  101239. return rc;
  101240. }
  101241. /*
  101242. ** This routine sets the busy callback for an Sqlite database to the
  101243. ** given callback function with the given argument.
  101244. */
  101245. SQLITE_API int sqlite3_busy_handler(
  101246. sqlite3 *db,
  101247. int (*xBusy)(void*,int),
  101248. void *pArg
  101249. ){
  101250. sqlite3_mutex_enter(db->mutex);
  101251. db->busyHandler.xFunc = xBusy;
  101252. db->busyHandler.pArg = pArg;
  101253. db->busyHandler.nBusy = 0;
  101254. sqlite3_mutex_leave(db->mutex);
  101255. return SQLITE_OK;
  101256. }
  101257. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  101258. /*
  101259. ** This routine sets the progress callback for an Sqlite database to the
  101260. ** given callback function with the given argument. The progress callback will
  101261. ** be invoked every nOps opcodes.
  101262. */
  101263. SQLITE_API void sqlite3_progress_handler(
  101264. sqlite3 *db,
  101265. int nOps,
  101266. int (*xProgress)(void*),
  101267. void *pArg
  101268. ){
  101269. sqlite3_mutex_enter(db->mutex);
  101270. if( nOps>0 ){
  101271. db->xProgress = xProgress;
  101272. db->nProgressOps = nOps;
  101273. db->pProgressArg = pArg;
  101274. }else{
  101275. db->xProgress = 0;
  101276. db->nProgressOps = 0;
  101277. db->pProgressArg = 0;
  101278. }
  101279. sqlite3_mutex_leave(db->mutex);
  101280. }
  101281. #endif
  101282. /*
  101283. ** This routine installs a default busy handler that waits for the
  101284. ** specified number of milliseconds before returning 0.
  101285. */
  101286. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  101287. if( ms>0 ){
  101288. db->busyTimeout = ms;
  101289. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  101290. }else{
  101291. sqlite3_busy_handler(db, 0, 0);
  101292. }
  101293. return SQLITE_OK;
  101294. }
  101295. /*
  101296. ** Cause any pending operation to stop at its earliest opportunity.
  101297. */
  101298. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  101299. db->u1.isInterrupted = 1;
  101300. }
  101301. /*
  101302. ** This function is exactly the same as sqlite3_create_function(), except
  101303. ** that it is designed to be called by internal code. The difference is
  101304. ** that if a malloc() fails in sqlite3_create_function(), an error code
  101305. ** is returned and the mallocFailed flag cleared.
  101306. */
  101307. SQLITE_PRIVATE int sqlite3CreateFunc(
  101308. sqlite3 *db,
  101309. const char *zFunctionName,
  101310. int nArg,
  101311. int enc,
  101312. void *pUserData,
  101313. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101314. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101315. void (*xFinal)(sqlite3_context*),
  101316. FuncDestructor *pDestructor
  101317. ){
  101318. FuncDef *p;
  101319. int nName;
  101320. assert( sqlite3_mutex_held(db->mutex) );
  101321. if( zFunctionName==0 ||
  101322. (xFunc && (xFinal || xStep)) ||
  101323. (!xFunc && (xFinal && !xStep)) ||
  101324. (!xFunc && (!xFinal && xStep)) ||
  101325. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  101326. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  101327. return SQLITE_MISUSE_BKPT;
  101328. }
  101329. #ifndef SQLITE_OMIT_UTF16
  101330. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  101331. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  101332. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  101333. **
  101334. ** If SQLITE_ANY is specified, add three versions of the function
  101335. ** to the hash table.
  101336. */
  101337. if( enc==SQLITE_UTF16 ){
  101338. enc = SQLITE_UTF16NATIVE;
  101339. }else if( enc==SQLITE_ANY ){
  101340. int rc;
  101341. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  101342. pUserData, xFunc, xStep, xFinal, pDestructor);
  101343. if( rc==SQLITE_OK ){
  101344. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  101345. pUserData, xFunc, xStep, xFinal, pDestructor);
  101346. }
  101347. if( rc!=SQLITE_OK ){
  101348. return rc;
  101349. }
  101350. enc = SQLITE_UTF16BE;
  101351. }
  101352. #else
  101353. enc = SQLITE_UTF8;
  101354. #endif
  101355. /* Check if an existing function is being overridden or deleted. If so,
  101356. ** and there are active VMs, then return SQLITE_BUSY. If a function
  101357. ** is being overridden/deleted but there are no active VMs, allow the
  101358. ** operation to continue but invalidate all precompiled statements.
  101359. */
  101360. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  101361. if( p && p->iPrefEnc==enc && p->nArg==nArg ){
  101362. if( db->activeVdbeCnt ){
  101363. sqlite3Error(db, SQLITE_BUSY,
  101364. "unable to delete/modify user-function due to active statements");
  101365. assert( !db->mallocFailed );
  101366. return SQLITE_BUSY;
  101367. }else{
  101368. sqlite3ExpirePreparedStatements(db);
  101369. }
  101370. }
  101371. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  101372. assert(p || db->mallocFailed);
  101373. if( !p ){
  101374. return SQLITE_NOMEM;
  101375. }
  101376. /* If an older version of the function with a configured destructor is
  101377. ** being replaced invoke the destructor function here. */
  101378. functionDestroy(db, p);
  101379. if( pDestructor ){
  101380. pDestructor->nRef++;
  101381. }
  101382. p->pDestructor = pDestructor;
  101383. p->flags = 0;
  101384. p->xFunc = xFunc;
  101385. p->xStep = xStep;
  101386. p->xFinalize = xFinal;
  101387. p->pUserData = pUserData;
  101388. p->nArg = (u16)nArg;
  101389. return SQLITE_OK;
  101390. }
  101391. /*
  101392. ** Create new user functions.
  101393. */
  101394. SQLITE_API int sqlite3_create_function(
  101395. sqlite3 *db,
  101396. const char *zFunc,
  101397. int nArg,
  101398. int enc,
  101399. void *p,
  101400. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101401. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101402. void (*xFinal)(sqlite3_context*)
  101403. ){
  101404. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  101405. xFinal, 0);
  101406. }
  101407. SQLITE_API int sqlite3_create_function_v2(
  101408. sqlite3 *db,
  101409. const char *zFunc,
  101410. int nArg,
  101411. int enc,
  101412. void *p,
  101413. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  101414. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  101415. void (*xFinal)(sqlite3_context*),
  101416. void (*xDestroy)(void *)
  101417. ){
  101418. int rc = SQLITE_ERROR;
  101419. FuncDestructor *pArg = 0;
  101420. sqlite3_mutex_enter(db->mutex);
  101421. if( xDestroy ){
  101422. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  101423. if( !pArg ){
  101424. xDestroy(p);
  101425. goto out;
  101426. }
  101427. pArg->xDestroy = xDestroy;
  101428. pArg->pUserData = p;
  101429. }
  101430. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  101431. if( pArg && pArg->nRef==0 ){
  101432. assert( rc!=SQLITE_OK );
  101433. xDestroy(p);
  101434. sqlite3DbFree(db, pArg);
  101435. }
  101436. out:
  101437. rc = sqlite3ApiExit(db, rc);
  101438. sqlite3_mutex_leave(db->mutex);
  101439. return rc;
  101440. }
  101441. #ifndef SQLITE_OMIT_UTF16
  101442. SQLITE_API int sqlite3_create_function16(
  101443. sqlite3 *db,
  101444. const void *zFunctionName,
  101445. int nArg,
  101446. int eTextRep,
  101447. void *p,
  101448. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  101449. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  101450. void (*xFinal)(sqlite3_context*)
  101451. ){
  101452. int rc;
  101453. char *zFunc8;
  101454. sqlite3_mutex_enter(db->mutex);
  101455. assert( !db->mallocFailed );
  101456. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  101457. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  101458. sqlite3DbFree(db, zFunc8);
  101459. rc = sqlite3ApiExit(db, rc);
  101460. sqlite3_mutex_leave(db->mutex);
  101461. return rc;
  101462. }
  101463. #endif
  101464. /*
  101465. ** Declare that a function has been overloaded by a virtual table.
  101466. **
  101467. ** If the function already exists as a regular global function, then
  101468. ** this routine is a no-op. If the function does not exist, then create
  101469. ** a new one that always throws a run-time error.
  101470. **
  101471. ** When virtual tables intend to provide an overloaded function, they
  101472. ** should call this routine to make sure the global function exists.
  101473. ** A global function must exist in order for name resolution to work
  101474. ** properly.
  101475. */
  101476. SQLITE_API int sqlite3_overload_function(
  101477. sqlite3 *db,
  101478. const char *zName,
  101479. int nArg
  101480. ){
  101481. int nName = sqlite3Strlen30(zName);
  101482. int rc;
  101483. sqlite3_mutex_enter(db->mutex);
  101484. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  101485. sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  101486. 0, sqlite3InvalidFunction, 0, 0, 0);
  101487. }
  101488. rc = sqlite3ApiExit(db, SQLITE_OK);
  101489. sqlite3_mutex_leave(db->mutex);
  101490. return rc;
  101491. }
  101492. #ifndef SQLITE_OMIT_TRACE
  101493. /*
  101494. ** Register a trace function. The pArg from the previously registered trace
  101495. ** is returned.
  101496. **
  101497. ** A NULL trace function means that no tracing is executes. A non-NULL
  101498. ** trace is a pointer to a function that is invoked at the start of each
  101499. ** SQL statement.
  101500. */
  101501. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  101502. void *pOld;
  101503. sqlite3_mutex_enter(db->mutex);
  101504. pOld = db->pTraceArg;
  101505. db->xTrace = xTrace;
  101506. db->pTraceArg = pArg;
  101507. sqlite3_mutex_leave(db->mutex);
  101508. return pOld;
  101509. }
  101510. /*
  101511. ** Register a profile function. The pArg from the previously registered
  101512. ** profile function is returned.
  101513. **
  101514. ** A NULL profile function means that no profiling is executes. A non-NULL
  101515. ** profile is a pointer to a function that is invoked at the conclusion of
  101516. ** each SQL statement that is run.
  101517. */
  101518. SQLITE_API void *sqlite3_profile(
  101519. sqlite3 *db,
  101520. void (*xProfile)(void*,const char*,sqlite_uint64),
  101521. void *pArg
  101522. ){
  101523. void *pOld;
  101524. sqlite3_mutex_enter(db->mutex);
  101525. pOld = db->pProfileArg;
  101526. db->xProfile = xProfile;
  101527. db->pProfileArg = pArg;
  101528. sqlite3_mutex_leave(db->mutex);
  101529. return pOld;
  101530. }
  101531. #endif /* SQLITE_OMIT_TRACE */
  101532. /*** EXPERIMENTAL ***
  101533. **
  101534. ** Register a function to be invoked when a transaction comments.
  101535. ** If the invoked function returns non-zero, then the commit becomes a
  101536. ** rollback.
  101537. */
  101538. SQLITE_API void *sqlite3_commit_hook(
  101539. sqlite3 *db, /* Attach the hook to this database */
  101540. int (*xCallback)(void*), /* Function to invoke on each commit */
  101541. void *pArg /* Argument to the function */
  101542. ){
  101543. void *pOld;
  101544. sqlite3_mutex_enter(db->mutex);
  101545. pOld = db->pCommitArg;
  101546. db->xCommitCallback = xCallback;
  101547. db->pCommitArg = pArg;
  101548. sqlite3_mutex_leave(db->mutex);
  101549. return pOld;
  101550. }
  101551. /*
  101552. ** Register a callback to be invoked each time a row is updated,
  101553. ** inserted or deleted using this database connection.
  101554. */
  101555. SQLITE_API void *sqlite3_update_hook(
  101556. sqlite3 *db, /* Attach the hook to this database */
  101557. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  101558. void *pArg /* Argument to the function */
  101559. ){
  101560. void *pRet;
  101561. sqlite3_mutex_enter(db->mutex);
  101562. pRet = db->pUpdateArg;
  101563. db->xUpdateCallback = xCallback;
  101564. db->pUpdateArg = pArg;
  101565. sqlite3_mutex_leave(db->mutex);
  101566. return pRet;
  101567. }
  101568. /*
  101569. ** Register a callback to be invoked each time a transaction is rolled
  101570. ** back by this database connection.
  101571. */
  101572. SQLITE_API void *sqlite3_rollback_hook(
  101573. sqlite3 *db, /* Attach the hook to this database */
  101574. void (*xCallback)(void*), /* Callback function */
  101575. void *pArg /* Argument to the function */
  101576. ){
  101577. void *pRet;
  101578. sqlite3_mutex_enter(db->mutex);
  101579. pRet = db->pRollbackArg;
  101580. db->xRollbackCallback = xCallback;
  101581. db->pRollbackArg = pArg;
  101582. sqlite3_mutex_leave(db->mutex);
  101583. return pRet;
  101584. }
  101585. #ifndef SQLITE_OMIT_WAL
  101586. /*
  101587. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  101588. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  101589. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  101590. ** wal_autocheckpoint()).
  101591. */
  101592. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  101593. void *pClientData, /* Argument */
  101594. sqlite3 *db, /* Connection */
  101595. const char *zDb, /* Database */
  101596. int nFrame /* Size of WAL */
  101597. ){
  101598. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  101599. sqlite3BeginBenignMalloc();
  101600. sqlite3_wal_checkpoint(db, zDb);
  101601. sqlite3EndBenignMalloc();
  101602. }
  101603. return SQLITE_OK;
  101604. }
  101605. #endif /* SQLITE_OMIT_WAL */
  101606. /*
  101607. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  101608. ** a database after committing a transaction if there are nFrame or
  101609. ** more frames in the log file. Passing zero or a negative value as the
  101610. ** nFrame parameter disables automatic checkpoints entirely.
  101611. **
  101612. ** The callback registered by this function replaces any existing callback
  101613. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  101614. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  101615. ** configured by this function.
  101616. */
  101617. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  101618. #ifdef SQLITE_OMIT_WAL
  101619. UNUSED_PARAMETER(db);
  101620. UNUSED_PARAMETER(nFrame);
  101621. #else
  101622. if( nFrame>0 ){
  101623. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  101624. }else{
  101625. sqlite3_wal_hook(db, 0, 0);
  101626. }
  101627. #endif
  101628. return SQLITE_OK;
  101629. }
  101630. /*
  101631. ** Register a callback to be invoked each time a transaction is written
  101632. ** into the write-ahead-log by this database connection.
  101633. */
  101634. SQLITE_API void *sqlite3_wal_hook(
  101635. sqlite3 *db, /* Attach the hook to this db handle */
  101636. int(*xCallback)(void *, sqlite3*, const char*, int),
  101637. void *pArg /* First argument passed to xCallback() */
  101638. ){
  101639. #ifndef SQLITE_OMIT_WAL
  101640. void *pRet;
  101641. sqlite3_mutex_enter(db->mutex);
  101642. pRet = db->pWalArg;
  101643. db->xWalCallback = xCallback;
  101644. db->pWalArg = pArg;
  101645. sqlite3_mutex_leave(db->mutex);
  101646. return pRet;
  101647. #else
  101648. return 0;
  101649. #endif
  101650. }
  101651. /*
  101652. ** Checkpoint database zDb.
  101653. */
  101654. SQLITE_API int sqlite3_wal_checkpoint_v2(
  101655. sqlite3 *db, /* Database handle */
  101656. const char *zDb, /* Name of attached database (or NULL) */
  101657. int eMode, /* SQLITE_CHECKPOINT_* value */
  101658. int *pnLog, /* OUT: Size of WAL log in frames */
  101659. int *pnCkpt /* OUT: Total number of frames checkpointed */
  101660. ){
  101661. #ifdef SQLITE_OMIT_WAL
  101662. return SQLITE_OK;
  101663. #else
  101664. int rc; /* Return code */
  101665. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  101666. /* Initialize the output variables to -1 in case an error occurs. */
  101667. if( pnLog ) *pnLog = -1;
  101668. if( pnCkpt ) *pnCkpt = -1;
  101669. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  101670. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  101671. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  101672. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  101673. return SQLITE_MISUSE;
  101674. }
  101675. sqlite3_mutex_enter(db->mutex);
  101676. if( zDb && zDb[0] ){
  101677. iDb = sqlite3FindDbName(db, zDb);
  101678. }
  101679. if( iDb<0 ){
  101680. rc = SQLITE_ERROR;
  101681. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  101682. }else{
  101683. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  101684. sqlite3Error(db, rc, 0);
  101685. }
  101686. rc = sqlite3ApiExit(db, rc);
  101687. sqlite3_mutex_leave(db->mutex);
  101688. return rc;
  101689. #endif
  101690. }
  101691. /*
  101692. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  101693. ** to contains a zero-length string, all attached databases are
  101694. ** checkpointed.
  101695. */
  101696. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  101697. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  101698. }
  101699. #ifndef SQLITE_OMIT_WAL
  101700. /*
  101701. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  101702. ** not currently open in WAL mode.
  101703. **
  101704. ** If a transaction is open on the database being checkpointed, this
  101705. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  101706. ** an error occurs while running the checkpoint, an SQLite error code is
  101707. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  101708. **
  101709. ** The mutex on database handle db should be held by the caller. The mutex
  101710. ** associated with the specific b-tree being checkpointed is taken by
  101711. ** this function while the checkpoint is running.
  101712. **
  101713. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  101714. ** checkpointed. If an error is encountered it is returned immediately -
  101715. ** no attempt is made to checkpoint any remaining databases.
  101716. **
  101717. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  101718. */
  101719. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  101720. int rc = SQLITE_OK; /* Return code */
  101721. int i; /* Used to iterate through attached dbs */
  101722. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  101723. assert( sqlite3_mutex_held(db->mutex) );
  101724. assert( !pnLog || *pnLog==-1 );
  101725. assert( !pnCkpt || *pnCkpt==-1 );
  101726. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  101727. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  101728. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  101729. pnLog = 0;
  101730. pnCkpt = 0;
  101731. if( rc==SQLITE_BUSY ){
  101732. bBusy = 1;
  101733. rc = SQLITE_OK;
  101734. }
  101735. }
  101736. }
  101737. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  101738. }
  101739. #endif /* SQLITE_OMIT_WAL */
  101740. /*
  101741. ** This function returns true if main-memory should be used instead of
  101742. ** a temporary file for transient pager files and statement journals.
  101743. ** The value returned depends on the value of db->temp_store (runtime
  101744. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  101745. ** following table describes the relationship between these two values
  101746. ** and this functions return value.
  101747. **
  101748. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  101749. ** ----------------- -------------- ------------------------------
  101750. ** 0 any file (return 0)
  101751. ** 1 1 file (return 0)
  101752. ** 1 2 memory (return 1)
  101753. ** 1 0 file (return 0)
  101754. ** 2 1 file (return 0)
  101755. ** 2 2 memory (return 1)
  101756. ** 2 0 memory (return 1)
  101757. ** 3 any memory (return 1)
  101758. */
  101759. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  101760. #if SQLITE_TEMP_STORE==1
  101761. return ( db->temp_store==2 );
  101762. #endif
  101763. #if SQLITE_TEMP_STORE==2
  101764. return ( db->temp_store!=1 );
  101765. #endif
  101766. #if SQLITE_TEMP_STORE==3
  101767. return 1;
  101768. #endif
  101769. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  101770. return 0;
  101771. #endif
  101772. }
  101773. /*
  101774. ** Return UTF-8 encoded English language explanation of the most recent
  101775. ** error.
  101776. */
  101777. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  101778. const char *z;
  101779. if( !db ){
  101780. return sqlite3ErrStr(SQLITE_NOMEM);
  101781. }
  101782. if( !sqlite3SafetyCheckSickOrOk(db) ){
  101783. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  101784. }
  101785. sqlite3_mutex_enter(db->mutex);
  101786. if( db->mallocFailed ){
  101787. z = sqlite3ErrStr(SQLITE_NOMEM);
  101788. }else{
  101789. z = (char*)sqlite3_value_text(db->pErr);
  101790. assert( !db->mallocFailed );
  101791. if( z==0 ){
  101792. z = sqlite3ErrStr(db->errCode);
  101793. }
  101794. }
  101795. sqlite3_mutex_leave(db->mutex);
  101796. return z;
  101797. }
  101798. #ifndef SQLITE_OMIT_UTF16
  101799. /*
  101800. ** Return UTF-16 encoded English language explanation of the most recent
  101801. ** error.
  101802. */
  101803. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  101804. static const u16 outOfMem[] = {
  101805. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  101806. };
  101807. static const u16 misuse[] = {
  101808. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  101809. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  101810. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  101811. 'o', 'u', 't', ' ',
  101812. 'o', 'f', ' ',
  101813. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  101814. };
  101815. const void *z;
  101816. if( !db ){
  101817. return (void *)outOfMem;
  101818. }
  101819. if( !sqlite3SafetyCheckSickOrOk(db) ){
  101820. return (void *)misuse;
  101821. }
  101822. sqlite3_mutex_enter(db->mutex);
  101823. if( db->mallocFailed ){
  101824. z = (void *)outOfMem;
  101825. }else{
  101826. z = sqlite3_value_text16(db->pErr);
  101827. if( z==0 ){
  101828. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  101829. SQLITE_UTF8, SQLITE_STATIC);
  101830. z = sqlite3_value_text16(db->pErr);
  101831. }
  101832. /* A malloc() may have failed within the call to sqlite3_value_text16()
  101833. ** above. If this is the case, then the db->mallocFailed flag needs to
  101834. ** be cleared before returning. Do this directly, instead of via
  101835. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  101836. */
  101837. db->mallocFailed = 0;
  101838. }
  101839. sqlite3_mutex_leave(db->mutex);
  101840. return z;
  101841. }
  101842. #endif /* SQLITE_OMIT_UTF16 */
  101843. /*
  101844. ** Return the most recent error code generated by an SQLite routine. If NULL is
  101845. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  101846. */
  101847. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  101848. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  101849. return SQLITE_MISUSE_BKPT;
  101850. }
  101851. if( !db || db->mallocFailed ){
  101852. return SQLITE_NOMEM;
  101853. }
  101854. return db->errCode & db->errMask;
  101855. }
  101856. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  101857. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  101858. return SQLITE_MISUSE_BKPT;
  101859. }
  101860. if( !db || db->mallocFailed ){
  101861. return SQLITE_NOMEM;
  101862. }
  101863. return db->errCode;
  101864. }
  101865. /*
  101866. ** Create a new collating function for database "db". The name is zName
  101867. ** and the encoding is enc.
  101868. */
  101869. static int createCollation(
  101870. sqlite3* db,
  101871. const char *zName,
  101872. u8 enc,
  101873. u8 collType,
  101874. void* pCtx,
  101875. int(*xCompare)(void*,int,const void*,int,const void*),
  101876. void(*xDel)(void*)
  101877. ){
  101878. CollSeq *pColl;
  101879. int enc2;
  101880. int nName = sqlite3Strlen30(zName);
  101881. assert( sqlite3_mutex_held(db->mutex) );
  101882. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  101883. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  101884. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  101885. */
  101886. enc2 = enc;
  101887. testcase( enc2==SQLITE_UTF16 );
  101888. testcase( enc2==SQLITE_UTF16_ALIGNED );
  101889. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  101890. enc2 = SQLITE_UTF16NATIVE;
  101891. }
  101892. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  101893. return SQLITE_MISUSE_BKPT;
  101894. }
  101895. /* Check if this call is removing or replacing an existing collation
  101896. ** sequence. If so, and there are active VMs, return busy. If there
  101897. ** are no active VMs, invalidate any pre-compiled statements.
  101898. */
  101899. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  101900. if( pColl && pColl->xCmp ){
  101901. if( db->activeVdbeCnt ){
  101902. sqlite3Error(db, SQLITE_BUSY,
  101903. "unable to delete/modify collation sequence due to active statements");
  101904. return SQLITE_BUSY;
  101905. }
  101906. sqlite3ExpirePreparedStatements(db);
  101907. /* If collation sequence pColl was created directly by a call to
  101908. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  101909. ** then any copies made by synthCollSeq() need to be invalidated.
  101910. ** Also, collation destructor - CollSeq.xDel() - function may need
  101911. ** to be called.
  101912. */
  101913. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  101914. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  101915. int j;
  101916. for(j=0; j<3; j++){
  101917. CollSeq *p = &aColl[j];
  101918. if( p->enc==pColl->enc ){
  101919. if( p->xDel ){
  101920. p->xDel(p->pUser);
  101921. }
  101922. p->xCmp = 0;
  101923. }
  101924. }
  101925. }
  101926. }
  101927. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  101928. if( pColl==0 ) return SQLITE_NOMEM;
  101929. pColl->xCmp = xCompare;
  101930. pColl->pUser = pCtx;
  101931. pColl->xDel = xDel;
  101932. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  101933. pColl->type = collType;
  101934. sqlite3Error(db, SQLITE_OK, 0);
  101935. return SQLITE_OK;
  101936. }
  101937. /*
  101938. ** This array defines hard upper bounds on limit values. The
  101939. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  101940. ** #defines in sqlite3.h.
  101941. */
  101942. static const int aHardLimit[] = {
  101943. SQLITE_MAX_LENGTH,
  101944. SQLITE_MAX_SQL_LENGTH,
  101945. SQLITE_MAX_COLUMN,
  101946. SQLITE_MAX_EXPR_DEPTH,
  101947. SQLITE_MAX_COMPOUND_SELECT,
  101948. SQLITE_MAX_VDBE_OP,
  101949. SQLITE_MAX_FUNCTION_ARG,
  101950. SQLITE_MAX_ATTACHED,
  101951. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  101952. SQLITE_MAX_VARIABLE_NUMBER,
  101953. SQLITE_MAX_TRIGGER_DEPTH,
  101954. };
  101955. /*
  101956. ** Make sure the hard limits are set to reasonable values
  101957. */
  101958. #if SQLITE_MAX_LENGTH<100
  101959. # error SQLITE_MAX_LENGTH must be at least 100
  101960. #endif
  101961. #if SQLITE_MAX_SQL_LENGTH<100
  101962. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  101963. #endif
  101964. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  101965. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  101966. #endif
  101967. #if SQLITE_MAX_COMPOUND_SELECT<2
  101968. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  101969. #endif
  101970. #if SQLITE_MAX_VDBE_OP<40
  101971. # error SQLITE_MAX_VDBE_OP must be at least 40
  101972. #endif
  101973. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  101974. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  101975. #endif
  101976. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  101977. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  101978. #endif
  101979. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  101980. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  101981. #endif
  101982. #if SQLITE_MAX_COLUMN>32767
  101983. # error SQLITE_MAX_COLUMN must not exceed 32767
  101984. #endif
  101985. #if SQLITE_MAX_TRIGGER_DEPTH<1
  101986. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  101987. #endif
  101988. /*
  101989. ** Change the value of a limit. Report the old value.
  101990. ** If an invalid limit index is supplied, report -1.
  101991. ** Make no changes but still report the old value if the
  101992. ** new limit is negative.
  101993. **
  101994. ** A new lower limit does not shrink existing constructs.
  101995. ** It merely prevents new constructs that exceed the limit
  101996. ** from forming.
  101997. */
  101998. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  101999. int oldLimit;
  102000. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  102001. ** there is a hard upper bound set at compile-time by a C preprocessor
  102002. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  102003. ** "_MAX_".)
  102004. */
  102005. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  102006. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  102007. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  102008. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  102009. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  102010. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  102011. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  102012. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  102013. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  102014. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  102015. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  102016. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  102017. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  102018. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  102019. return -1;
  102020. }
  102021. oldLimit = db->aLimit[limitId];
  102022. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  102023. if( newLimit>aHardLimit[limitId] ){
  102024. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  102025. }
  102026. db->aLimit[limitId] = newLimit;
  102027. }
  102028. return oldLimit; /* IMP: R-53341-35419 */
  102029. }
  102030. /*
  102031. ** This routine does the work of opening a database on behalf of
  102032. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  102033. ** is UTF-8 encoded.
  102034. */
  102035. static int openDatabase(
  102036. const char *zFilename, /* Database filename UTF-8 encoded */
  102037. sqlite3 **ppDb, /* OUT: Returned database handle */
  102038. unsigned flags, /* Operational flags */
  102039. const char *zVfs /* Name of the VFS to use */
  102040. ){
  102041. sqlite3 *db;
  102042. int rc;
  102043. int isThreadsafe;
  102044. *ppDb = 0;
  102045. #ifndef SQLITE_OMIT_AUTOINIT
  102046. rc = sqlite3_initialize();
  102047. if( rc ) return rc;
  102048. #endif
  102049. /* Only allow sensible combinations of bits in the flags argument.
  102050. ** Throw an error if any non-sense combination is used. If we
  102051. ** do not block illegal combinations here, it could trigger
  102052. ** assert() statements in deeper layers. Sensible combinations
  102053. ** are:
  102054. **
  102055. ** 1: SQLITE_OPEN_READONLY
  102056. ** 2: SQLITE_OPEN_READWRITE
  102057. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  102058. */
  102059. assert( SQLITE_OPEN_READONLY == 0x01 );
  102060. assert( SQLITE_OPEN_READWRITE == 0x02 );
  102061. assert( SQLITE_OPEN_CREATE == 0x04 );
  102062. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  102063. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  102064. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  102065. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
  102066. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  102067. isThreadsafe = 0;
  102068. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  102069. isThreadsafe = 0;
  102070. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  102071. isThreadsafe = 1;
  102072. }else{
  102073. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  102074. }
  102075. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  102076. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  102077. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  102078. flags |= SQLITE_OPEN_SHAREDCACHE;
  102079. }
  102080. /* Remove harmful bits from the flags parameter
  102081. **
  102082. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  102083. ** dealt with in the previous code block. Besides these, the only
  102084. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  102085. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  102086. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  102087. ** off all other flags.
  102088. */
  102089. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  102090. SQLITE_OPEN_EXCLUSIVE |
  102091. SQLITE_OPEN_MAIN_DB |
  102092. SQLITE_OPEN_TEMP_DB |
  102093. SQLITE_OPEN_TRANSIENT_DB |
  102094. SQLITE_OPEN_MAIN_JOURNAL |
  102095. SQLITE_OPEN_TEMP_JOURNAL |
  102096. SQLITE_OPEN_SUBJOURNAL |
  102097. SQLITE_OPEN_MASTER_JOURNAL |
  102098. SQLITE_OPEN_NOMUTEX |
  102099. SQLITE_OPEN_FULLMUTEX |
  102100. SQLITE_OPEN_WAL
  102101. );
  102102. /* Allocate the sqlite data structure */
  102103. db = sqlite3MallocZero( sizeof(sqlite3) );
  102104. if( db==0 ) goto opendb_out;
  102105. if( isThreadsafe ){
  102106. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  102107. if( db->mutex==0 ){
  102108. sqlite3_free(db);
  102109. db = 0;
  102110. goto opendb_out;
  102111. }
  102112. }
  102113. sqlite3_mutex_enter(db->mutex);
  102114. db->errMask = 0xff;
  102115. db->nDb = 2;
  102116. db->magic = SQLITE_MAGIC_BUSY;
  102117. db->aDb = db->aDbStatic;
  102118. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  102119. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  102120. db->autoCommit = 1;
  102121. db->nextAutovac = -1;
  102122. db->nextPagesize = 0;
  102123. db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
  102124. #if SQLITE_DEFAULT_FILE_FORMAT<4
  102125. | SQLITE_LegacyFileFmt
  102126. #endif
  102127. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  102128. | SQLITE_LoadExtension
  102129. #endif
  102130. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  102131. | SQLITE_RecTriggers
  102132. #endif
  102133. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  102134. | SQLITE_ForeignKeys
  102135. #endif
  102136. ;
  102137. sqlite3HashInit(&db->aCollSeq);
  102138. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102139. sqlite3HashInit(&db->aModule);
  102140. #endif
  102141. db->pVfs = sqlite3_vfs_find(zVfs);
  102142. if( !db->pVfs ){
  102143. rc = SQLITE_ERROR;
  102144. sqlite3Error(db, rc, "no such vfs: %s", zVfs);
  102145. goto opendb_out;
  102146. }
  102147. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  102148. ** and UTF-16, so add a version for each to avoid any unnecessary
  102149. ** conversions. The only error that can occur here is a malloc() failure.
  102150. */
  102151. createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
  102152. binCollFunc, 0);
  102153. createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
  102154. binCollFunc, 0);
  102155. createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
  102156. binCollFunc, 0);
  102157. createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
  102158. binCollFunc, 0);
  102159. if( db->mallocFailed ){
  102160. goto opendb_out;
  102161. }
  102162. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  102163. assert( db->pDfltColl!=0 );
  102164. /* Also add a UTF-8 case-insensitive collation sequence. */
  102165. createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
  102166. nocaseCollatingFunc, 0);
  102167. /* Open the backend database driver */
  102168. db->openFlags = flags;
  102169. rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
  102170. flags | SQLITE_OPEN_MAIN_DB);
  102171. if( rc!=SQLITE_OK ){
  102172. if( rc==SQLITE_IOERR_NOMEM ){
  102173. rc = SQLITE_NOMEM;
  102174. }
  102175. sqlite3Error(db, rc, 0);
  102176. goto opendb_out;
  102177. }
  102178. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  102179. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  102180. /* The default safety_level for the main database is 'full'; for the temp
  102181. ** database it is 'NONE'. This matches the pager layer defaults.
  102182. */
  102183. db->aDb[0].zName = "main";
  102184. db->aDb[0].safety_level = 3;
  102185. db->aDb[1].zName = "temp";
  102186. db->aDb[1].safety_level = 1;
  102187. db->magic = SQLITE_MAGIC_OPEN;
  102188. if( db->mallocFailed ){
  102189. goto opendb_out;
  102190. }
  102191. /* Register all built-in functions, but do not attempt to read the
  102192. ** database schema yet. This is delayed until the first time the database
  102193. ** is accessed.
  102194. */
  102195. sqlite3Error(db, SQLITE_OK, 0);
  102196. sqlite3RegisterBuiltinFunctions(db);
  102197. /* Load automatic extensions - extensions that have been registered
  102198. ** using the sqlite3_automatic_extension() API.
  102199. */
  102200. sqlite3AutoLoadExtensions(db);
  102201. rc = sqlite3_errcode(db);
  102202. if( rc!=SQLITE_OK ){
  102203. goto opendb_out;
  102204. }
  102205. #ifdef SQLITE_ENABLE_FTS1
  102206. if( !db->mallocFailed ){
  102207. extern int sqlite3Fts1Init(sqlite3*);
  102208. rc = sqlite3Fts1Init(db);
  102209. }
  102210. #endif
  102211. #ifdef SQLITE_ENABLE_FTS2
  102212. if( !db->mallocFailed && rc==SQLITE_OK ){
  102213. extern int sqlite3Fts2Init(sqlite3*);
  102214. rc = sqlite3Fts2Init(db);
  102215. }
  102216. #endif
  102217. #ifdef SQLITE_ENABLE_FTS3
  102218. if( !db->mallocFailed && rc==SQLITE_OK ){
  102219. rc = sqlite3Fts3Init(db);
  102220. }
  102221. #endif
  102222. #ifdef SQLITE_ENABLE_ICU
  102223. if( !db->mallocFailed && rc==SQLITE_OK ){
  102224. rc = sqlite3IcuInit(db);
  102225. }
  102226. #endif
  102227. #ifdef SQLITE_ENABLE_RTREE
  102228. if( !db->mallocFailed && rc==SQLITE_OK){
  102229. rc = sqlite3RtreeInit(db);
  102230. }
  102231. #endif
  102232. sqlite3Error(db, rc, 0);
  102233. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  102234. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  102235. ** mode. Doing nothing at all also makes NORMAL the default.
  102236. */
  102237. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  102238. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  102239. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  102240. SQLITE_DEFAULT_LOCKING_MODE);
  102241. #endif
  102242. /* Enable the lookaside-malloc subsystem */
  102243. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  102244. sqlite3GlobalConfig.nLookaside);
  102245. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  102246. opendb_out:
  102247. if( db ){
  102248. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  102249. sqlite3_mutex_leave(db->mutex);
  102250. }
  102251. rc = sqlite3_errcode(db);
  102252. if( rc==SQLITE_NOMEM ){
  102253. sqlite3_close(db);
  102254. db = 0;
  102255. }else if( rc!=SQLITE_OK ){
  102256. db->magic = SQLITE_MAGIC_SICK;
  102257. }
  102258. *ppDb = db;
  102259. return sqlite3ApiExit(0, rc);
  102260. }
  102261. /*
  102262. ** Open a new database handle.
  102263. */
  102264. SQLITE_API int sqlite3_open(
  102265. const char *zFilename,
  102266. sqlite3 **ppDb
  102267. ){
  102268. return openDatabase(zFilename, ppDb,
  102269. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  102270. }
  102271. SQLITE_API int sqlite3_open_v2(
  102272. const char *filename, /* Database filename (UTF-8) */
  102273. sqlite3 **ppDb, /* OUT: SQLite db handle */
  102274. int flags, /* Flags */
  102275. const char *zVfs /* Name of VFS module to use */
  102276. ){
  102277. return openDatabase(filename, ppDb, flags, zVfs);
  102278. }
  102279. #ifndef SQLITE_OMIT_UTF16
  102280. /*
  102281. ** Open a new database handle.
  102282. */
  102283. SQLITE_API int sqlite3_open16(
  102284. const void *zFilename,
  102285. sqlite3 **ppDb
  102286. ){
  102287. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  102288. sqlite3_value *pVal;
  102289. int rc;
  102290. assert( zFilename );
  102291. assert( ppDb );
  102292. *ppDb = 0;
  102293. #ifndef SQLITE_OMIT_AUTOINIT
  102294. rc = sqlite3_initialize();
  102295. if( rc ) return rc;
  102296. #endif
  102297. pVal = sqlite3ValueNew(0);
  102298. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  102299. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  102300. if( zFilename8 ){
  102301. rc = openDatabase(zFilename8, ppDb,
  102302. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  102303. assert( *ppDb || rc==SQLITE_NOMEM );
  102304. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  102305. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  102306. }
  102307. }else{
  102308. rc = SQLITE_NOMEM;
  102309. }
  102310. sqlite3ValueFree(pVal);
  102311. return sqlite3ApiExit(0, rc);
  102312. }
  102313. #endif /* SQLITE_OMIT_UTF16 */
  102314. /*
  102315. ** Register a new collation sequence with the database handle db.
  102316. */
  102317. SQLITE_API int sqlite3_create_collation(
  102318. sqlite3* db,
  102319. const char *zName,
  102320. int enc,
  102321. void* pCtx,
  102322. int(*xCompare)(void*,int,const void*,int,const void*)
  102323. ){
  102324. int rc;
  102325. sqlite3_mutex_enter(db->mutex);
  102326. assert( !db->mallocFailed );
  102327. rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
  102328. rc = sqlite3ApiExit(db, rc);
  102329. sqlite3_mutex_leave(db->mutex);
  102330. return rc;
  102331. }
  102332. /*
  102333. ** Register a new collation sequence with the database handle db.
  102334. */
  102335. SQLITE_API int sqlite3_create_collation_v2(
  102336. sqlite3* db,
  102337. const char *zName,
  102338. int enc,
  102339. void* pCtx,
  102340. int(*xCompare)(void*,int,const void*,int,const void*),
  102341. void(*xDel)(void*)
  102342. ){
  102343. int rc;
  102344. sqlite3_mutex_enter(db->mutex);
  102345. assert( !db->mallocFailed );
  102346. rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
  102347. rc = sqlite3ApiExit(db, rc);
  102348. sqlite3_mutex_leave(db->mutex);
  102349. return rc;
  102350. }
  102351. #ifndef SQLITE_OMIT_UTF16
  102352. /*
  102353. ** Register a new collation sequence with the database handle db.
  102354. */
  102355. SQLITE_API int sqlite3_create_collation16(
  102356. sqlite3* db,
  102357. const void *zName,
  102358. int enc,
  102359. void* pCtx,
  102360. int(*xCompare)(void*,int,const void*,int,const void*)
  102361. ){
  102362. int rc = SQLITE_OK;
  102363. char *zName8;
  102364. sqlite3_mutex_enter(db->mutex);
  102365. assert( !db->mallocFailed );
  102366. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  102367. if( zName8 ){
  102368. rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
  102369. sqlite3DbFree(db, zName8);
  102370. }
  102371. rc = sqlite3ApiExit(db, rc);
  102372. sqlite3_mutex_leave(db->mutex);
  102373. return rc;
  102374. }
  102375. #endif /* SQLITE_OMIT_UTF16 */
  102376. /*
  102377. ** Register a collation sequence factory callback with the database handle
  102378. ** db. Replace any previously installed collation sequence factory.
  102379. */
  102380. SQLITE_API int sqlite3_collation_needed(
  102381. sqlite3 *db,
  102382. void *pCollNeededArg,
  102383. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  102384. ){
  102385. sqlite3_mutex_enter(db->mutex);
  102386. db->xCollNeeded = xCollNeeded;
  102387. db->xCollNeeded16 = 0;
  102388. db->pCollNeededArg = pCollNeededArg;
  102389. sqlite3_mutex_leave(db->mutex);
  102390. return SQLITE_OK;
  102391. }
  102392. #ifndef SQLITE_OMIT_UTF16
  102393. /*
  102394. ** Register a collation sequence factory callback with the database handle
  102395. ** db. Replace any previously installed collation sequence factory.
  102396. */
  102397. SQLITE_API int sqlite3_collation_needed16(
  102398. sqlite3 *db,
  102399. void *pCollNeededArg,
  102400. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  102401. ){
  102402. sqlite3_mutex_enter(db->mutex);
  102403. db->xCollNeeded = 0;
  102404. db->xCollNeeded16 = xCollNeeded16;
  102405. db->pCollNeededArg = pCollNeededArg;
  102406. sqlite3_mutex_leave(db->mutex);
  102407. return SQLITE_OK;
  102408. }
  102409. #endif /* SQLITE_OMIT_UTF16 */
  102410. #ifndef SQLITE_OMIT_DEPRECATED
  102411. /*
  102412. ** This function is now an anachronism. It used to be used to recover from a
  102413. ** malloc() failure, but SQLite now does this automatically.
  102414. */
  102415. SQLITE_API int sqlite3_global_recover(void){
  102416. return SQLITE_OK;
  102417. }
  102418. #endif
  102419. /*
  102420. ** Test to see whether or not the database connection is in autocommit
  102421. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  102422. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  102423. ** by the next COMMIT or ROLLBACK.
  102424. **
  102425. ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  102426. */
  102427. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  102428. return db->autoCommit;
  102429. }
  102430. /*
  102431. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  102432. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  102433. ** constants. They server two purposes:
  102434. **
  102435. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  102436. ** to detect when version error conditions occurs.
  102437. **
  102438. ** 2. Invoke sqlite3_log() to provide the source code location where
  102439. ** a low-level error is first detected.
  102440. */
  102441. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  102442. testcase( sqlite3GlobalConfig.xLog!=0 );
  102443. sqlite3_log(SQLITE_CORRUPT,
  102444. "database corruption at line %d of [%.10s]",
  102445. lineno, 20+sqlite3_sourceid());
  102446. return SQLITE_CORRUPT;
  102447. }
  102448. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  102449. testcase( sqlite3GlobalConfig.xLog!=0 );
  102450. sqlite3_log(SQLITE_MISUSE,
  102451. "misuse at line %d of [%.10s]",
  102452. lineno, 20+sqlite3_sourceid());
  102453. return SQLITE_MISUSE;
  102454. }
  102455. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  102456. testcase( sqlite3GlobalConfig.xLog!=0 );
  102457. sqlite3_log(SQLITE_CANTOPEN,
  102458. "cannot open file at line %d of [%.10s]",
  102459. lineno, 20+sqlite3_sourceid());
  102460. return SQLITE_CANTOPEN;
  102461. }
  102462. #ifndef SQLITE_OMIT_DEPRECATED
  102463. /*
  102464. ** This is a convenience routine that makes sure that all thread-specific
  102465. ** data for this thread has been deallocated.
  102466. **
  102467. ** SQLite no longer uses thread-specific data so this routine is now a
  102468. ** no-op. It is retained for historical compatibility.
  102469. */
  102470. SQLITE_API void sqlite3_thread_cleanup(void){
  102471. }
  102472. #endif
  102473. /*
  102474. ** Return meta information about a specific column of a database table.
  102475. ** See comment in sqlite3.h (sqlite.h.in) for details.
  102476. */
  102477. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  102478. SQLITE_API int sqlite3_table_column_metadata(
  102479. sqlite3 *db, /* Connection handle */
  102480. const char *zDbName, /* Database name or NULL */
  102481. const char *zTableName, /* Table name */
  102482. const char *zColumnName, /* Column name */
  102483. char const **pzDataType, /* OUTPUT: Declared data type */
  102484. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  102485. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  102486. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  102487. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  102488. ){
  102489. int rc;
  102490. char *zErrMsg = 0;
  102491. Table *pTab = 0;
  102492. Column *pCol = 0;
  102493. int iCol;
  102494. char const *zDataType = 0;
  102495. char const *zCollSeq = 0;
  102496. int notnull = 0;
  102497. int primarykey = 0;
  102498. int autoinc = 0;
  102499. /* Ensure the database schema has been loaded */
  102500. sqlite3_mutex_enter(db->mutex);
  102501. sqlite3BtreeEnterAll(db);
  102502. rc = sqlite3Init(db, &zErrMsg);
  102503. if( SQLITE_OK!=rc ){
  102504. goto error_out;
  102505. }
  102506. /* Locate the table in question */
  102507. pTab = sqlite3FindTable(db, zTableName, zDbName);
  102508. if( !pTab || pTab->pSelect ){
  102509. pTab = 0;
  102510. goto error_out;
  102511. }
  102512. /* Find the column for which info is requested */
  102513. if( sqlite3IsRowid(zColumnName) ){
  102514. iCol = pTab->iPKey;
  102515. if( iCol>=0 ){
  102516. pCol = &pTab->aCol[iCol];
  102517. }
  102518. }else{
  102519. for(iCol=0; iCol<pTab->nCol; iCol++){
  102520. pCol = &pTab->aCol[iCol];
  102521. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  102522. break;
  102523. }
  102524. }
  102525. if( iCol==pTab->nCol ){
  102526. pTab = 0;
  102527. goto error_out;
  102528. }
  102529. }
  102530. /* The following block stores the meta information that will be returned
  102531. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  102532. ** and autoinc. At this point there are two possibilities:
  102533. **
  102534. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  102535. ** and there is no explicitly declared IPK column.
  102536. **
  102537. ** 2. The table is not a view and the column name identified an
  102538. ** explicitly declared column. Copy meta information from *pCol.
  102539. */
  102540. if( pCol ){
  102541. zDataType = pCol->zType;
  102542. zCollSeq = pCol->zColl;
  102543. notnull = pCol->notNull!=0;
  102544. primarykey = pCol->isPrimKey!=0;
  102545. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  102546. }else{
  102547. zDataType = "INTEGER";
  102548. primarykey = 1;
  102549. }
  102550. if( !zCollSeq ){
  102551. zCollSeq = "BINARY";
  102552. }
  102553. error_out:
  102554. sqlite3BtreeLeaveAll(db);
  102555. /* Whether the function call succeeded or failed, set the output parameters
  102556. ** to whatever their local counterparts contain. If an error did occur,
  102557. ** this has the effect of zeroing all output parameters.
  102558. */
  102559. if( pzDataType ) *pzDataType = zDataType;
  102560. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  102561. if( pNotNull ) *pNotNull = notnull;
  102562. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  102563. if( pAutoinc ) *pAutoinc = autoinc;
  102564. if( SQLITE_OK==rc && !pTab ){
  102565. sqlite3DbFree(db, zErrMsg);
  102566. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  102567. zColumnName);
  102568. rc = SQLITE_ERROR;
  102569. }
  102570. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  102571. sqlite3DbFree(db, zErrMsg);
  102572. rc = sqlite3ApiExit(db, rc);
  102573. sqlite3_mutex_leave(db->mutex);
  102574. return rc;
  102575. }
  102576. #endif
  102577. /*
  102578. ** Sleep for a little while. Return the amount of time slept.
  102579. */
  102580. SQLITE_API int sqlite3_sleep(int ms){
  102581. sqlite3_vfs *pVfs;
  102582. int rc;
  102583. pVfs = sqlite3_vfs_find(0);
  102584. if( pVfs==0 ) return 0;
  102585. /* This function works in milliseconds, but the underlying OsSleep()
  102586. ** API uses microseconds. Hence the 1000's.
  102587. */
  102588. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  102589. return rc;
  102590. }
  102591. /*
  102592. ** Enable or disable the extended result codes.
  102593. */
  102594. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  102595. sqlite3_mutex_enter(db->mutex);
  102596. db->errMask = onoff ? 0xffffffff : 0xff;
  102597. sqlite3_mutex_leave(db->mutex);
  102598. return SQLITE_OK;
  102599. }
  102600. /*
  102601. ** Invoke the xFileControl method on a particular database.
  102602. */
  102603. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  102604. int rc = SQLITE_ERROR;
  102605. int iDb;
  102606. sqlite3_mutex_enter(db->mutex);
  102607. if( zDbName==0 ){
  102608. iDb = 0;
  102609. }else{
  102610. for(iDb=0; iDb<db->nDb; iDb++){
  102611. if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
  102612. }
  102613. }
  102614. if( iDb<db->nDb ){
  102615. Btree *pBtree = db->aDb[iDb].pBt;
  102616. if( pBtree ){
  102617. Pager *pPager;
  102618. sqlite3_file *fd;
  102619. sqlite3BtreeEnter(pBtree);
  102620. pPager = sqlite3BtreePager(pBtree);
  102621. assert( pPager!=0 );
  102622. fd = sqlite3PagerFile(pPager);
  102623. assert( fd!=0 );
  102624. if( op==SQLITE_FCNTL_FILE_POINTER ){
  102625. *(sqlite3_file**)pArg = fd;
  102626. rc = SQLITE_OK;
  102627. }else if( fd->pMethods ){
  102628. rc = sqlite3OsFileControl(fd, op, pArg);
  102629. }else{
  102630. rc = SQLITE_NOTFOUND;
  102631. }
  102632. sqlite3BtreeLeave(pBtree);
  102633. }
  102634. }
  102635. sqlite3_mutex_leave(db->mutex);
  102636. return rc;
  102637. }
  102638. /*
  102639. ** Interface to the testing logic.
  102640. */
  102641. SQLITE_API int sqlite3_test_control(int op, ...){
  102642. int rc = 0;
  102643. #ifndef SQLITE_OMIT_BUILTIN_TEST
  102644. va_list ap;
  102645. va_start(ap, op);
  102646. switch( op ){
  102647. /*
  102648. ** Save the current state of the PRNG.
  102649. */
  102650. case SQLITE_TESTCTRL_PRNG_SAVE: {
  102651. sqlite3PrngSaveState();
  102652. break;
  102653. }
  102654. /*
  102655. ** Restore the state of the PRNG to the last state saved using
  102656. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  102657. ** this verb acts like PRNG_RESET.
  102658. */
  102659. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  102660. sqlite3PrngRestoreState();
  102661. break;
  102662. }
  102663. /*
  102664. ** Reset the PRNG back to its uninitialized state. The next call
  102665. ** to sqlite3_randomness() will reseed the PRNG using a single call
  102666. ** to the xRandomness method of the default VFS.
  102667. */
  102668. case SQLITE_TESTCTRL_PRNG_RESET: {
  102669. sqlite3PrngResetState();
  102670. break;
  102671. }
  102672. /*
  102673. ** sqlite3_test_control(BITVEC_TEST, size, program)
  102674. **
  102675. ** Run a test against a Bitvec object of size. The program argument
  102676. ** is an array of integers that defines the test. Return -1 on a
  102677. ** memory allocation error, 0 on success, or non-zero for an error.
  102678. ** See the sqlite3BitvecBuiltinTest() for additional information.
  102679. */
  102680. case SQLITE_TESTCTRL_BITVEC_TEST: {
  102681. int sz = va_arg(ap, int);
  102682. int *aProg = va_arg(ap, int*);
  102683. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  102684. break;
  102685. }
  102686. /*
  102687. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  102688. **
  102689. ** Register hooks to call to indicate which malloc() failures
  102690. ** are benign.
  102691. */
  102692. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  102693. typedef void (*void_function)(void);
  102694. void_function xBenignBegin;
  102695. void_function xBenignEnd;
  102696. xBenignBegin = va_arg(ap, void_function);
  102697. xBenignEnd = va_arg(ap, void_function);
  102698. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  102699. break;
  102700. }
  102701. /*
  102702. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  102703. **
  102704. ** Set the PENDING byte to the value in the argument, if X>0.
  102705. ** Make no changes if X==0. Return the value of the pending byte
  102706. ** as it existing before this routine was called.
  102707. **
  102708. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  102709. ** an incompatible database file format. Changing the PENDING byte
  102710. ** while any database connection is open results in undefined and
  102711. ** dileterious behavior.
  102712. */
  102713. case SQLITE_TESTCTRL_PENDING_BYTE: {
  102714. rc = PENDING_BYTE;
  102715. #ifndef SQLITE_OMIT_WSD
  102716. {
  102717. unsigned int newVal = va_arg(ap, unsigned int);
  102718. if( newVal ) sqlite3PendingByte = newVal;
  102719. }
  102720. #endif
  102721. break;
  102722. }
  102723. /*
  102724. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  102725. **
  102726. ** This action provides a run-time test to see whether or not
  102727. ** assert() was enabled at compile-time. If X is true and assert()
  102728. ** is enabled, then the return value is true. If X is true and
  102729. ** assert() is disabled, then the return value is zero. If X is
  102730. ** false and assert() is enabled, then the assertion fires and the
  102731. ** process aborts. If X is false and assert() is disabled, then the
  102732. ** return value is zero.
  102733. */
  102734. case SQLITE_TESTCTRL_ASSERT: {
  102735. volatile int x = 0;
  102736. assert( (x = va_arg(ap,int))!=0 );
  102737. rc = x;
  102738. break;
  102739. }
  102740. /*
  102741. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  102742. **
  102743. ** This action provides a run-time test to see how the ALWAYS and
  102744. ** NEVER macros were defined at compile-time.
  102745. **
  102746. ** The return value is ALWAYS(X).
  102747. **
  102748. ** The recommended test is X==2. If the return value is 2, that means
  102749. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  102750. ** default setting. If the return value is 1, then ALWAYS() is either
  102751. ** hard-coded to true or else it asserts if its argument is false.
  102752. ** The first behavior (hard-coded to true) is the case if
  102753. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  102754. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  102755. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  102756. **
  102757. ** The run-time test procedure might look something like this:
  102758. **
  102759. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  102760. ** // ALWAYS() and NEVER() are no-op pass-through macros
  102761. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  102762. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  102763. ** }else{
  102764. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  102765. ** }
  102766. */
  102767. case SQLITE_TESTCTRL_ALWAYS: {
  102768. int x = va_arg(ap,int);
  102769. rc = ALWAYS(x);
  102770. break;
  102771. }
  102772. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  102773. **
  102774. ** Set the nReserve size to N for the main database on the database
  102775. ** connection db.
  102776. */
  102777. case SQLITE_TESTCTRL_RESERVE: {
  102778. sqlite3 *db = va_arg(ap, sqlite3*);
  102779. int x = va_arg(ap,int);
  102780. sqlite3_mutex_enter(db->mutex);
  102781. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  102782. sqlite3_mutex_leave(db->mutex);
  102783. break;
  102784. }
  102785. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  102786. **
  102787. ** Enable or disable various optimizations for testing purposes. The
  102788. ** argument N is a bitmask of optimizations to be disabled. For normal
  102789. ** operation N should be 0. The idea is that a test program (like the
  102790. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  102791. ** with various optimizations disabled to verify that the same answer
  102792. ** is obtained in every case.
  102793. */
  102794. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  102795. sqlite3 *db = va_arg(ap, sqlite3*);
  102796. int x = va_arg(ap,int);
  102797. db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
  102798. break;
  102799. }
  102800. #ifdef SQLITE_N_KEYWORD
  102801. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  102802. **
  102803. ** If zWord is a keyword recognized by the parser, then return the
  102804. ** number of keywords. Or if zWord is not a keyword, return 0.
  102805. **
  102806. ** This test feature is only available in the amalgamation since
  102807. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  102808. ** is built using separate source files.
  102809. */
  102810. case SQLITE_TESTCTRL_ISKEYWORD: {
  102811. const char *zWord = va_arg(ap, const char*);
  102812. int n = sqlite3Strlen30(zWord);
  102813. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  102814. break;
  102815. }
  102816. #endif
  102817. /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
  102818. **
  102819. ** Return the size of a pcache header in bytes.
  102820. */
  102821. case SQLITE_TESTCTRL_PGHDRSZ: {
  102822. rc = sizeof(PgHdr);
  102823. break;
  102824. }
  102825. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  102826. **
  102827. ** Pass pFree into sqlite3ScratchFree().
  102828. ** If sz>0 then allocate a scratch buffer into pNew.
  102829. */
  102830. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  102831. void *pFree, **ppNew;
  102832. int sz;
  102833. sz = va_arg(ap, int);
  102834. ppNew = va_arg(ap, void**);
  102835. pFree = va_arg(ap, void*);
  102836. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  102837. sqlite3ScratchFree(pFree);
  102838. break;
  102839. }
  102840. }
  102841. va_end(ap);
  102842. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  102843. return rc;
  102844. }
  102845. /************** End of main.c ************************************************/
  102846. /************** Begin file notify.c ******************************************/
  102847. /*
  102848. ** 2009 March 3
  102849. **
  102850. ** The author disclaims copyright to this source code. In place of
  102851. ** a legal notice, here is a blessing:
  102852. **
  102853. ** May you do good and not evil.
  102854. ** May you find forgiveness for yourself and forgive others.
  102855. ** May you share freely, never taking more than you give.
  102856. **
  102857. *************************************************************************
  102858. **
  102859. ** This file contains the implementation of the sqlite3_unlock_notify()
  102860. ** API method and its associated functionality.
  102861. */
  102862. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  102863. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  102864. /*
  102865. ** Public interfaces:
  102866. **
  102867. ** sqlite3ConnectionBlocked()
  102868. ** sqlite3ConnectionUnlocked()
  102869. ** sqlite3ConnectionClosed()
  102870. ** sqlite3_unlock_notify()
  102871. */
  102872. #define assertMutexHeld() \
  102873. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  102874. /*
  102875. ** Head of a linked list of all sqlite3 objects created by this process
  102876. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  102877. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  102878. ** mutex is held.
  102879. */
  102880. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  102881. #ifndef NDEBUG
  102882. /*
  102883. ** This function is a complex assert() that verifies the following
  102884. ** properties of the blocked connections list:
  102885. **
  102886. ** 1) Each entry in the list has a non-NULL value for either
  102887. ** pUnlockConnection or pBlockingConnection, or both.
  102888. **
  102889. ** 2) All entries in the list that share a common value for
  102890. ** xUnlockNotify are grouped together.
  102891. **
  102892. ** 3) If the argument db is not NULL, then none of the entries in the
  102893. ** blocked connections list have pUnlockConnection or pBlockingConnection
  102894. ** set to db. This is used when closing connection db.
  102895. */
  102896. static void checkListProperties(sqlite3 *db){
  102897. sqlite3 *p;
  102898. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  102899. int seen = 0;
  102900. sqlite3 *p2;
  102901. /* Verify property (1) */
  102902. assert( p->pUnlockConnection || p->pBlockingConnection );
  102903. /* Verify property (2) */
  102904. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  102905. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  102906. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  102907. assert( db==0 || p->pUnlockConnection!=db );
  102908. assert( db==0 || p->pBlockingConnection!=db );
  102909. }
  102910. }
  102911. }
  102912. #else
  102913. # define checkListProperties(x)
  102914. #endif
  102915. /*
  102916. ** Remove connection db from the blocked connections list. If connection
  102917. ** db is not currently a part of the list, this function is a no-op.
  102918. */
  102919. static void removeFromBlockedList(sqlite3 *db){
  102920. sqlite3 **pp;
  102921. assertMutexHeld();
  102922. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  102923. if( *pp==db ){
  102924. *pp = (*pp)->pNextBlocked;
  102925. break;
  102926. }
  102927. }
  102928. }
  102929. /*
  102930. ** Add connection db to the blocked connections list. It is assumed
  102931. ** that it is not already a part of the list.
  102932. */
  102933. static void addToBlockedList(sqlite3 *db){
  102934. sqlite3 **pp;
  102935. assertMutexHeld();
  102936. for(
  102937. pp=&sqlite3BlockedList;
  102938. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  102939. pp=&(*pp)->pNextBlocked
  102940. );
  102941. db->pNextBlocked = *pp;
  102942. *pp = db;
  102943. }
  102944. /*
  102945. ** Obtain the STATIC_MASTER mutex.
  102946. */
  102947. static void enterMutex(void){
  102948. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  102949. checkListProperties(0);
  102950. }
  102951. /*
  102952. ** Release the STATIC_MASTER mutex.
  102953. */
  102954. static void leaveMutex(void){
  102955. assertMutexHeld();
  102956. checkListProperties(0);
  102957. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  102958. }
  102959. /*
  102960. ** Register an unlock-notify callback.
  102961. **
  102962. ** This is called after connection "db" has attempted some operation
  102963. ** but has received an SQLITE_LOCKED error because another connection
  102964. ** (call it pOther) in the same process was busy using the same shared
  102965. ** cache. pOther is found by looking at db->pBlockingConnection.
  102966. **
  102967. ** If there is no blocking connection, the callback is invoked immediately,
  102968. ** before this routine returns.
  102969. **
  102970. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  102971. ** a deadlock.
  102972. **
  102973. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  102974. ** its locks.
  102975. **
  102976. ** Each call to this routine overrides any prior callbacks registered
  102977. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  102978. ** cancelled.
  102979. */
  102980. SQLITE_API int sqlite3_unlock_notify(
  102981. sqlite3 *db,
  102982. void (*xNotify)(void **, int),
  102983. void *pArg
  102984. ){
  102985. int rc = SQLITE_OK;
  102986. sqlite3_mutex_enter(db->mutex);
  102987. enterMutex();
  102988. if( xNotify==0 ){
  102989. removeFromBlockedList(db);
  102990. db->pBlockingConnection = 0;
  102991. db->pUnlockConnection = 0;
  102992. db->xUnlockNotify = 0;
  102993. db->pUnlockArg = 0;
  102994. }else if( 0==db->pBlockingConnection ){
  102995. /* The blocking transaction has been concluded. Or there never was a
  102996. ** blocking transaction. In either case, invoke the notify callback
  102997. ** immediately.
  102998. */
  102999. xNotify(&pArg, 1);
  103000. }else{
  103001. sqlite3 *p;
  103002. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  103003. if( p ){
  103004. rc = SQLITE_LOCKED; /* Deadlock detected. */
  103005. }else{
  103006. db->pUnlockConnection = db->pBlockingConnection;
  103007. db->xUnlockNotify = xNotify;
  103008. db->pUnlockArg = pArg;
  103009. removeFromBlockedList(db);
  103010. addToBlockedList(db);
  103011. }
  103012. }
  103013. leaveMutex();
  103014. assert( !db->mallocFailed );
  103015. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  103016. sqlite3_mutex_leave(db->mutex);
  103017. return rc;
  103018. }
  103019. /*
  103020. ** This function is called while stepping or preparing a statement
  103021. ** associated with connection db. The operation will return SQLITE_LOCKED
  103022. ** to the user because it requires a lock that will not be available
  103023. ** until connection pBlocker concludes its current transaction.
  103024. */
  103025. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  103026. enterMutex();
  103027. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  103028. addToBlockedList(db);
  103029. }
  103030. db->pBlockingConnection = pBlocker;
  103031. leaveMutex();
  103032. }
  103033. /*
  103034. ** This function is called when
  103035. ** the transaction opened by database db has just finished. Locks held
  103036. ** by database connection db have been released.
  103037. **
  103038. ** This function loops through each entry in the blocked connections
  103039. ** list and does the following:
  103040. **
  103041. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  103042. ** set to db, then set pBlockingConnection=0.
  103043. **
  103044. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  103045. ** set to db, then invoke the configured unlock-notify callback and
  103046. ** set pUnlockConnection=0.
  103047. **
  103048. ** 3) If the two steps above mean that pBlockingConnection==0 and
  103049. ** pUnlockConnection==0, remove the entry from the blocked connections
  103050. ** list.
  103051. */
  103052. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  103053. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  103054. int nArg = 0; /* Number of entries in aArg[] */
  103055. sqlite3 **pp; /* Iterator variable */
  103056. void **aArg; /* Arguments to the unlock callback */
  103057. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  103058. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  103059. aArg = aStatic;
  103060. enterMutex(); /* Enter STATIC_MASTER mutex */
  103061. /* This loop runs once for each entry in the blocked-connections list. */
  103062. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  103063. sqlite3 *p = *pp;
  103064. /* Step 1. */
  103065. if( p->pBlockingConnection==db ){
  103066. p->pBlockingConnection = 0;
  103067. }
  103068. /* Step 2. */
  103069. if( p->pUnlockConnection==db ){
  103070. assert( p->xUnlockNotify );
  103071. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  103072. xUnlockNotify(aArg, nArg);
  103073. nArg = 0;
  103074. }
  103075. sqlite3BeginBenignMalloc();
  103076. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  103077. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  103078. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  103079. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  103080. ){
  103081. /* The aArg[] array needs to grow. */
  103082. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  103083. if( pNew ){
  103084. memcpy(pNew, aArg, nArg*sizeof(void *));
  103085. sqlite3_free(aDyn);
  103086. aDyn = aArg = pNew;
  103087. }else{
  103088. /* This occurs when the array of context pointers that need to
  103089. ** be passed to the unlock-notify callback is larger than the
  103090. ** aStatic[] array allocated on the stack and the attempt to
  103091. ** allocate a larger array from the heap has failed.
  103092. **
  103093. ** This is a difficult situation to handle. Returning an error
  103094. ** code to the caller is insufficient, as even if an error code
  103095. ** is returned the transaction on connection db will still be
  103096. ** closed and the unlock-notify callbacks on blocked connections
  103097. ** will go unissued. This might cause the application to wait
  103098. ** indefinitely for an unlock-notify callback that will never
  103099. ** arrive.
  103100. **
  103101. ** Instead, invoke the unlock-notify callback with the context
  103102. ** array already accumulated. We can then clear the array and
  103103. ** begin accumulating any further context pointers without
  103104. ** requiring any dynamic allocation. This is sub-optimal because
  103105. ** it means that instead of one callback with a large array of
  103106. ** context pointers the application will receive two or more
  103107. ** callbacks with smaller arrays of context pointers, which will
  103108. ** reduce the applications ability to prioritize multiple
  103109. ** connections. But it is the best that can be done under the
  103110. ** circumstances.
  103111. */
  103112. xUnlockNotify(aArg, nArg);
  103113. nArg = 0;
  103114. }
  103115. }
  103116. sqlite3EndBenignMalloc();
  103117. aArg[nArg++] = p->pUnlockArg;
  103118. xUnlockNotify = p->xUnlockNotify;
  103119. p->pUnlockConnection = 0;
  103120. p->xUnlockNotify = 0;
  103121. p->pUnlockArg = 0;
  103122. }
  103123. /* Step 3. */
  103124. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  103125. /* Remove connection p from the blocked connections list. */
  103126. *pp = p->pNextBlocked;
  103127. p->pNextBlocked = 0;
  103128. }else{
  103129. pp = &p->pNextBlocked;
  103130. }
  103131. }
  103132. if( nArg!=0 ){
  103133. xUnlockNotify(aArg, nArg);
  103134. }
  103135. sqlite3_free(aDyn);
  103136. leaveMutex(); /* Leave STATIC_MASTER mutex */
  103137. }
  103138. /*
  103139. ** This is called when the database connection passed as an argument is
  103140. ** being closed. The connection is removed from the blocked list.
  103141. */
  103142. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  103143. sqlite3ConnectionUnlocked(db);
  103144. enterMutex();
  103145. removeFromBlockedList(db);
  103146. checkListProperties(db);
  103147. leaveMutex();
  103148. }
  103149. #endif
  103150. /************** End of notify.c **********************************************/
  103151. /************** Begin file fts3.c ********************************************/
  103152. /*
  103153. ** 2006 Oct 10
  103154. **
  103155. ** The author disclaims copyright to this source code. In place of
  103156. ** a legal notice, here is a blessing:
  103157. **
  103158. ** May you do good and not evil.
  103159. ** May you find forgiveness for yourself and forgive others.
  103160. ** May you share freely, never taking more than you give.
  103161. **
  103162. ******************************************************************************
  103163. **
  103164. ** This is an SQLite module implementing full-text search.
  103165. */
  103166. /*
  103167. ** The code in this file is only compiled if:
  103168. **
  103169. ** * The FTS3 module is being built as an extension
  103170. ** (in which case SQLITE_CORE is not defined), or
  103171. **
  103172. ** * The FTS3 module is being built into the core of
  103173. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  103174. */
  103175. /* The full-text index is stored in a series of b+tree (-like)
  103176. ** structures called segments which map terms to doclists. The
  103177. ** structures are like b+trees in layout, but are constructed from the
  103178. ** bottom up in optimal fashion and are not updatable. Since trees
  103179. ** are built from the bottom up, things will be described from the
  103180. ** bottom up.
  103181. **
  103182. **
  103183. **** Varints ****
  103184. ** The basic unit of encoding is a variable-length integer called a
  103185. ** varint. We encode variable-length integers in little-endian order
  103186. ** using seven bits * per byte as follows:
  103187. **
  103188. ** KEY:
  103189. ** A = 0xxxxxxx 7 bits of data and one flag bit
  103190. ** B = 1xxxxxxx 7 bits of data and one flag bit
  103191. **
  103192. ** 7 bits - A
  103193. ** 14 bits - BA
  103194. ** 21 bits - BBA
  103195. ** and so on.
  103196. **
  103197. ** This is similar in concept to how sqlite encodes "varints" but
  103198. ** the encoding is not the same. SQLite varints are big-endian
  103199. ** are are limited to 9 bytes in length whereas FTS3 varints are
  103200. ** little-endian and can be up to 10 bytes in length (in theory).
  103201. **
  103202. ** Example encodings:
  103203. **
  103204. ** 1: 0x01
  103205. ** 127: 0x7f
  103206. ** 128: 0x81 0x00
  103207. **
  103208. **
  103209. **** Document lists ****
  103210. ** A doclist (document list) holds a docid-sorted list of hits for a
  103211. ** given term. Doclists hold docids and associated token positions.
  103212. ** A docid is the unique integer identifier for a single document.
  103213. ** A position is the index of a word within the document. The first
  103214. ** word of the document has a position of 0.
  103215. **
  103216. ** FTS3 used to optionally store character offsets using a compile-time
  103217. ** option. But that functionality is no longer supported.
  103218. **
  103219. ** A doclist is stored like this:
  103220. **
  103221. ** array {
  103222. ** varint docid;
  103223. ** array { (position list for column 0)
  103224. ** varint position; (2 more than the delta from previous position)
  103225. ** }
  103226. ** array {
  103227. ** varint POS_COLUMN; (marks start of position list for new column)
  103228. ** varint column; (index of new column)
  103229. ** array {
  103230. ** varint position; (2 more than the delta from previous position)
  103231. ** }
  103232. ** }
  103233. ** varint POS_END; (marks end of positions for this document.
  103234. ** }
  103235. **
  103236. ** Here, array { X } means zero or more occurrences of X, adjacent in
  103237. ** memory. A "position" is an index of a token in the token stream
  103238. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  103239. ** in the same logical place as the position element, and act as sentinals
  103240. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  103241. ** The positions numbers are not stored literally but rather as two more
  103242. ** than the difference from the prior position, or the just the position plus
  103243. ** 2 for the first position. Example:
  103244. **
  103245. ** label: A B C D E F G H I J K
  103246. ** value: 123 5 9 1 1 14 35 0 234 72 0
  103247. **
  103248. ** The 123 value is the first docid. For column zero in this document
  103249. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  103250. ** at D signals the start of a new column; the 1 at E indicates that the
  103251. ** new column is column number 1. There are two positions at 12 and 45
  103252. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  103253. ** 234 at I is the next docid. It has one position 72 (72-2) and then
  103254. ** terminates with the 0 at K.
  103255. **
  103256. ** A "position-list" is the list of positions for multiple columns for
  103257. ** a single docid. A "column-list" is the set of positions for a single
  103258. ** column. Hence, a position-list consists of one or more column-lists,
  103259. ** a document record consists of a docid followed by a position-list and
  103260. ** a doclist consists of one or more document records.
  103261. **
  103262. ** A bare doclist omits the position information, becoming an
  103263. ** array of varint-encoded docids.
  103264. **
  103265. **** Segment leaf nodes ****
  103266. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  103267. ** nodes are written using LeafWriter, and read using LeafReader (to
  103268. ** iterate through a single leaf node's data) and LeavesReader (to
  103269. ** iterate through a segment's entire leaf layer). Leaf nodes have
  103270. ** the format:
  103271. **
  103272. ** varint iHeight; (height from leaf level, always 0)
  103273. ** varint nTerm; (length of first term)
  103274. ** char pTerm[nTerm]; (content of first term)
  103275. ** varint nDoclist; (length of term's associated doclist)
  103276. ** char pDoclist[nDoclist]; (content of doclist)
  103277. ** array {
  103278. ** (further terms are delta-encoded)
  103279. ** varint nPrefix; (length of prefix shared with previous term)
  103280. ** varint nSuffix; (length of unshared suffix)
  103281. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  103282. ** varint nDoclist; (length of term's associated doclist)
  103283. ** char pDoclist[nDoclist]; (content of doclist)
  103284. ** }
  103285. **
  103286. ** Here, array { X } means zero or more occurrences of X, adjacent in
  103287. ** memory.
  103288. **
  103289. ** Leaf nodes are broken into blocks which are stored contiguously in
  103290. ** the %_segments table in sorted order. This means that when the end
  103291. ** of a node is reached, the next term is in the node with the next
  103292. ** greater node id.
  103293. **
  103294. ** New data is spilled to a new leaf node when the current node
  103295. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  103296. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  103297. ** node (a leaf node with a single term and doclist). The goal of
  103298. ** these settings is to pack together groups of small doclists while
  103299. ** making it efficient to directly access large doclists. The
  103300. ** assumption is that large doclists represent terms which are more
  103301. ** likely to be query targets.
  103302. **
  103303. ** TODO(shess) It may be useful for blocking decisions to be more
  103304. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  103305. ** node rather than splitting into 2k and .5k nodes. My intuition is
  103306. ** that this might extend through 2x or 4x the pagesize.
  103307. **
  103308. **
  103309. **** Segment interior nodes ****
  103310. ** Segment interior nodes store blockids for subtree nodes and terms
  103311. ** to describe what data is stored by the each subtree. Interior
  103312. ** nodes are written using InteriorWriter, and read using
  103313. ** InteriorReader. InteriorWriters are created as needed when
  103314. ** SegmentWriter creates new leaf nodes, or when an interior node
  103315. ** itself grows too big and must be split. The format of interior
  103316. ** nodes:
  103317. **
  103318. ** varint iHeight; (height from leaf level, always >0)
  103319. ** varint iBlockid; (block id of node's leftmost subtree)
  103320. ** optional {
  103321. ** varint nTerm; (length of first term)
  103322. ** char pTerm[nTerm]; (content of first term)
  103323. ** array {
  103324. ** (further terms are delta-encoded)
  103325. ** varint nPrefix; (length of shared prefix with previous term)
  103326. ** varint nSuffix; (length of unshared suffix)
  103327. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  103328. ** }
  103329. ** }
  103330. **
  103331. ** Here, optional { X } means an optional element, while array { X }
  103332. ** means zero or more occurrences of X, adjacent in memory.
  103333. **
  103334. ** An interior node encodes n terms separating n+1 subtrees. The
  103335. ** subtree blocks are contiguous, so only the first subtree's blockid
  103336. ** is encoded. The subtree at iBlockid will contain all terms less
  103337. ** than the first term encoded (or all terms if no term is encoded).
  103338. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  103339. ** than pTerm[i+1], the subtree for that term will be rooted at
  103340. ** iBlockid+i. Interior nodes only store enough term data to
  103341. ** distinguish adjacent children (if the rightmost term of the left
  103342. ** child is "something", and the leftmost term of the right child is
  103343. ** "wicked", only "w" is stored).
  103344. **
  103345. ** New data is spilled to a new interior node at the same height when
  103346. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  103347. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  103348. ** interior nodes and making the tree too skinny. The interior nodes
  103349. ** at a given height are naturally tracked by interior nodes at
  103350. ** height+1, and so on.
  103351. **
  103352. **
  103353. **** Segment directory ****
  103354. ** The segment directory in table %_segdir stores meta-information for
  103355. ** merging and deleting segments, and also the root node of the
  103356. ** segment's tree.
  103357. **
  103358. ** The root node is the top node of the segment's tree after encoding
  103359. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  103360. ** This could be either a leaf node or an interior node. If the top
  103361. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  103362. ** and a new root interior node is generated (which should always fit
  103363. ** within ROOT_MAX because it only needs space for 2 varints, the
  103364. ** height and the blockid of the previous root).
  103365. **
  103366. ** The meta-information in the segment directory is:
  103367. ** level - segment level (see below)
  103368. ** idx - index within level
  103369. ** - (level,idx uniquely identify a segment)
  103370. ** start_block - first leaf node
  103371. ** leaves_end_block - last leaf node
  103372. ** end_block - last block (including interior nodes)
  103373. ** root - contents of root node
  103374. **
  103375. ** If the root node is a leaf node, then start_block,
  103376. ** leaves_end_block, and end_block are all 0.
  103377. **
  103378. **
  103379. **** Segment merging ****
  103380. ** To amortize update costs, segments are grouped into levels and
  103381. ** merged in batches. Each increase in level represents exponentially
  103382. ** more documents.
  103383. **
  103384. ** New documents (actually, document updates) are tokenized and
  103385. ** written individually (using LeafWriter) to a level 0 segment, with
  103386. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  103387. ** level 0 segments are merged into a single level 1 segment. Level 1
  103388. ** is populated like level 0, and eventually MERGE_COUNT level 1
  103389. ** segments are merged to a single level 2 segment (representing
  103390. ** MERGE_COUNT^2 updates), and so on.
  103391. **
  103392. ** A segment merge traverses all segments at a given level in
  103393. ** parallel, performing a straightforward sorted merge. Since segment
  103394. ** leaf nodes are written in to the %_segments table in order, this
  103395. ** merge traverses the underlying sqlite disk structures efficiently.
  103396. ** After the merge, all segment blocks from the merged level are
  103397. ** deleted.
  103398. **
  103399. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  103400. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  103401. ** very similar performance numbers to 16 on insertion, though they're
  103402. ** a tiny bit slower (perhaps due to more overhead in merge-time
  103403. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  103404. ** 16, 2 about 66% slower than 16.
  103405. **
  103406. ** At query time, high MERGE_COUNT increases the number of segments
  103407. ** which need to be scanned and merged. For instance, with 100k docs
  103408. ** inserted:
  103409. **
  103410. ** MERGE_COUNT segments
  103411. ** 16 25
  103412. ** 8 12
  103413. ** 4 10
  103414. ** 2 6
  103415. **
  103416. ** This appears to have only a moderate impact on queries for very
  103417. ** frequent terms (which are somewhat dominated by segment merge
  103418. ** costs), and infrequent and non-existent terms still seem to be fast
  103419. ** even with many segments.
  103420. **
  103421. ** TODO(shess) That said, it would be nice to have a better query-side
  103422. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  103423. ** optimizations to things like doclist merging will swing the sweet
  103424. ** spot around.
  103425. **
  103426. **
  103427. **
  103428. **** Handling of deletions and updates ****
  103429. ** Since we're using a segmented structure, with no docid-oriented
  103430. ** index into the term index, we clearly cannot simply update the term
  103431. ** index when a document is deleted or updated. For deletions, we
  103432. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  103433. ** we simply write the new doclist. Segment merges overwrite older
  103434. ** data for a particular docid with newer data, so deletes or updates
  103435. ** will eventually overtake the earlier data and knock it out. The
  103436. ** query logic likewise merges doclists so that newer data knocks out
  103437. ** older data.
  103438. **
  103439. ** TODO(shess) Provide a VACUUM type operation to clear out all
  103440. ** deletions and duplications. This would basically be a forced merge
  103441. ** into a single segment.
  103442. */
  103443. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  103444. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  103445. # define SQLITE_CORE 1
  103446. #endif
  103447. /************** Include fts3Int.h in the middle of fts3.c ********************/
  103448. /************** Begin file fts3Int.h *****************************************/
  103449. /*
  103450. ** 2009 Nov 12
  103451. **
  103452. ** The author disclaims copyright to this source code. In place of
  103453. ** a legal notice, here is a blessing:
  103454. **
  103455. ** May you do good and not evil.
  103456. ** May you find forgiveness for yourself and forgive others.
  103457. ** May you share freely, never taking more than you give.
  103458. **
  103459. ******************************************************************************
  103460. **
  103461. */
  103462. #ifndef _FTSINT_H
  103463. #define _FTSINT_H
  103464. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  103465. # define NDEBUG 1
  103466. #endif
  103467. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  103468. /************** Begin file fts3_tokenizer.h **********************************/
  103469. /*
  103470. ** 2006 July 10
  103471. **
  103472. ** The author disclaims copyright to this source code.
  103473. **
  103474. *************************************************************************
  103475. ** Defines the interface to tokenizers used by fulltext-search. There
  103476. ** are three basic components:
  103477. **
  103478. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  103479. ** interface functions. This is essentially the class structure for
  103480. ** tokenizers.
  103481. **
  103482. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  103483. ** including customization information defined at creation time.
  103484. **
  103485. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  103486. ** tokens from a particular input.
  103487. */
  103488. #ifndef _FTS3_TOKENIZER_H_
  103489. #define _FTS3_TOKENIZER_H_
  103490. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  103491. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  103492. ** we will need a way to register the API consistently.
  103493. */
  103494. /*
  103495. ** Structures used by the tokenizer interface. When a new tokenizer
  103496. ** implementation is registered, the caller provides a pointer to
  103497. ** an sqlite3_tokenizer_module containing pointers to the callback
  103498. ** functions that make up an implementation.
  103499. **
  103500. ** When an fts3 table is created, it passes any arguments passed to
  103501. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  103502. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  103503. ** implementation. The xCreate() function in turn returns an
  103504. ** sqlite3_tokenizer structure representing the specific tokenizer to
  103505. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  103506. **
  103507. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  103508. ** method is called. It returns an sqlite3_tokenizer_cursor object
  103509. ** that may be used to tokenize a specific input buffer based on
  103510. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  103511. ** object.
  103512. */
  103513. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  103514. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  103515. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  103516. struct sqlite3_tokenizer_module {
  103517. /*
  103518. ** Structure version. Should always be set to 0.
  103519. */
  103520. int iVersion;
  103521. /*
  103522. ** Create a new tokenizer. The values in the argv[] array are the
  103523. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  103524. ** TABLE statement that created the fts3 table. For example, if
  103525. ** the following SQL is executed:
  103526. **
  103527. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  103528. **
  103529. ** then argc is set to 2, and the argv[] array contains pointers
  103530. ** to the strings "arg1" and "arg2".
  103531. **
  103532. ** This method should return either SQLITE_OK (0), or an SQLite error
  103533. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  103534. ** to point at the newly created tokenizer structure. The generic
  103535. ** sqlite3_tokenizer.pModule variable should not be initialised by
  103536. ** this callback. The caller will do so.
  103537. */
  103538. int (*xCreate)(
  103539. int argc, /* Size of argv array */
  103540. const char *const*argv, /* Tokenizer argument strings */
  103541. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  103542. );
  103543. /*
  103544. ** Destroy an existing tokenizer. The fts3 module calls this method
  103545. ** exactly once for each successful call to xCreate().
  103546. */
  103547. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  103548. /*
  103549. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  103550. ** is responsible for ensuring that the input buffer remains valid
  103551. ** until the cursor is closed (using the xClose() method).
  103552. */
  103553. int (*xOpen)(
  103554. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  103555. const char *pInput, int nBytes, /* Input buffer */
  103556. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  103557. );
  103558. /*
  103559. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  103560. ** method exactly once for each successful call to xOpen().
  103561. */
  103562. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  103563. /*
  103564. ** Retrieve the next token from the tokenizer cursor pCursor. This
  103565. ** method should either return SQLITE_OK and set the values of the
  103566. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  103567. ** the end of the buffer has been reached, or an SQLite error code.
  103568. **
  103569. ** *ppToken should be set to point at a buffer containing the
  103570. ** normalized version of the token (i.e. after any case-folding and/or
  103571. ** stemming has been performed). *pnBytes should be set to the length
  103572. ** of this buffer in bytes. The input text that generated the token is
  103573. ** identified by the byte offsets returned in *piStartOffset and
  103574. ** *piEndOffset. *piStartOffset should be set to the index of the first
  103575. ** byte of the token in the input buffer. *piEndOffset should be set
  103576. ** to the index of the first byte just past the end of the token in
  103577. ** the input buffer.
  103578. **
  103579. ** The buffer *ppToken is set to point at is managed by the tokenizer
  103580. ** implementation. It is only required to be valid until the next call
  103581. ** to xNext() or xClose().
  103582. */
  103583. /* TODO(shess) current implementation requires pInput to be
  103584. ** nul-terminated. This should either be fixed, or pInput/nBytes
  103585. ** should be converted to zInput.
  103586. */
  103587. int (*xNext)(
  103588. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  103589. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  103590. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  103591. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  103592. int *piPosition /* OUT: Number of tokens returned before this one */
  103593. );
  103594. };
  103595. struct sqlite3_tokenizer {
  103596. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  103597. /* Tokenizer implementations will typically add additional fields */
  103598. };
  103599. struct sqlite3_tokenizer_cursor {
  103600. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  103601. /* Tokenizer implementations will typically add additional fields */
  103602. };
  103603. int fts3_global_term_cnt(int iTerm, int iCol);
  103604. int fts3_term_cnt(int iTerm, int iCol);
  103605. #endif /* _FTS3_TOKENIZER_H_ */
  103606. /************** End of fts3_tokenizer.h **************************************/
  103607. /************** Continuing where we left off in fts3Int.h ********************/
  103608. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  103609. /************** Begin file fts3_hash.h ***************************************/
  103610. /*
  103611. ** 2001 September 22
  103612. **
  103613. ** The author disclaims copyright to this source code. In place of
  103614. ** a legal notice, here is a blessing:
  103615. **
  103616. ** May you do good and not evil.
  103617. ** May you find forgiveness for yourself and forgive others.
  103618. ** May you share freely, never taking more than you give.
  103619. **
  103620. *************************************************************************
  103621. ** This is the header file for the generic hash-table implemenation
  103622. ** used in SQLite. We've modified it slightly to serve as a standalone
  103623. ** hash table implementation for the full-text indexing module.
  103624. **
  103625. */
  103626. #ifndef _FTS3_HASH_H_
  103627. #define _FTS3_HASH_H_
  103628. /* Forward declarations of structures. */
  103629. typedef struct Fts3Hash Fts3Hash;
  103630. typedef struct Fts3HashElem Fts3HashElem;
  103631. /* A complete hash table is an instance of the following structure.
  103632. ** The internals of this structure are intended to be opaque -- client
  103633. ** code should not attempt to access or modify the fields of this structure
  103634. ** directly. Change this structure only by using the routines below.
  103635. ** However, many of the "procedures" and "functions" for modifying and
  103636. ** accessing this structure are really macros, so we can't really make
  103637. ** this structure opaque.
  103638. */
  103639. struct Fts3Hash {
  103640. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  103641. char copyKey; /* True if copy of key made on insert */
  103642. int count; /* Number of entries in this table */
  103643. Fts3HashElem *first; /* The first element of the array */
  103644. int htsize; /* Number of buckets in the hash table */
  103645. struct _fts3ht { /* the hash table */
  103646. int count; /* Number of entries with this hash */
  103647. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  103648. } *ht;
  103649. };
  103650. /* Each element in the hash table is an instance of the following
  103651. ** structure. All elements are stored on a single doubly-linked list.
  103652. **
  103653. ** Again, this structure is intended to be opaque, but it can't really
  103654. ** be opaque because it is used by macros.
  103655. */
  103656. struct Fts3HashElem {
  103657. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  103658. void *data; /* Data associated with this element */
  103659. void *pKey; int nKey; /* Key associated with this element */
  103660. };
  103661. /*
  103662. ** There are 2 different modes of operation for a hash table:
  103663. **
  103664. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  103665. ** (including the null-terminator, if any). Case
  103666. ** is respected in comparisons.
  103667. **
  103668. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  103669. ** memcmp() is used to compare keys.
  103670. **
  103671. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  103672. */
  103673. #define FTS3_HASH_STRING 1
  103674. #define FTS3_HASH_BINARY 2
  103675. /*
  103676. ** Access routines. To delete, insert a NULL pointer.
  103677. */
  103678. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  103679. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  103680. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  103681. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  103682. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  103683. /*
  103684. ** Shorthand for the functions above
  103685. */
  103686. #define fts3HashInit sqlite3Fts3HashInit
  103687. #define fts3HashInsert sqlite3Fts3HashInsert
  103688. #define fts3HashFind sqlite3Fts3HashFind
  103689. #define fts3HashClear sqlite3Fts3HashClear
  103690. #define fts3HashFindElem sqlite3Fts3HashFindElem
  103691. /*
  103692. ** Macros for looping over all elements of a hash table. The idiom is
  103693. ** like this:
  103694. **
  103695. ** Fts3Hash h;
  103696. ** Fts3HashElem *p;
  103697. ** ...
  103698. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  103699. ** SomeStructure *pData = fts3HashData(p);
  103700. ** // do something with pData
  103701. ** }
  103702. */
  103703. #define fts3HashFirst(H) ((H)->first)
  103704. #define fts3HashNext(E) ((E)->next)
  103705. #define fts3HashData(E) ((E)->data)
  103706. #define fts3HashKey(E) ((E)->pKey)
  103707. #define fts3HashKeysize(E) ((E)->nKey)
  103708. /*
  103709. ** Number of entries in a hash table
  103710. */
  103711. #define fts3HashCount(H) ((H)->count)
  103712. #endif /* _FTS3_HASH_H_ */
  103713. /************** End of fts3_hash.h *******************************************/
  103714. /************** Continuing where we left off in fts3Int.h ********************/
  103715. /*
  103716. ** This constant controls how often segments are merged. Once there are
  103717. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  103718. ** segment of level N+1.
  103719. */
  103720. #define FTS3_MERGE_COUNT 16
  103721. /*
  103722. ** This is the maximum amount of data (in bytes) to store in the
  103723. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  103724. ** populated as documents are inserted/updated/deleted in a transaction
  103725. ** and used to create a new segment when the transaction is committed.
  103726. ** However if this limit is reached midway through a transaction, a new
  103727. ** segment is created and the hash table cleared immediately.
  103728. */
  103729. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  103730. /*
  103731. ** Macro to return the number of elements in an array. SQLite has a
  103732. ** similar macro called ArraySize(). Use a different name to avoid
  103733. ** a collision when building an amalgamation with built-in FTS3.
  103734. */
  103735. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  103736. /*
  103737. ** Maximum length of a varint encoded integer. The varint format is different
  103738. ** from that used by SQLite, so the maximum length is 10, not 9.
  103739. */
  103740. #define FTS3_VARINT_MAX 10
  103741. /*
  103742. ** The testcase() macro is only used by the amalgamation. If undefined,
  103743. ** make it a no-op.
  103744. */
  103745. #ifndef testcase
  103746. # define testcase(X)
  103747. #endif
  103748. /*
  103749. ** Terminator values for position-lists and column-lists.
  103750. */
  103751. #define POS_COLUMN (1) /* Column-list terminator */
  103752. #define POS_END (0) /* Position-list terminator */
  103753. /*
  103754. ** This section provides definitions to allow the
  103755. ** FTS3 extension to be compiled outside of the
  103756. ** amalgamation.
  103757. */
  103758. #ifndef SQLITE_AMALGAMATION
  103759. /*
  103760. ** Macros indicating that conditional expressions are always true or
  103761. ** false.
  103762. */
  103763. #ifdef SQLITE_COVERAGE_TEST
  103764. # define ALWAYS(x) (1)
  103765. # define NEVER(X) (0)
  103766. #else
  103767. # define ALWAYS(x) (x)
  103768. # define NEVER(X) (x)
  103769. #endif
  103770. /*
  103771. ** Internal types used by SQLite.
  103772. */
  103773. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  103774. typedef short int i16; /* 2-byte (or larger) signed integer */
  103775. typedef unsigned int u32; /* 4-byte unsigned integer */
  103776. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  103777. /*
  103778. ** Macro used to suppress compiler warnings for unused parameters.
  103779. */
  103780. #define UNUSED_PARAMETER(x) (void)(x)
  103781. #endif
  103782. typedef struct Fts3Table Fts3Table;
  103783. typedef struct Fts3Cursor Fts3Cursor;
  103784. typedef struct Fts3Expr Fts3Expr;
  103785. typedef struct Fts3Phrase Fts3Phrase;
  103786. typedef struct Fts3PhraseToken Fts3PhraseToken;
  103787. typedef struct Fts3SegFilter Fts3SegFilter;
  103788. typedef struct Fts3DeferredToken Fts3DeferredToken;
  103789. typedef struct Fts3SegReader Fts3SegReader;
  103790. typedef struct Fts3SegReaderCursor Fts3SegReaderCursor;
  103791. /*
  103792. ** A connection to a fulltext index is an instance of the following
  103793. ** structure. The xCreate and xConnect methods create an instance
  103794. ** of this structure and xDestroy and xDisconnect free that instance.
  103795. ** All other methods receive a pointer to the structure as one of their
  103796. ** arguments.
  103797. */
  103798. struct Fts3Table {
  103799. sqlite3_vtab base; /* Base class used by SQLite core */
  103800. sqlite3 *db; /* The database connection */
  103801. const char *zDb; /* logical database name */
  103802. const char *zName; /* virtual table name */
  103803. int nColumn; /* number of named columns in virtual table */
  103804. char **azColumn; /* column names. malloced */
  103805. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  103806. /* Precompiled statements used by the implementation. Each of these
  103807. ** statements is run and reset within a single virtual table API call.
  103808. */
  103809. sqlite3_stmt *aStmt[24];
  103810. char *zReadExprlist;
  103811. char *zWriteExprlist;
  103812. int nNodeSize; /* Soft limit for node size */
  103813. u8 bHasStat; /* True if %_stat table exists */
  103814. u8 bHasDocsize; /* True if %_docsize table exists */
  103815. int nPgsz; /* Page size for host database */
  103816. char *zSegmentsTbl; /* Name of %_segments table */
  103817. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  103818. /* The following hash table is used to buffer pending index updates during
  103819. ** transactions. Variable nPendingData estimates the memory size of the
  103820. ** pending data, including hash table overhead, but not malloc overhead.
  103821. ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
  103822. ** automatically. Variable iPrevDocid is the docid of the most recently
  103823. ** inserted record.
  103824. */
  103825. int nMaxPendingData;
  103826. int nPendingData;
  103827. sqlite_int64 iPrevDocid;
  103828. Fts3Hash pendingTerms;
  103829. };
  103830. /*
  103831. ** When the core wants to read from the virtual table, it creates a
  103832. ** virtual table cursor (an instance of the following structure) using
  103833. ** the xOpen method. Cursors are destroyed using the xClose method.
  103834. */
  103835. struct Fts3Cursor {
  103836. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  103837. i16 eSearch; /* Search strategy (see below) */
  103838. u8 isEof; /* True if at End Of Results */
  103839. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  103840. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  103841. Fts3Expr *pExpr; /* Parsed MATCH query string */
  103842. int nPhrase; /* Number of matchable phrases in query */
  103843. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  103844. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  103845. char *pNextId; /* Pointer into the body of aDoclist */
  103846. char *aDoclist; /* List of docids for full-text queries */
  103847. int nDoclist; /* Size of buffer at aDoclist */
  103848. int eEvalmode; /* An FTS3_EVAL_XX constant */
  103849. int nRowAvg; /* Average size of database rows, in pages */
  103850. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  103851. u32 *aMatchinfo; /* Information about most recent match */
  103852. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  103853. char *zMatchinfo; /* Matchinfo specification */
  103854. };
  103855. #define FTS3_EVAL_FILTER 0
  103856. #define FTS3_EVAL_NEXT 1
  103857. #define FTS3_EVAL_MATCHINFO 2
  103858. /*
  103859. ** The Fts3Cursor.eSearch member is always set to one of the following.
  103860. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  103861. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  103862. ** of the column to be searched. For example, in
  103863. **
  103864. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  103865. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  103866. **
  103867. ** Because the LHS of the MATCH operator is 2nd column "b",
  103868. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  103869. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  103870. ** indicating that all columns should be searched,
  103871. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  103872. */
  103873. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  103874. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  103875. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  103876. /*
  103877. ** A "phrase" is a sequence of one or more tokens that must match in
  103878. ** sequence. A single token is the base case and the most common case.
  103879. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  103880. ** nToken will be the number of tokens in the string.
  103881. **
  103882. ** The nDocMatch and nMatch variables contain data that may be used by the
  103883. ** matchinfo() function. They are populated when the full-text index is
  103884. ** queried for hits on the phrase. If one or more tokens in the phrase
  103885. ** are deferred, the nDocMatch and nMatch variables are populated based
  103886. ** on the assumption that the
  103887. */
  103888. struct Fts3PhraseToken {
  103889. char *z; /* Text of the token */
  103890. int n; /* Number of bytes in buffer z */
  103891. int isPrefix; /* True if token ends with a "*" character */
  103892. int bFulltext; /* True if full-text index was used */
  103893. Fts3SegReaderCursor *pSegcsr; /* Segment-reader for this token */
  103894. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  103895. };
  103896. struct Fts3Phrase {
  103897. /* Variables populated by fts3_expr.c when parsing a MATCH expression */
  103898. int nToken; /* Number of tokens in the phrase */
  103899. int iColumn; /* Index of column this phrase must match */
  103900. int isNot; /* Phrase prefixed by unary not (-) operator */
  103901. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  103902. };
  103903. /*
  103904. ** A tree of these objects forms the RHS of a MATCH operator.
  103905. **
  103906. ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
  103907. ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
  103908. ** containing the results of the NEAR or phrase query in FTS3 doclist
  103909. ** format. As usual, the initial "Length" field found in doclists stored
  103910. ** on disk is omitted from this buffer.
  103911. **
  103912. ** Variable pCurrent always points to the start of a docid field within
  103913. ** aDoclist. Since the doclist is usually scanned in docid order, this can
  103914. ** be used to accelerate seeking to the required docid within the doclist.
  103915. */
  103916. struct Fts3Expr {
  103917. int eType; /* One of the FTSQUERY_XXX values defined below */
  103918. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  103919. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  103920. Fts3Expr *pLeft; /* Left operand */
  103921. Fts3Expr *pRight; /* Right operand */
  103922. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  103923. int isLoaded; /* True if aDoclist/nDoclist are initialized. */
  103924. char *aDoclist; /* Buffer containing doclist */
  103925. int nDoclist; /* Size of aDoclist in bytes */
  103926. sqlite3_int64 iCurrent;
  103927. char *pCurrent;
  103928. };
  103929. /*
  103930. ** Candidate values for Fts3Query.eType. Note that the order of the first
  103931. ** four values is in order of precedence when parsing expressions. For
  103932. ** example, the following:
  103933. **
  103934. ** "a OR b AND c NOT d NEAR e"
  103935. **
  103936. ** is equivalent to:
  103937. **
  103938. ** "a OR (b AND (c NOT (d NEAR e)))"
  103939. */
  103940. #define FTSQUERY_NEAR 1
  103941. #define FTSQUERY_NOT 2
  103942. #define FTSQUERY_AND 3
  103943. #define FTSQUERY_OR 4
  103944. #define FTSQUERY_PHRASE 5
  103945. /* fts3_write.c */
  103946. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  103947. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  103948. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  103949. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  103950. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
  103951. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  103952. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
  103953. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  103954. SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
  103955. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, sqlite3_stmt **);
  103956. SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
  103957. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
  103958. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  103959. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  103960. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  103961. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  103962. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  103963. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  103964. SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
  103965. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  103966. #define FTS3_SEGCURSOR_PENDING -1
  103967. #define FTS3_SEGCURSOR_ALL -2
  103968. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3SegReaderCursor*, Fts3SegFilter*);
  103969. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3SegReaderCursor *);
  103970. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3SegReaderCursor *);
  103971. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  103972. Fts3Table *, int, const char *, int, int, int, Fts3SegReaderCursor *);
  103973. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  103974. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  103975. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  103976. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  103977. #define FTS3_SEGMENT_PREFIX 0x00000008
  103978. #define FTS3_SEGMENT_SCAN 0x00000010
  103979. /* Type passed as 4th argument to SegmentReaderIterate() */
  103980. struct Fts3SegFilter {
  103981. const char *zTerm;
  103982. int nTerm;
  103983. int iCol;
  103984. int flags;
  103985. };
  103986. struct Fts3SegReaderCursor {
  103987. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  103988. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  103989. int nSegment; /* Size of apSegment array */
  103990. int nAdvance; /* How many seg-readers to advance */
  103991. Fts3SegFilter *pFilter; /* Pointer to filter object */
  103992. char *aBuffer; /* Buffer to merge doclists in */
  103993. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  103994. /* Cost of running this iterator. Used by fts3.c only. */
  103995. int nCost;
  103996. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  103997. char *zTerm; /* Pointer to term buffer */
  103998. int nTerm; /* Size of zTerm in bytes */
  103999. char *aDoclist; /* Pointer to doclist buffer */
  104000. int nDoclist; /* Size of aDoclist[] in bytes */
  104001. };
  104002. /* fts3.c */
  104003. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  104004. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  104005. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  104006. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  104007. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  104008. SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
  104009. SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
  104010. SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
  104011. SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
  104012. /* fts3_tokenizer.c */
  104013. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  104014. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  104015. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  104016. sqlite3_tokenizer **, char **
  104017. );
  104018. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  104019. /* fts3_snippet.c */
  104020. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  104021. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  104022. const char *, const char *, int, int
  104023. );
  104024. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  104025. /* fts3_expr.c */
  104026. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
  104027. char **, int, int, const char *, int, Fts3Expr **
  104028. );
  104029. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  104030. #ifdef SQLITE_TEST
  104031. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  104032. #endif
  104033. /* fts3_aux.c */
  104034. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  104035. #endif /* _FTSINT_H */
  104036. /************** End of fts3Int.h *********************************************/
  104037. /************** Continuing where we left off in fts3.c ***********************/
  104038. #ifndef SQLITE_CORE
  104039. SQLITE_EXTENSION_INIT1
  104040. #endif
  104041. /*
  104042. ** Write a 64-bit variable-length integer to memory starting at p[0].
  104043. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  104044. ** The number of bytes written is returned.
  104045. */
  104046. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  104047. unsigned char *q = (unsigned char *) p;
  104048. sqlite_uint64 vu = v;
  104049. do{
  104050. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  104051. vu >>= 7;
  104052. }while( vu!=0 );
  104053. q[-1] &= 0x7f; /* turn off high bit in final byte */
  104054. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  104055. return (int) (q - (unsigned char *)p);
  104056. }
  104057. /*
  104058. ** Read a 64-bit variable-length integer from memory starting at p[0].
  104059. ** Return the number of bytes read, or 0 on error.
  104060. ** The value is stored in *v.
  104061. */
  104062. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  104063. const unsigned char *q = (const unsigned char *) p;
  104064. sqlite_uint64 x = 0, y = 1;
  104065. while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
  104066. x += y * (*q++ & 0x7f);
  104067. y <<= 7;
  104068. }
  104069. x += y * (*q++);
  104070. *v = (sqlite_int64) x;
  104071. return (int) (q - (unsigned char *)p);
  104072. }
  104073. /*
  104074. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  104075. ** 32-bit integer before it is returned.
  104076. */
  104077. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  104078. sqlite_int64 i;
  104079. int ret = sqlite3Fts3GetVarint(p, &i);
  104080. *pi = (int) i;
  104081. return ret;
  104082. }
  104083. /*
  104084. ** Return the number of bytes required to encode v as a varint
  104085. */
  104086. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  104087. int i = 0;
  104088. do{
  104089. i++;
  104090. v >>= 7;
  104091. }while( v!=0 );
  104092. return i;
  104093. }
  104094. /*
  104095. ** Convert an SQL-style quoted string into a normal string by removing
  104096. ** the quote characters. The conversion is done in-place. If the
  104097. ** input does not begin with a quote character, then this routine
  104098. ** is a no-op.
  104099. **
  104100. ** Examples:
  104101. **
  104102. ** "abc" becomes abc
  104103. ** 'xyz' becomes xyz
  104104. ** [pqr] becomes pqr
  104105. ** `mno` becomes mno
  104106. **
  104107. */
  104108. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  104109. char quote; /* Quote character (if any ) */
  104110. quote = z[0];
  104111. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  104112. int iIn = 1; /* Index of next byte to read from input */
  104113. int iOut = 0; /* Index of next byte to write to output */
  104114. /* If the first byte was a '[', then the close-quote character is a ']' */
  104115. if( quote=='[' ) quote = ']';
  104116. while( ALWAYS(z[iIn]) ){
  104117. if( z[iIn]==quote ){
  104118. if( z[iIn+1]!=quote ) break;
  104119. z[iOut++] = quote;
  104120. iIn += 2;
  104121. }else{
  104122. z[iOut++] = z[iIn++];
  104123. }
  104124. }
  104125. z[iOut] = '\0';
  104126. }
  104127. }
  104128. /*
  104129. ** Read a single varint from the doclist at *pp and advance *pp to point
  104130. ** to the first byte past the end of the varint. Add the value of the varint
  104131. ** to *pVal.
  104132. */
  104133. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  104134. sqlite3_int64 iVal;
  104135. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  104136. *pVal += iVal;
  104137. }
  104138. /*
  104139. ** As long as *pp has not reached its end (pEnd), then do the same
  104140. ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
  104141. ** But if we have reached the end of the varint, just set *pp=0 and
  104142. ** leave *pVal unchanged.
  104143. */
  104144. static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
  104145. if( *pp>=pEnd ){
  104146. *pp = 0;
  104147. }else{
  104148. fts3GetDeltaVarint(pp, pVal);
  104149. }
  104150. }
  104151. /*
  104152. ** The xDisconnect() virtual table method.
  104153. */
  104154. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  104155. Fts3Table *p = (Fts3Table *)pVtab;
  104156. int i;
  104157. assert( p->nPendingData==0 );
  104158. assert( p->pSegments==0 );
  104159. /* Free any prepared statements held */
  104160. for(i=0; i<SizeofArray(p->aStmt); i++){
  104161. sqlite3_finalize(p->aStmt[i]);
  104162. }
  104163. sqlite3_free(p->zSegmentsTbl);
  104164. sqlite3_free(p->zReadExprlist);
  104165. sqlite3_free(p->zWriteExprlist);
  104166. /* Invoke the tokenizer destructor to free the tokenizer. */
  104167. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  104168. sqlite3_free(p);
  104169. return SQLITE_OK;
  104170. }
  104171. /*
  104172. ** Construct one or more SQL statements from the format string given
  104173. ** and then evaluate those statements. The success code is written
  104174. ** into *pRc.
  104175. **
  104176. ** If *pRc is initially non-zero then this routine is a no-op.
  104177. */
  104178. static void fts3DbExec(
  104179. int *pRc, /* Success code */
  104180. sqlite3 *db, /* Database in which to run SQL */
  104181. const char *zFormat, /* Format string for SQL */
  104182. ... /* Arguments to the format string */
  104183. ){
  104184. va_list ap;
  104185. char *zSql;
  104186. if( *pRc ) return;
  104187. va_start(ap, zFormat);
  104188. zSql = sqlite3_vmprintf(zFormat, ap);
  104189. va_end(ap);
  104190. if( zSql==0 ){
  104191. *pRc = SQLITE_NOMEM;
  104192. }else{
  104193. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  104194. sqlite3_free(zSql);
  104195. }
  104196. }
  104197. /*
  104198. ** The xDestroy() virtual table method.
  104199. */
  104200. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  104201. int rc = SQLITE_OK; /* Return code */
  104202. Fts3Table *p = (Fts3Table *)pVtab;
  104203. sqlite3 *db = p->db;
  104204. /* Drop the shadow tables */
  104205. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
  104206. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
  104207. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
  104208. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
  104209. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
  104210. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  104211. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  104212. ** Otherwise, return an SQLite error code.
  104213. */
  104214. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  104215. }
  104216. /*
  104217. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  104218. ** passed as the first argument. This is done as part of the xConnect()
  104219. ** and xCreate() methods.
  104220. **
  104221. ** If *pRc is non-zero when this function is called, it is a no-op.
  104222. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  104223. ** before returning.
  104224. */
  104225. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  104226. if( *pRc==SQLITE_OK ){
  104227. int i; /* Iterator variable */
  104228. int rc; /* Return code */
  104229. char *zSql; /* SQL statement passed to declare_vtab() */
  104230. char *zCols; /* List of user defined columns */
  104231. /* Create a list of user columns for the virtual table */
  104232. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  104233. for(i=1; zCols && i<p->nColumn; i++){
  104234. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  104235. }
  104236. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  104237. zSql = sqlite3_mprintf(
  104238. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
  104239. );
  104240. if( !zCols || !zSql ){
  104241. rc = SQLITE_NOMEM;
  104242. }else{
  104243. rc = sqlite3_declare_vtab(p->db, zSql);
  104244. }
  104245. sqlite3_free(zSql);
  104246. sqlite3_free(zCols);
  104247. *pRc = rc;
  104248. }
  104249. }
  104250. /*
  104251. ** Create the backing store tables (%_content, %_segments and %_segdir)
  104252. ** required by the FTS3 table passed as the only argument. This is done
  104253. ** as part of the vtab xCreate() method.
  104254. **
  104255. ** If the p->bHasDocsize boolean is true (indicating that this is an
  104256. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  104257. ** %_stat tables required by FTS4.
  104258. */
  104259. static int fts3CreateTables(Fts3Table *p){
  104260. int rc = SQLITE_OK; /* Return code */
  104261. int i; /* Iterator variable */
  104262. char *zContentCols; /* Columns of %_content table */
  104263. sqlite3 *db = p->db; /* The database connection */
  104264. /* Create a list of user columns for the content table */
  104265. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  104266. for(i=0; zContentCols && i<p->nColumn; i++){
  104267. char *z = p->azColumn[i];
  104268. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  104269. }
  104270. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  104271. /* Create the content table */
  104272. fts3DbExec(&rc, db,
  104273. "CREATE TABLE %Q.'%q_content'(%s)",
  104274. p->zDb, p->zName, zContentCols
  104275. );
  104276. sqlite3_free(zContentCols);
  104277. /* Create other tables */
  104278. fts3DbExec(&rc, db,
  104279. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  104280. p->zDb, p->zName
  104281. );
  104282. fts3DbExec(&rc, db,
  104283. "CREATE TABLE %Q.'%q_segdir'("
  104284. "level INTEGER,"
  104285. "idx INTEGER,"
  104286. "start_block INTEGER,"
  104287. "leaves_end_block INTEGER,"
  104288. "end_block INTEGER,"
  104289. "root BLOB,"
  104290. "PRIMARY KEY(level, idx)"
  104291. ");",
  104292. p->zDb, p->zName
  104293. );
  104294. if( p->bHasDocsize ){
  104295. fts3DbExec(&rc, db,
  104296. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  104297. p->zDb, p->zName
  104298. );
  104299. }
  104300. if( p->bHasStat ){
  104301. fts3DbExec(&rc, db,
  104302. "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
  104303. p->zDb, p->zName
  104304. );
  104305. }
  104306. return rc;
  104307. }
  104308. /*
  104309. ** Store the current database page-size in bytes in p->nPgsz.
  104310. **
  104311. ** If *pRc is non-zero when this function is called, it is a no-op.
  104312. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  104313. ** before returning.
  104314. */
  104315. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  104316. if( *pRc==SQLITE_OK ){
  104317. int rc; /* Return code */
  104318. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  104319. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  104320. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  104321. if( !zSql ){
  104322. rc = SQLITE_NOMEM;
  104323. }else{
  104324. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  104325. if( rc==SQLITE_OK ){
  104326. sqlite3_step(pStmt);
  104327. p->nPgsz = sqlite3_column_int(pStmt, 0);
  104328. rc = sqlite3_finalize(pStmt);
  104329. }
  104330. }
  104331. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  104332. sqlite3_free(zSql);
  104333. *pRc = rc;
  104334. }
  104335. }
  104336. /*
  104337. ** "Special" FTS4 arguments are column specifications of the following form:
  104338. **
  104339. ** <key> = <value>
  104340. **
  104341. ** There may not be whitespace surrounding the "=" character. The <value>
  104342. ** term may be quoted, but the <key> may not.
  104343. */
  104344. static int fts3IsSpecialColumn(
  104345. const char *z,
  104346. int *pnKey,
  104347. char **pzValue
  104348. ){
  104349. char *zValue;
  104350. const char *zCsr = z;
  104351. while( *zCsr!='=' ){
  104352. if( *zCsr=='\0' ) return 0;
  104353. zCsr++;
  104354. }
  104355. *pnKey = (int)(zCsr-z);
  104356. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  104357. if( zValue ){
  104358. sqlite3Fts3Dequote(zValue);
  104359. }
  104360. *pzValue = zValue;
  104361. return 1;
  104362. }
  104363. /*
  104364. ** Append the output of a printf() style formatting to an existing string.
  104365. */
  104366. static void fts3Appendf(
  104367. int *pRc, /* IN/OUT: Error code */
  104368. char **pz, /* IN/OUT: Pointer to string buffer */
  104369. const char *zFormat, /* Printf format string to append */
  104370. ... /* Arguments for printf format string */
  104371. ){
  104372. if( *pRc==SQLITE_OK ){
  104373. va_list ap;
  104374. char *z;
  104375. va_start(ap, zFormat);
  104376. z = sqlite3_vmprintf(zFormat, ap);
  104377. if( z && *pz ){
  104378. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  104379. sqlite3_free(z);
  104380. z = z2;
  104381. }
  104382. if( z==0 ) *pRc = SQLITE_NOMEM;
  104383. sqlite3_free(*pz);
  104384. *pz = z;
  104385. }
  104386. }
  104387. /*
  104388. ** Return a copy of input string zInput enclosed in double-quotes (") and
  104389. ** with all double quote characters escaped. For example:
  104390. **
  104391. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  104392. **
  104393. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  104394. ** is the callers responsibility to call sqlite3_free() to release this
  104395. ** memory.
  104396. */
  104397. static char *fts3QuoteId(char const *zInput){
  104398. int nRet;
  104399. char *zRet;
  104400. nRet = 2 + strlen(zInput)*2 + 1;
  104401. zRet = sqlite3_malloc(nRet);
  104402. if( zRet ){
  104403. int i;
  104404. char *z = zRet;
  104405. *(z++) = '"';
  104406. for(i=0; zInput[i]; i++){
  104407. if( zInput[i]=='"' ) *(z++) = '"';
  104408. *(z++) = zInput[i];
  104409. }
  104410. *(z++) = '"';
  104411. *(z++) = '\0';
  104412. }
  104413. return zRet;
  104414. }
  104415. /*
  104416. ** Return a list of comma separated SQL expressions that could be used
  104417. ** in a SELECT statement such as the following:
  104418. **
  104419. ** SELECT <list of expressions> FROM %_content AS x ...
  104420. **
  104421. ** to return the docid, followed by each column of text data in order
  104422. ** from left to write. If parameter zFunc is not NULL, then instead of
  104423. ** being returned directly each column of text data is passed to an SQL
  104424. ** function named zFunc first. For example, if zFunc is "unzip" and the
  104425. ** table has the three user-defined columns "a", "b", and "c", the following
  104426. ** string is returned:
  104427. **
  104428. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')"
  104429. **
  104430. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  104431. ** is the responsibility of the caller to eventually free it.
  104432. **
  104433. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  104434. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  104435. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  104436. ** no error occurs, *pRc is left unmodified.
  104437. */
  104438. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  104439. char *zRet = 0;
  104440. char *zFree = 0;
  104441. char *zFunction;
  104442. int i;
  104443. if( !zFunc ){
  104444. zFunction = "";
  104445. }else{
  104446. zFree = zFunction = fts3QuoteId(zFunc);
  104447. }
  104448. fts3Appendf(pRc, &zRet, "docid");
  104449. for(i=0; i<p->nColumn; i++){
  104450. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  104451. }
  104452. sqlite3_free(zFree);
  104453. return zRet;
  104454. }
  104455. /*
  104456. ** Return a list of N comma separated question marks, where N is the number
  104457. ** of columns in the %_content table (one for the docid plus one for each
  104458. ** user-defined text column).
  104459. **
  104460. ** If argument zFunc is not NULL, then all but the first question mark
  104461. ** is preceded by zFunc and an open bracket, and followed by a closed
  104462. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  104463. ** user-defined text columns, the following string is returned:
  104464. **
  104465. ** "?, zip(?), zip(?), zip(?)"
  104466. **
  104467. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  104468. ** is the responsibility of the caller to eventually free it.
  104469. **
  104470. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  104471. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  104472. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  104473. ** no error occurs, *pRc is left unmodified.
  104474. */
  104475. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  104476. char *zRet = 0;
  104477. char *zFree = 0;
  104478. char *zFunction;
  104479. int i;
  104480. if( !zFunc ){
  104481. zFunction = "";
  104482. }else{
  104483. zFree = zFunction = fts3QuoteId(zFunc);
  104484. }
  104485. fts3Appendf(pRc, &zRet, "?");
  104486. for(i=0; i<p->nColumn; i++){
  104487. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  104488. }
  104489. sqlite3_free(zFree);
  104490. return zRet;
  104491. }
  104492. /*
  104493. ** This function is the implementation of both the xConnect and xCreate
  104494. ** methods of the FTS3 virtual table.
  104495. **
  104496. ** The argv[] array contains the following:
  104497. **
  104498. ** argv[0] -> module name ("fts3" or "fts4")
  104499. ** argv[1] -> database name
  104500. ** argv[2] -> table name
  104501. ** argv[...] -> "column name" and other module argument fields.
  104502. */
  104503. static int fts3InitVtab(
  104504. int isCreate, /* True for xCreate, false for xConnect */
  104505. sqlite3 *db, /* The SQLite database connection */
  104506. void *pAux, /* Hash table containing tokenizers */
  104507. int argc, /* Number of elements in argv array */
  104508. const char * const *argv, /* xCreate/xConnect argument array */
  104509. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  104510. char **pzErr /* Write any error message here */
  104511. ){
  104512. Fts3Hash *pHash = (Fts3Hash *)pAux;
  104513. Fts3Table *p = 0; /* Pointer to allocated vtab */
  104514. int rc = SQLITE_OK; /* Return code */
  104515. int i; /* Iterator variable */
  104516. int nByte; /* Size of allocation used for *p */
  104517. int iCol; /* Column index */
  104518. int nString = 0; /* Bytes required to hold all column names */
  104519. int nCol = 0; /* Number of columns in the FTS table */
  104520. char *zCsr; /* Space for holding column names */
  104521. int nDb; /* Bytes required to hold database name */
  104522. int nName; /* Bytes required to hold table name */
  104523. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  104524. int bNoDocsize = 0; /* True to omit %_docsize table */
  104525. const char **aCol; /* Array of column names */
  104526. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  104527. char *zCompress = 0;
  104528. char *zUncompress = 0;
  104529. assert( strlen(argv[0])==4 );
  104530. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  104531. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  104532. );
  104533. nDb = (int)strlen(argv[1]) + 1;
  104534. nName = (int)strlen(argv[2]) + 1;
  104535. aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
  104536. if( !aCol ) return SQLITE_NOMEM;
  104537. memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
  104538. /* Loop through all of the arguments passed by the user to the FTS3/4
  104539. ** module (i.e. all the column names and special arguments). This loop
  104540. ** does the following:
  104541. **
  104542. ** + Figures out the number of columns the FTSX table will have, and
  104543. ** the number of bytes of space that must be allocated to store copies
  104544. ** of the column names.
  104545. **
  104546. ** + If there is a tokenizer specification included in the arguments,
  104547. ** initializes the tokenizer pTokenizer.
  104548. */
  104549. for(i=3; rc==SQLITE_OK && i<argc; i++){
  104550. char const *z = argv[i];
  104551. int nKey;
  104552. char *zVal;
  104553. /* Check if this is a tokenizer specification */
  104554. if( !pTokenizer
  104555. && strlen(z)>8
  104556. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  104557. && 0==sqlite3Fts3IsIdChar(z[8])
  104558. ){
  104559. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  104560. }
  104561. /* Check if it is an FTS4 special argument. */
  104562. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  104563. if( !zVal ){
  104564. rc = SQLITE_NOMEM;
  104565. goto fts3_init_out;
  104566. }
  104567. if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
  104568. if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
  104569. bNoDocsize = 1;
  104570. }else{
  104571. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  104572. rc = SQLITE_ERROR;
  104573. }
  104574. }else if( nKey==8 && 0==sqlite3_strnicmp(z, "compress", 8) ){
  104575. zCompress = zVal;
  104576. zVal = 0;
  104577. }else if( nKey==10 && 0==sqlite3_strnicmp(z, "uncompress", 10) ){
  104578. zUncompress = zVal;
  104579. zVal = 0;
  104580. }else{
  104581. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  104582. rc = SQLITE_ERROR;
  104583. }
  104584. sqlite3_free(zVal);
  104585. }
  104586. /* Otherwise, the argument is a column name. */
  104587. else {
  104588. nString += (int)(strlen(z) + 1);
  104589. aCol[nCol++] = z;
  104590. }
  104591. }
  104592. if( rc!=SQLITE_OK ) goto fts3_init_out;
  104593. if( nCol==0 ){
  104594. assert( nString==0 );
  104595. aCol[0] = "content";
  104596. nString = 8;
  104597. nCol = 1;
  104598. }
  104599. if( pTokenizer==0 ){
  104600. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  104601. if( rc!=SQLITE_OK ) goto fts3_init_out;
  104602. }
  104603. assert( pTokenizer );
  104604. /* Allocate and populate the Fts3Table structure. */
  104605. nByte = sizeof(Fts3Table) + /* Fts3Table */
  104606. nCol * sizeof(char *) + /* azColumn */
  104607. nName + /* zName */
  104608. nDb + /* zDb */
  104609. nString; /* Space for azColumn strings */
  104610. p = (Fts3Table*)sqlite3_malloc(nByte);
  104611. if( p==0 ){
  104612. rc = SQLITE_NOMEM;
  104613. goto fts3_init_out;
  104614. }
  104615. memset(p, 0, nByte);
  104616. p->db = db;
  104617. p->nColumn = nCol;
  104618. p->nPendingData = 0;
  104619. p->azColumn = (char **)&p[1];
  104620. p->pTokenizer = pTokenizer;
  104621. p->nNodeSize = 1000;
  104622. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  104623. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  104624. p->bHasStat = isFts4;
  104625. fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
  104626. /* Fill in the zName and zDb fields of the vtab structure. */
  104627. zCsr = (char *)&p->azColumn[nCol];
  104628. p->zName = zCsr;
  104629. memcpy(zCsr, argv[2], nName);
  104630. zCsr += nName;
  104631. p->zDb = zCsr;
  104632. memcpy(zCsr, argv[1], nDb);
  104633. zCsr += nDb;
  104634. /* Fill in the azColumn array */
  104635. for(iCol=0; iCol<nCol; iCol++){
  104636. char *z;
  104637. int n;
  104638. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  104639. memcpy(zCsr, z, n);
  104640. zCsr[n] = '\0';
  104641. sqlite3Fts3Dequote(zCsr);
  104642. p->azColumn[iCol] = zCsr;
  104643. zCsr += n+1;
  104644. assert( zCsr <= &((char *)p)[nByte] );
  104645. }
  104646. if( (zCompress==0)!=(zUncompress==0) ){
  104647. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  104648. rc = SQLITE_ERROR;
  104649. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  104650. }
  104651. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  104652. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  104653. if( rc!=SQLITE_OK ) goto fts3_init_out;
  104654. /* If this is an xCreate call, create the underlying tables in the
  104655. ** database. TODO: For xConnect(), it could verify that said tables exist.
  104656. */
  104657. if( isCreate ){
  104658. rc = fts3CreateTables(p);
  104659. }
  104660. /* Figure out the page-size for the database. This is required in order to
  104661. ** estimate the cost of loading large doclists from the database (see
  104662. ** function sqlite3Fts3SegReaderCost() for details).
  104663. */
  104664. fts3DatabasePageSize(&rc, p);
  104665. /* Declare the table schema to SQLite. */
  104666. fts3DeclareVtab(&rc, p);
  104667. fts3_init_out:
  104668. sqlite3_free(zCompress);
  104669. sqlite3_free(zUncompress);
  104670. sqlite3_free((void *)aCol);
  104671. if( rc!=SQLITE_OK ){
  104672. if( p ){
  104673. fts3DisconnectMethod((sqlite3_vtab *)p);
  104674. }else if( pTokenizer ){
  104675. pTokenizer->pModule->xDestroy(pTokenizer);
  104676. }
  104677. }else{
  104678. *ppVTab = &p->base;
  104679. }
  104680. return rc;
  104681. }
  104682. /*
  104683. ** The xConnect() and xCreate() methods for the virtual table. All the
  104684. ** work is done in function fts3InitVtab().
  104685. */
  104686. static int fts3ConnectMethod(
  104687. sqlite3 *db, /* Database connection */
  104688. void *pAux, /* Pointer to tokenizer hash table */
  104689. int argc, /* Number of elements in argv array */
  104690. const char * const *argv, /* xCreate/xConnect argument array */
  104691. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  104692. char **pzErr /* OUT: sqlite3_malloc'd error message */
  104693. ){
  104694. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  104695. }
  104696. static int fts3CreateMethod(
  104697. sqlite3 *db, /* Database connection */
  104698. void *pAux, /* Pointer to tokenizer hash table */
  104699. int argc, /* Number of elements in argv array */
  104700. const char * const *argv, /* xCreate/xConnect argument array */
  104701. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  104702. char **pzErr /* OUT: sqlite3_malloc'd error message */
  104703. ){
  104704. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  104705. }
  104706. /*
  104707. ** Implementation of the xBestIndex method for FTS3 tables. There
  104708. ** are three possible strategies, in order of preference:
  104709. **
  104710. ** 1. Direct lookup by rowid or docid.
  104711. ** 2. Full-text search using a MATCH operator on a non-docid column.
  104712. ** 3. Linear scan of %_content table.
  104713. */
  104714. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  104715. Fts3Table *p = (Fts3Table *)pVTab;
  104716. int i; /* Iterator variable */
  104717. int iCons = -1; /* Index of constraint to use */
  104718. /* By default use a full table scan. This is an expensive option,
  104719. ** so search through the constraints to see if a more efficient
  104720. ** strategy is possible.
  104721. */
  104722. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  104723. pInfo->estimatedCost = 500000;
  104724. for(i=0; i<pInfo->nConstraint; i++){
  104725. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  104726. if( pCons->usable==0 ) continue;
  104727. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  104728. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  104729. && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
  104730. ){
  104731. pInfo->idxNum = FTS3_DOCID_SEARCH;
  104732. pInfo->estimatedCost = 1.0;
  104733. iCons = i;
  104734. }
  104735. /* A MATCH constraint. Use a full-text search.
  104736. **
  104737. ** If there is more than one MATCH constraint available, use the first
  104738. ** one encountered. If there is both a MATCH constraint and a direct
  104739. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  104740. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  104741. ** it would lead to an "unable to use function MATCH in the requested
  104742. ** context" error.
  104743. */
  104744. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  104745. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  104746. ){
  104747. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  104748. pInfo->estimatedCost = 2.0;
  104749. iCons = i;
  104750. break;
  104751. }
  104752. }
  104753. if( iCons>=0 ){
  104754. pInfo->aConstraintUsage[iCons].argvIndex = 1;
  104755. pInfo->aConstraintUsage[iCons].omit = 1;
  104756. }
  104757. return SQLITE_OK;
  104758. }
  104759. /*
  104760. ** Implementation of xOpen method.
  104761. */
  104762. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  104763. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  104764. UNUSED_PARAMETER(pVTab);
  104765. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  104766. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  104767. ** if the allocation fails, return SQLITE_NOMEM.
  104768. */
  104769. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  104770. if( !pCsr ){
  104771. return SQLITE_NOMEM;
  104772. }
  104773. memset(pCsr, 0, sizeof(Fts3Cursor));
  104774. return SQLITE_OK;
  104775. }
  104776. /*
  104777. ** Close the cursor. For additional information see the documentation
  104778. ** on the xClose method of the virtual table interface.
  104779. */
  104780. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  104781. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  104782. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  104783. sqlite3_finalize(pCsr->pStmt);
  104784. sqlite3Fts3ExprFree(pCsr->pExpr);
  104785. sqlite3Fts3FreeDeferredTokens(pCsr);
  104786. sqlite3_free(pCsr->aDoclist);
  104787. sqlite3_free(pCsr->aMatchinfo);
  104788. sqlite3_free(pCsr);
  104789. return SQLITE_OK;
  104790. }
  104791. /*
  104792. ** Position the pCsr->pStmt statement so that it is on the row
  104793. ** of the %_content table that contains the last match. Return
  104794. ** SQLITE_OK on success.
  104795. */
  104796. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  104797. if( pCsr->isRequireSeek ){
  104798. pCsr->isRequireSeek = 0;
  104799. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  104800. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  104801. return SQLITE_OK;
  104802. }else{
  104803. int rc = sqlite3_reset(pCsr->pStmt);
  104804. if( rc==SQLITE_OK ){
  104805. /* If no row was found and no error has occured, then the %_content
  104806. ** table is missing a row that is present in the full-text index.
  104807. ** The data structures are corrupt.
  104808. */
  104809. rc = SQLITE_CORRUPT;
  104810. }
  104811. pCsr->isEof = 1;
  104812. if( pContext ){
  104813. sqlite3_result_error_code(pContext, rc);
  104814. }
  104815. return rc;
  104816. }
  104817. }else{
  104818. return SQLITE_OK;
  104819. }
  104820. }
  104821. /*
  104822. ** This function is used to process a single interior node when searching
  104823. ** a b-tree for a term or term prefix. The node data is passed to this
  104824. ** function via the zNode/nNode parameters. The term to search for is
  104825. ** passed in zTerm/nTerm.
  104826. **
  104827. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  104828. ** of the child node that heads the sub-tree that may contain the term.
  104829. **
  104830. ** If piLast is not NULL, then *piLast is set to the right-most child node
  104831. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  104832. ** a prefix.
  104833. **
  104834. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  104835. */
  104836. static int fts3ScanInteriorNode(
  104837. const char *zTerm, /* Term to select leaves for */
  104838. int nTerm, /* Size of term zTerm in bytes */
  104839. const char *zNode, /* Buffer containing segment interior node */
  104840. int nNode, /* Size of buffer at zNode */
  104841. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  104842. sqlite3_int64 *piLast /* OUT: Selected child node */
  104843. ){
  104844. int rc = SQLITE_OK; /* Return code */
  104845. const char *zCsr = zNode; /* Cursor to iterate through node */
  104846. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  104847. char *zBuffer = 0; /* Buffer to load terms into */
  104848. int nAlloc = 0; /* Size of allocated buffer */
  104849. int isFirstTerm = 1; /* True when processing first term on page */
  104850. sqlite3_int64 iChild; /* Block id of child node to descend to */
  104851. /* Skip over the 'height' varint that occurs at the start of every
  104852. ** interior node. Then load the blockid of the left-child of the b-tree
  104853. ** node into variable iChild.
  104854. **
  104855. ** Even if the data structure on disk is corrupted, this (reading two
  104856. ** varints from the buffer) does not risk an overread. If zNode is a
  104857. ** root node, then the buffer comes from a SELECT statement. SQLite does
  104858. ** not make this guarantee explicitly, but in practice there are always
  104859. ** either more than 20 bytes of allocated space following the nNode bytes of
  104860. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  104861. ** table, then there are always 20 bytes of zeroed padding following the
  104862. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  104863. */
  104864. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  104865. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  104866. if( zCsr>zEnd ){
  104867. return SQLITE_CORRUPT;
  104868. }
  104869. while( zCsr<zEnd && (piFirst || piLast) ){
  104870. int cmp; /* memcmp() result */
  104871. int nSuffix; /* Size of term suffix */
  104872. int nPrefix = 0; /* Size of term prefix */
  104873. int nBuffer; /* Total term size */
  104874. /* Load the next term on the node into zBuffer. Use realloc() to expand
  104875. ** the size of zBuffer if required. */
  104876. if( !isFirstTerm ){
  104877. zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
  104878. }
  104879. isFirstTerm = 0;
  104880. zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
  104881. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  104882. rc = SQLITE_CORRUPT;
  104883. goto finish_scan;
  104884. }
  104885. if( nPrefix+nSuffix>nAlloc ){
  104886. char *zNew;
  104887. nAlloc = (nPrefix+nSuffix) * 2;
  104888. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  104889. if( !zNew ){
  104890. rc = SQLITE_NOMEM;
  104891. goto finish_scan;
  104892. }
  104893. zBuffer = zNew;
  104894. }
  104895. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  104896. nBuffer = nPrefix + nSuffix;
  104897. zCsr += nSuffix;
  104898. /* Compare the term we are searching for with the term just loaded from
  104899. ** the interior node. If the specified term is greater than or equal
  104900. ** to the term from the interior node, then all terms on the sub-tree
  104901. ** headed by node iChild are smaller than zTerm. No need to search
  104902. ** iChild.
  104903. **
  104904. ** If the interior node term is larger than the specified term, then
  104905. ** the tree headed by iChild may contain the specified term.
  104906. */
  104907. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  104908. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  104909. *piFirst = iChild;
  104910. piFirst = 0;
  104911. }
  104912. if( piLast && cmp<0 ){
  104913. *piLast = iChild;
  104914. piLast = 0;
  104915. }
  104916. iChild++;
  104917. };
  104918. if( piFirst ) *piFirst = iChild;
  104919. if( piLast ) *piLast = iChild;
  104920. finish_scan:
  104921. sqlite3_free(zBuffer);
  104922. return rc;
  104923. }
  104924. /*
  104925. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  104926. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  104927. ** contains a term. This function searches the sub-tree headed by the zNode
  104928. ** node for the range of leaf nodes that may contain the specified term
  104929. ** or terms for which the specified term is a prefix.
  104930. **
  104931. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  104932. ** left-most leaf node in the tree that may contain the specified term.
  104933. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  104934. ** right-most leaf node that may contain a term for which the specified
  104935. ** term is a prefix.
  104936. **
  104937. ** It is possible that the range of returned leaf nodes does not contain
  104938. ** the specified term or any terms for which it is a prefix. However, if the
  104939. ** segment does contain any such terms, they are stored within the identified
  104940. ** range. Because this function only inspects interior segment nodes (and
  104941. ** never loads leaf nodes into memory), it is not possible to be sure.
  104942. **
  104943. ** If an error occurs, an error code other than SQLITE_OK is returned.
  104944. */
  104945. static int fts3SelectLeaf(
  104946. Fts3Table *p, /* Virtual table handle */
  104947. const char *zTerm, /* Term to select leaves for */
  104948. int nTerm, /* Size of term zTerm in bytes */
  104949. const char *zNode, /* Buffer containing segment interior node */
  104950. int nNode, /* Size of buffer at zNode */
  104951. sqlite3_int64 *piLeaf, /* Selected leaf node */
  104952. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  104953. ){
  104954. int rc; /* Return code */
  104955. int iHeight; /* Height of this node in tree */
  104956. assert( piLeaf || piLeaf2 );
  104957. sqlite3Fts3GetVarint32(zNode, &iHeight);
  104958. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  104959. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  104960. if( rc==SQLITE_OK && iHeight>1 ){
  104961. char *zBlob = 0; /* Blob read from %_segments table */
  104962. int nBlob; /* Size of zBlob in bytes */
  104963. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  104964. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
  104965. if( rc==SQLITE_OK ){
  104966. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  104967. }
  104968. sqlite3_free(zBlob);
  104969. piLeaf = 0;
  104970. zBlob = 0;
  104971. }
  104972. if( rc==SQLITE_OK ){
  104973. rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
  104974. }
  104975. if( rc==SQLITE_OK ){
  104976. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  104977. }
  104978. sqlite3_free(zBlob);
  104979. }
  104980. return rc;
  104981. }
  104982. /*
  104983. ** This function is used to create delta-encoded serialized lists of FTS3
  104984. ** varints. Each call to this function appends a single varint to a list.
  104985. */
  104986. static void fts3PutDeltaVarint(
  104987. char **pp, /* IN/OUT: Output pointer */
  104988. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  104989. sqlite3_int64 iVal /* Write this value to the list */
  104990. ){
  104991. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  104992. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  104993. *piPrev = iVal;
  104994. }
  104995. /*
  104996. ** When this function is called, *ppPoslist is assumed to point to the
  104997. ** start of a position-list. After it returns, *ppPoslist points to the
  104998. ** first byte after the position-list.
  104999. **
  105000. ** A position list is list of positions (delta encoded) and columns for
  105001. ** a single document record of a doclist. So, in other words, this
  105002. ** routine advances *ppPoslist so that it points to the next docid in
  105003. ** the doclist, or to the first byte past the end of the doclist.
  105004. **
  105005. ** If pp is not NULL, then the contents of the position list are copied
  105006. ** to *pp. *pp is set to point to the first byte past the last byte copied
  105007. ** before this function returns.
  105008. */
  105009. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  105010. char *pEnd = *ppPoslist;
  105011. char c = 0;
  105012. /* The end of a position list is marked by a zero encoded as an FTS3
  105013. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  105014. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  105015. ** of some other, multi-byte, value.
  105016. **
  105017. ** The following while-loop moves pEnd to point to the first byte that is not
  105018. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  105019. ** pEnd once more so that it points to the byte immediately following the
  105020. ** last byte in the position-list.
  105021. */
  105022. while( *pEnd | c ){
  105023. c = *pEnd++ & 0x80;
  105024. testcase( c!=0 && (*pEnd)==0 );
  105025. }
  105026. pEnd++; /* Advance past the POS_END terminator byte */
  105027. if( pp ){
  105028. int n = (int)(pEnd - *ppPoslist);
  105029. char *p = *pp;
  105030. memcpy(p, *ppPoslist, n);
  105031. p += n;
  105032. *pp = p;
  105033. }
  105034. *ppPoslist = pEnd;
  105035. }
  105036. /*
  105037. ** When this function is called, *ppPoslist is assumed to point to the
  105038. ** start of a column-list. After it returns, *ppPoslist points to the
  105039. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  105040. **
  105041. ** A column-list is list of delta-encoded positions for a single column
  105042. ** within a single document within a doclist.
  105043. **
  105044. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  105045. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  105046. ** the POS_COLUMN or POS_END that terminates the column-list.
  105047. **
  105048. ** If pp is not NULL, then the contents of the column-list are copied
  105049. ** to *pp. *pp is set to point to the first byte past the last byte copied
  105050. ** before this function returns. The POS_COLUMN or POS_END terminator
  105051. ** is not copied into *pp.
  105052. */
  105053. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  105054. char *pEnd = *ppPoslist;
  105055. char c = 0;
  105056. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  105057. ** not part of a multi-byte varint.
  105058. */
  105059. while( 0xFE & (*pEnd | c) ){
  105060. c = *pEnd++ & 0x80;
  105061. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  105062. }
  105063. if( pp ){
  105064. int n = (int)(pEnd - *ppPoslist);
  105065. char *p = *pp;
  105066. memcpy(p, *ppPoslist, n);
  105067. p += n;
  105068. *pp = p;
  105069. }
  105070. *ppPoslist = pEnd;
  105071. }
  105072. /*
  105073. ** Value used to signify the end of an position-list. This is safe because
  105074. ** it is not possible to have a document with 2^31 terms.
  105075. */
  105076. #define POSITION_LIST_END 0x7fffffff
  105077. /*
  105078. ** This function is used to help parse position-lists. When this function is
  105079. ** called, *pp may point to the start of the next varint in the position-list
  105080. ** being parsed, or it may point to 1 byte past the end of the position-list
  105081. ** (in which case **pp will be a terminator bytes POS_END (0) or
  105082. ** (1)).
  105083. **
  105084. ** If *pp points past the end of the current position-list, set *pi to
  105085. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  105086. ** increment the current value of *pi by the value read, and set *pp to
  105087. ** point to the next value before returning.
  105088. **
  105089. ** Before calling this routine *pi must be initialized to the value of
  105090. ** the previous position, or zero if we are reading the first position
  105091. ** in the position-list. Because positions are delta-encoded, the value
  105092. ** of the previous position is needed in order to compute the value of
  105093. ** the next position.
  105094. */
  105095. static void fts3ReadNextPos(
  105096. char **pp, /* IN/OUT: Pointer into position-list buffer */
  105097. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  105098. ){
  105099. if( (**pp)&0xFE ){
  105100. fts3GetDeltaVarint(pp, pi);
  105101. *pi -= 2;
  105102. }else{
  105103. *pi = POSITION_LIST_END;
  105104. }
  105105. }
  105106. /*
  105107. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  105108. ** the value of iCol encoded as a varint to *pp. This will start a new
  105109. ** column list.
  105110. **
  105111. ** Set *pp to point to the byte just after the last byte written before
  105112. ** returning (do not modify it if iCol==0). Return the total number of bytes
  105113. ** written (0 if iCol==0).
  105114. */
  105115. static int fts3PutColNumber(char **pp, int iCol){
  105116. int n = 0; /* Number of bytes written */
  105117. if( iCol ){
  105118. char *p = *pp; /* Output pointer */
  105119. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  105120. *p = 0x01;
  105121. *pp = &p[n];
  105122. }
  105123. return n;
  105124. }
  105125. /*
  105126. ** Compute the union of two position lists. The output written
  105127. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  105128. ** order and with any duplicates removed. All pointers are
  105129. ** updated appropriately. The caller is responsible for insuring
  105130. ** that there is enough space in *pp to hold the complete output.
  105131. */
  105132. static void fts3PoslistMerge(
  105133. char **pp, /* Output buffer */
  105134. char **pp1, /* Left input list */
  105135. char **pp2 /* Right input list */
  105136. ){
  105137. char *p = *pp;
  105138. char *p1 = *pp1;
  105139. char *p2 = *pp2;
  105140. while( *p1 || *p2 ){
  105141. int iCol1; /* The current column index in pp1 */
  105142. int iCol2; /* The current column index in pp2 */
  105143. if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
  105144. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  105145. else iCol1 = 0;
  105146. if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
  105147. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  105148. else iCol2 = 0;
  105149. if( iCol1==iCol2 ){
  105150. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  105151. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  105152. sqlite3_int64 iPrev = 0;
  105153. int n = fts3PutColNumber(&p, iCol1);
  105154. p1 += n;
  105155. p2 += n;
  105156. /* At this point, both p1 and p2 point to the start of column-lists
  105157. ** for the same column (the column with index iCol1 and iCol2).
  105158. ** A column-list is a list of non-negative delta-encoded varints, each
  105159. ** incremented by 2 before being stored. Each list is terminated by a
  105160. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  105161. ** and writes the results to buffer p. p is left pointing to the byte
  105162. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  105163. ** written to the output.
  105164. */
  105165. fts3GetDeltaVarint(&p1, &i1);
  105166. fts3GetDeltaVarint(&p2, &i2);
  105167. do {
  105168. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  105169. iPrev -= 2;
  105170. if( i1==i2 ){
  105171. fts3ReadNextPos(&p1, &i1);
  105172. fts3ReadNextPos(&p2, &i2);
  105173. }else if( i1<i2 ){
  105174. fts3ReadNextPos(&p1, &i1);
  105175. }else{
  105176. fts3ReadNextPos(&p2, &i2);
  105177. }
  105178. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  105179. }else if( iCol1<iCol2 ){
  105180. p1 += fts3PutColNumber(&p, iCol1);
  105181. fts3ColumnlistCopy(&p, &p1);
  105182. }else{
  105183. p2 += fts3PutColNumber(&p, iCol2);
  105184. fts3ColumnlistCopy(&p, &p2);
  105185. }
  105186. }
  105187. *p++ = POS_END;
  105188. *pp = p;
  105189. *pp1 = p1 + 1;
  105190. *pp2 = p2 + 1;
  105191. }
  105192. /*
  105193. ** nToken==1 searches for adjacent positions.
  105194. **
  105195. ** This function is used to merge two position lists into one. When it is
  105196. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  105197. ** the part of a doclist that follows each document id. For example, if a row
  105198. ** contains:
  105199. **
  105200. ** 'a b c'|'x y z'|'a b b a'
  105201. **
  105202. ** Then the position list for this row for token 'b' would consist of:
  105203. **
  105204. ** 0x02 0x01 0x02 0x03 0x03 0x00
  105205. **
  105206. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  105207. ** byte following the 0x00 terminator of their respective position lists.
  105208. **
  105209. ** If isSaveLeft is 0, an entry is added to the output position list for
  105210. ** each position in *pp2 for which there exists one or more positions in
  105211. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  105212. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  105213. ** slots before it.
  105214. */
  105215. static int fts3PoslistPhraseMerge(
  105216. char **pp, /* IN/OUT: Preallocated output buffer */
  105217. int nToken, /* Maximum difference in token positions */
  105218. int isSaveLeft, /* Save the left position */
  105219. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  105220. char **pp1, /* IN/OUT: Left input list */
  105221. char **pp2 /* IN/OUT: Right input list */
  105222. ){
  105223. char *p = (pp ? *pp : 0);
  105224. char *p1 = *pp1;
  105225. char *p2 = *pp2;
  105226. int iCol1 = 0;
  105227. int iCol2 = 0;
  105228. /* Never set both isSaveLeft and isExact for the same invocation. */
  105229. assert( isSaveLeft==0 || isExact==0 );
  105230. assert( *p1!=0 && *p2!=0 );
  105231. if( *p1==POS_COLUMN ){
  105232. p1++;
  105233. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  105234. }
  105235. if( *p2==POS_COLUMN ){
  105236. p2++;
  105237. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  105238. }
  105239. while( 1 ){
  105240. if( iCol1==iCol2 ){
  105241. char *pSave = p;
  105242. sqlite3_int64 iPrev = 0;
  105243. sqlite3_int64 iPos1 = 0;
  105244. sqlite3_int64 iPos2 = 0;
  105245. if( pp && iCol1 ){
  105246. *p++ = POS_COLUMN;
  105247. p += sqlite3Fts3PutVarint(p, iCol1);
  105248. }
  105249. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  105250. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  105251. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  105252. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  105253. while( 1 ){
  105254. if( iPos2==iPos1+nToken
  105255. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  105256. ){
  105257. sqlite3_int64 iSave;
  105258. if( !pp ){
  105259. fts3PoslistCopy(0, &p2);
  105260. fts3PoslistCopy(0, &p1);
  105261. *pp1 = p1;
  105262. *pp2 = p2;
  105263. return 1;
  105264. }
  105265. iSave = isSaveLeft ? iPos1 : iPos2;
  105266. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  105267. pSave = 0;
  105268. }
  105269. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  105270. if( (*p2&0xFE)==0 ) break;
  105271. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  105272. }else{
  105273. if( (*p1&0xFE)==0 ) break;
  105274. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  105275. }
  105276. }
  105277. if( pSave ){
  105278. assert( pp && p );
  105279. p = pSave;
  105280. }
  105281. fts3ColumnlistCopy(0, &p1);
  105282. fts3ColumnlistCopy(0, &p2);
  105283. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  105284. if( 0==*p1 || 0==*p2 ) break;
  105285. p1++;
  105286. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  105287. p2++;
  105288. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  105289. }
  105290. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  105291. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  105292. ** end of the position list, or the 0x01 that precedes the next
  105293. ** column-number in the position list.
  105294. */
  105295. else if( iCol1<iCol2 ){
  105296. fts3ColumnlistCopy(0, &p1);
  105297. if( 0==*p1 ) break;
  105298. p1++;
  105299. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  105300. }else{
  105301. fts3ColumnlistCopy(0, &p2);
  105302. if( 0==*p2 ) break;
  105303. p2++;
  105304. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  105305. }
  105306. }
  105307. fts3PoslistCopy(0, &p2);
  105308. fts3PoslistCopy(0, &p1);
  105309. *pp1 = p1;
  105310. *pp2 = p2;
  105311. if( !pp || *pp==p ){
  105312. return 0;
  105313. }
  105314. *p++ = 0x00;
  105315. *pp = p;
  105316. return 1;
  105317. }
  105318. /*
  105319. ** Merge two position-lists as required by the NEAR operator.
  105320. */
  105321. static int fts3PoslistNearMerge(
  105322. char **pp, /* Output buffer */
  105323. char *aTmp, /* Temporary buffer space */
  105324. int nRight, /* Maximum difference in token positions */
  105325. int nLeft, /* Maximum difference in token positions */
  105326. char **pp1, /* IN/OUT: Left input list */
  105327. char **pp2 /* IN/OUT: Right input list */
  105328. ){
  105329. char *p1 = *pp1;
  105330. char *p2 = *pp2;
  105331. if( !pp ){
  105332. if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
  105333. *pp1 = p1;
  105334. *pp2 = p2;
  105335. return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
  105336. }else{
  105337. char *pTmp1 = aTmp;
  105338. char *pTmp2;
  105339. char *aTmp2;
  105340. int res = 1;
  105341. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  105342. aTmp2 = pTmp2 = pTmp1;
  105343. *pp1 = p1;
  105344. *pp2 = p2;
  105345. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  105346. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  105347. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  105348. }else if( pTmp1!=aTmp ){
  105349. fts3PoslistCopy(pp, &aTmp);
  105350. }else if( pTmp2!=aTmp2 ){
  105351. fts3PoslistCopy(pp, &aTmp2);
  105352. }else{
  105353. res = 0;
  105354. }
  105355. return res;
  105356. }
  105357. }
  105358. /*
  105359. ** Values that may be used as the first parameter to fts3DoclistMerge().
  105360. */
  105361. #define MERGE_NOT 2 /* D + D -> D */
  105362. #define MERGE_AND 3 /* D + D -> D */
  105363. #define MERGE_OR 4 /* D + D -> D */
  105364. #define MERGE_POS_OR 5 /* P + P -> P */
  105365. #define MERGE_PHRASE 6 /* P + P -> D */
  105366. #define MERGE_POS_PHRASE 7 /* P + P -> P */
  105367. #define MERGE_NEAR 8 /* P + P -> D */
  105368. #define MERGE_POS_NEAR 9 /* P + P -> P */
  105369. /*
  105370. ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
  105371. ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
  105372. ** which is guaranteed to be large enough to hold the results. The number
  105373. ** of bytes written to aBuffer is stored in *pnBuffer before returning.
  105374. **
  105375. ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
  105376. ** occurs while allocating a temporary buffer as part of the merge operation,
  105377. ** SQLITE_NOMEM is returned.
  105378. */
  105379. static int fts3DoclistMerge(
  105380. int mergetype, /* One of the MERGE_XXX constants */
  105381. int nParam1, /* Used by MERGE_NEAR and MERGE_POS_NEAR */
  105382. int nParam2, /* Used by MERGE_NEAR and MERGE_POS_NEAR */
  105383. char *aBuffer, /* Pre-allocated output buffer */
  105384. int *pnBuffer, /* OUT: Bytes written to aBuffer */
  105385. char *a1, /* Buffer containing first doclist */
  105386. int n1, /* Size of buffer a1 */
  105387. char *a2, /* Buffer containing second doclist */
  105388. int n2, /* Size of buffer a2 */
  105389. int *pnDoc /* OUT: Number of docids in output */
  105390. ){
  105391. sqlite3_int64 i1 = 0;
  105392. sqlite3_int64 i2 = 0;
  105393. sqlite3_int64 iPrev = 0;
  105394. char *p = aBuffer;
  105395. char *p1 = a1;
  105396. char *p2 = a2;
  105397. char *pEnd1 = &a1[n1];
  105398. char *pEnd2 = &a2[n2];
  105399. int nDoc = 0;
  105400. assert( mergetype==MERGE_OR || mergetype==MERGE_POS_OR
  105401. || mergetype==MERGE_AND || mergetype==MERGE_NOT
  105402. || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
  105403. || mergetype==MERGE_NEAR || mergetype==MERGE_POS_NEAR
  105404. );
  105405. if( !aBuffer ){
  105406. *pnBuffer = 0;
  105407. return SQLITE_NOMEM;
  105408. }
  105409. /* Read the first docid from each doclist */
  105410. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105411. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105412. switch( mergetype ){
  105413. case MERGE_OR:
  105414. case MERGE_POS_OR:
  105415. while( p1 || p2 ){
  105416. if( p2 && p1 && i1==i2 ){
  105417. fts3PutDeltaVarint(&p, &iPrev, i1);
  105418. if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
  105419. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105420. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105421. }else if( !p2 || (p1 && i1<i2) ){
  105422. fts3PutDeltaVarint(&p, &iPrev, i1);
  105423. if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
  105424. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105425. }else{
  105426. fts3PutDeltaVarint(&p, &iPrev, i2);
  105427. if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
  105428. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105429. }
  105430. }
  105431. break;
  105432. case MERGE_AND:
  105433. while( p1 && p2 ){
  105434. if( i1==i2 ){
  105435. fts3PutDeltaVarint(&p, &iPrev, i1);
  105436. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105437. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105438. nDoc++;
  105439. }else if( i1<i2 ){
  105440. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105441. }else{
  105442. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105443. }
  105444. }
  105445. break;
  105446. case MERGE_NOT:
  105447. while( p1 ){
  105448. if( p2 && i1==i2 ){
  105449. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105450. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105451. }else if( !p2 || i1<i2 ){
  105452. fts3PutDeltaVarint(&p, &iPrev, i1);
  105453. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105454. }else{
  105455. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105456. }
  105457. }
  105458. break;
  105459. case MERGE_POS_PHRASE:
  105460. case MERGE_PHRASE: {
  105461. char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
  105462. while( p1 && p2 ){
  105463. if( i1==i2 ){
  105464. char *pSave = p;
  105465. sqlite3_int64 iPrevSave = iPrev;
  105466. fts3PutDeltaVarint(&p, &iPrev, i1);
  105467. if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
  105468. p = pSave;
  105469. iPrev = iPrevSave;
  105470. }else{
  105471. nDoc++;
  105472. }
  105473. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105474. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105475. }else if( i1<i2 ){
  105476. fts3PoslistCopy(0, &p1);
  105477. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105478. }else{
  105479. fts3PoslistCopy(0, &p2);
  105480. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105481. }
  105482. }
  105483. break;
  105484. }
  105485. default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
  105486. char *aTmp = 0;
  105487. char **ppPos = 0;
  105488. if( mergetype==MERGE_POS_NEAR ){
  105489. ppPos = &p;
  105490. aTmp = sqlite3_malloc(2*(n1+n2+1));
  105491. if( !aTmp ){
  105492. return SQLITE_NOMEM;
  105493. }
  105494. }
  105495. while( p1 && p2 ){
  105496. if( i1==i2 ){
  105497. char *pSave = p;
  105498. sqlite3_int64 iPrevSave = iPrev;
  105499. fts3PutDeltaVarint(&p, &iPrev, i1);
  105500. if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
  105501. iPrev = iPrevSave;
  105502. p = pSave;
  105503. }
  105504. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105505. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105506. }else if( i1<i2 ){
  105507. fts3PoslistCopy(0, &p1);
  105508. fts3GetDeltaVarint2(&p1, pEnd1, &i1);
  105509. }else{
  105510. fts3PoslistCopy(0, &p2);
  105511. fts3GetDeltaVarint2(&p2, pEnd2, &i2);
  105512. }
  105513. }
  105514. sqlite3_free(aTmp);
  105515. break;
  105516. }
  105517. }
  105518. if( pnDoc ) *pnDoc = nDoc;
  105519. *pnBuffer = (int)(p-aBuffer);
  105520. return SQLITE_OK;
  105521. }
  105522. /*
  105523. ** A pointer to an instance of this structure is used as the context
  105524. ** argument to sqlite3Fts3SegReaderIterate()
  105525. */
  105526. typedef struct TermSelect TermSelect;
  105527. struct TermSelect {
  105528. int isReqPos;
  105529. char *aaOutput[16]; /* Malloc'd output buffer */
  105530. int anOutput[16]; /* Size of output in bytes */
  105531. };
  105532. /*
  105533. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  105534. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  105535. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  105536. **
  105537. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  105538. ** the responsibility of the caller to free any doclists left in the
  105539. ** TermSelect.aaOutput[] array.
  105540. */
  105541. static int fts3TermSelectMerge(TermSelect *pTS){
  105542. int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
  105543. char *aOut = 0;
  105544. int nOut = 0;
  105545. int i;
  105546. /* Loop through the doclists in the aaOutput[] array. Merge them all
  105547. ** into a single doclist.
  105548. */
  105549. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  105550. if( pTS->aaOutput[i] ){
  105551. if( !aOut ){
  105552. aOut = pTS->aaOutput[i];
  105553. nOut = pTS->anOutput[i];
  105554. pTS->aaOutput[i] = 0;
  105555. }else{
  105556. int nNew = nOut + pTS->anOutput[i];
  105557. char *aNew = sqlite3_malloc(nNew);
  105558. if( !aNew ){
  105559. sqlite3_free(aOut);
  105560. return SQLITE_NOMEM;
  105561. }
  105562. fts3DoclistMerge(mergetype, 0, 0,
  105563. aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
  105564. );
  105565. sqlite3_free(pTS->aaOutput[i]);
  105566. sqlite3_free(aOut);
  105567. pTS->aaOutput[i] = 0;
  105568. aOut = aNew;
  105569. nOut = nNew;
  105570. }
  105571. }
  105572. }
  105573. pTS->aaOutput[0] = aOut;
  105574. pTS->anOutput[0] = nOut;
  105575. return SQLITE_OK;
  105576. }
  105577. /*
  105578. ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
  105579. ** querying the full-text index for a doclist associated with a term or
  105580. ** term-prefix.
  105581. */
  105582. static int fts3TermSelectCb(
  105583. Fts3Table *p, /* Virtual table object */
  105584. void *pContext, /* Pointer to TermSelect structure */
  105585. char *zTerm,
  105586. int nTerm,
  105587. char *aDoclist,
  105588. int nDoclist
  105589. ){
  105590. TermSelect *pTS = (TermSelect *)pContext;
  105591. UNUSED_PARAMETER(p);
  105592. UNUSED_PARAMETER(zTerm);
  105593. UNUSED_PARAMETER(nTerm);
  105594. if( pTS->aaOutput[0]==0 ){
  105595. /* If this is the first term selected, copy the doclist to the output
  105596. ** buffer using memcpy(). TODO: Add a way to transfer control of the
  105597. ** aDoclist buffer from the caller so as to avoid the memcpy().
  105598. */
  105599. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  105600. pTS->anOutput[0] = nDoclist;
  105601. if( pTS->aaOutput[0] ){
  105602. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  105603. }else{
  105604. return SQLITE_NOMEM;
  105605. }
  105606. }else{
  105607. int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
  105608. char *aMerge = aDoclist;
  105609. int nMerge = nDoclist;
  105610. int iOut;
  105611. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  105612. char *aNew;
  105613. int nNew;
  105614. if( pTS->aaOutput[iOut]==0 ){
  105615. assert( iOut>0 );
  105616. pTS->aaOutput[iOut] = aMerge;
  105617. pTS->anOutput[iOut] = nMerge;
  105618. break;
  105619. }
  105620. nNew = nMerge + pTS->anOutput[iOut];
  105621. aNew = sqlite3_malloc(nNew);
  105622. if( !aNew ){
  105623. if( aMerge!=aDoclist ){
  105624. sqlite3_free(aMerge);
  105625. }
  105626. return SQLITE_NOMEM;
  105627. }
  105628. fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew,
  105629. pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
  105630. );
  105631. if( iOut>0 ) sqlite3_free(aMerge);
  105632. sqlite3_free(pTS->aaOutput[iOut]);
  105633. pTS->aaOutput[iOut] = 0;
  105634. aMerge = aNew;
  105635. nMerge = nNew;
  105636. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  105637. pTS->aaOutput[iOut] = aMerge;
  105638. pTS->anOutput[iOut] = nMerge;
  105639. }
  105640. }
  105641. }
  105642. return SQLITE_OK;
  105643. }
  105644. static int fts3DeferredTermSelect(
  105645. Fts3DeferredToken *pToken, /* Phrase token */
  105646. int isTermPos, /* True to include positions */
  105647. int *pnOut, /* OUT: Size of list */
  105648. char **ppOut /* OUT: Body of list */
  105649. ){
  105650. char *aSource;
  105651. int nSource;
  105652. aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
  105653. if( !aSource ){
  105654. *pnOut = 0;
  105655. *ppOut = 0;
  105656. }else if( isTermPos ){
  105657. *ppOut = sqlite3_malloc(nSource);
  105658. if( !*ppOut ) return SQLITE_NOMEM;
  105659. memcpy(*ppOut, aSource, nSource);
  105660. *pnOut = nSource;
  105661. }else{
  105662. sqlite3_int64 docid;
  105663. *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
  105664. *ppOut = sqlite3_malloc(*pnOut);
  105665. if( !*ppOut ) return SQLITE_NOMEM;
  105666. sqlite3Fts3PutVarint(*ppOut, docid);
  105667. }
  105668. return SQLITE_OK;
  105669. }
  105670. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  105671. Fts3Table *p, /* FTS3 table handle */
  105672. int iLevel, /* Level of segments to scan */
  105673. const char *zTerm, /* Term to query for */
  105674. int nTerm, /* Size of zTerm in bytes */
  105675. int isPrefix, /* True for a prefix search */
  105676. int isScan, /* True to scan from zTerm to EOF */
  105677. Fts3SegReaderCursor *pCsr /* Cursor object to populate */
  105678. ){
  105679. int rc = SQLITE_OK;
  105680. int rc2;
  105681. int iAge = 0;
  105682. sqlite3_stmt *pStmt = 0;
  105683. Fts3SegReader *pPending = 0;
  105684. assert( iLevel==FTS3_SEGCURSOR_ALL
  105685. || iLevel==FTS3_SEGCURSOR_PENDING
  105686. || iLevel>=0
  105687. );
  105688. assert( FTS3_SEGCURSOR_PENDING<0 );
  105689. assert( FTS3_SEGCURSOR_ALL<0 );
  105690. assert( iLevel==FTS3_SEGCURSOR_ALL || (zTerm==0 && isPrefix==1) );
  105691. assert( isPrefix==0 || isScan==0 );
  105692. memset(pCsr, 0, sizeof(Fts3SegReaderCursor));
  105693. /* If iLevel is less than 0, include a seg-reader for the pending-terms. */
  105694. assert( isScan==0 || fts3HashCount(&p->pendingTerms)==0 );
  105695. if( iLevel<0 && isScan==0 ){
  105696. rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pPending);
  105697. if( rc==SQLITE_OK && pPending ){
  105698. int nByte = (sizeof(Fts3SegReader *) * 16);
  105699. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  105700. if( pCsr->apSegment==0 ){
  105701. rc = SQLITE_NOMEM;
  105702. }else{
  105703. pCsr->apSegment[0] = pPending;
  105704. pCsr->nSegment = 1;
  105705. pPending = 0;
  105706. }
  105707. }
  105708. }
  105709. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  105710. if( rc==SQLITE_OK ){
  105711. rc = sqlite3Fts3AllSegdirs(p, iLevel, &pStmt);
  105712. }
  105713. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  105714. /* Read the values returned by the SELECT into local variables. */
  105715. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  105716. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  105717. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  105718. int nRoot = sqlite3_column_bytes(pStmt, 4);
  105719. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  105720. /* If nSegment is a multiple of 16 the array needs to be extended. */
  105721. if( (pCsr->nSegment%16)==0 ){
  105722. Fts3SegReader **apNew;
  105723. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  105724. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  105725. if( !apNew ){
  105726. rc = SQLITE_NOMEM;
  105727. goto finished;
  105728. }
  105729. pCsr->apSegment = apNew;
  105730. }
  105731. /* If zTerm is not NULL, and this segment is not stored entirely on its
  105732. ** root node, the range of leaves scanned can be reduced. Do this. */
  105733. if( iStartBlock && zTerm ){
  105734. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  105735. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  105736. if( rc!=SQLITE_OK ) goto finished;
  105737. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  105738. }
  105739. rc = sqlite3Fts3SegReaderNew(iAge, iStartBlock, iLeavesEndBlock,
  105740. iEndBlock, zRoot, nRoot, &pCsr->apSegment[pCsr->nSegment]
  105741. );
  105742. if( rc!=SQLITE_OK ) goto finished;
  105743. pCsr->nSegment++;
  105744. iAge++;
  105745. }
  105746. }
  105747. finished:
  105748. rc2 = sqlite3_reset(pStmt);
  105749. if( rc==SQLITE_DONE ) rc = rc2;
  105750. sqlite3Fts3SegReaderFree(pPending);
  105751. return rc;
  105752. }
  105753. static int fts3TermSegReaderCursor(
  105754. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  105755. const char *zTerm, /* Term to query for */
  105756. int nTerm, /* Size of zTerm in bytes */
  105757. int isPrefix, /* True for a prefix search */
  105758. Fts3SegReaderCursor **ppSegcsr /* OUT: Allocated seg-reader cursor */
  105759. ){
  105760. Fts3SegReaderCursor *pSegcsr; /* Object to allocate and return */
  105761. int rc = SQLITE_NOMEM; /* Return code */
  105762. pSegcsr = sqlite3_malloc(sizeof(Fts3SegReaderCursor));
  105763. if( pSegcsr ){
  105764. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  105765. int i;
  105766. int nCost = 0;
  105767. rc = sqlite3Fts3SegReaderCursor(
  105768. p, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr);
  105769. for(i=0; rc==SQLITE_OK && i<pSegcsr->nSegment; i++){
  105770. rc = sqlite3Fts3SegReaderCost(pCsr, pSegcsr->apSegment[i], &nCost);
  105771. }
  105772. pSegcsr->nCost = nCost;
  105773. }
  105774. *ppSegcsr = pSegcsr;
  105775. return rc;
  105776. }
  105777. static void fts3SegReaderCursorFree(Fts3SegReaderCursor *pSegcsr){
  105778. sqlite3Fts3SegReaderFinish(pSegcsr);
  105779. sqlite3_free(pSegcsr);
  105780. }
  105781. /*
  105782. ** This function retreives the doclist for the specified term (or term
  105783. ** prefix) from the database.
  105784. **
  105785. ** The returned doclist may be in one of two formats, depending on the
  105786. ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
  105787. ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
  105788. ** is non-zero, then the returned list is in the same format as is stored
  105789. ** in the database without the found length specifier at the start of on-disk
  105790. ** doclists.
  105791. */
  105792. static int fts3TermSelect(
  105793. Fts3Table *p, /* Virtual table handle */
  105794. Fts3PhraseToken *pTok, /* Token to query for */
  105795. int iColumn, /* Column to query (or -ve for all columns) */
  105796. int isReqPos, /* True to include position lists in output */
  105797. int *pnOut, /* OUT: Size of buffer at *ppOut */
  105798. char **ppOut /* OUT: Malloced result buffer */
  105799. ){
  105800. int rc; /* Return code */
  105801. Fts3SegReaderCursor *pSegcsr; /* Seg-reader cursor for this term */
  105802. TermSelect tsc; /* Context object for fts3TermSelectCb() */
  105803. Fts3SegFilter filter; /* Segment term filter configuration */
  105804. pSegcsr = pTok->pSegcsr;
  105805. memset(&tsc, 0, sizeof(TermSelect));
  105806. tsc.isReqPos = isReqPos;
  105807. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
  105808. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  105809. | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
  105810. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  105811. filter.iCol = iColumn;
  105812. filter.zTerm = pTok->z;
  105813. filter.nTerm = pTok->n;
  105814. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  105815. while( SQLITE_OK==rc
  105816. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  105817. ){
  105818. rc = fts3TermSelectCb(p, (void *)&tsc,
  105819. pSegcsr->zTerm, pSegcsr->nTerm, pSegcsr->aDoclist, pSegcsr->nDoclist
  105820. );
  105821. }
  105822. if( rc==SQLITE_OK ){
  105823. rc = fts3TermSelectMerge(&tsc);
  105824. }
  105825. if( rc==SQLITE_OK ){
  105826. *ppOut = tsc.aaOutput[0];
  105827. *pnOut = tsc.anOutput[0];
  105828. }else{
  105829. int i;
  105830. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  105831. sqlite3_free(tsc.aaOutput[i]);
  105832. }
  105833. }
  105834. fts3SegReaderCursorFree(pSegcsr);
  105835. pTok->pSegcsr = 0;
  105836. return rc;
  105837. }
  105838. /*
  105839. ** This function counts the total number of docids in the doclist stored
  105840. ** in buffer aList[], size nList bytes.
  105841. **
  105842. ** If the isPoslist argument is true, then it is assumed that the doclist
  105843. ** contains a position-list following each docid. Otherwise, it is assumed
  105844. ** that the doclist is simply a list of docids stored as delta encoded
  105845. ** varints.
  105846. */
  105847. static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
  105848. int nDoc = 0; /* Return value */
  105849. if( aList ){
  105850. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  105851. char *p = aList; /* Cursor */
  105852. if( !isPoslist ){
  105853. /* The number of docids in the list is the same as the number of
  105854. ** varints. In FTS3 a varint consists of a single byte with the 0x80
  105855. ** bit cleared and zero or more bytes with the 0x80 bit set. So to
  105856. ** count the varints in the buffer, just count the number of bytes
  105857. ** with the 0x80 bit clear. */
  105858. while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
  105859. }else{
  105860. while( p<aEnd ){
  105861. nDoc++;
  105862. while( (*p++)&0x80 ); /* Skip docid varint */
  105863. fts3PoslistCopy(0, &p); /* Skip over position list */
  105864. }
  105865. }
  105866. }
  105867. return nDoc;
  105868. }
  105869. /*
  105870. ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
  105871. */
  105872. static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
  105873. int rc = SQLITE_OK;
  105874. if( pExpr ){
  105875. rc = fts3DeferExpression(pCsr, pExpr->pLeft);
  105876. if( rc==SQLITE_OK ){
  105877. rc = fts3DeferExpression(pCsr, pExpr->pRight);
  105878. }
  105879. if( pExpr->eType==FTSQUERY_PHRASE ){
  105880. int iCol = pExpr->pPhrase->iColumn;
  105881. int i;
  105882. for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
  105883. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  105884. if( pToken->pDeferred==0 ){
  105885. rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
  105886. }
  105887. }
  105888. }
  105889. }
  105890. return rc;
  105891. }
  105892. /*
  105893. ** This function removes the position information from a doclist. When
  105894. ** called, buffer aList (size *pnList bytes) contains a doclist that includes
  105895. ** position information. This function removes the position information so
  105896. ** that aList contains only docids, and adjusts *pnList to reflect the new
  105897. ** (possibly reduced) size of the doclist.
  105898. */
  105899. static void fts3DoclistStripPositions(
  105900. char *aList, /* IN/OUT: Buffer containing doclist */
  105901. int *pnList /* IN/OUT: Size of doclist in bytes */
  105902. ){
  105903. if( aList ){
  105904. char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
  105905. char *p = aList; /* Input cursor */
  105906. char *pOut = aList; /* Output cursor */
  105907. while( p<aEnd ){
  105908. sqlite3_int64 delta;
  105909. p += sqlite3Fts3GetVarint(p, &delta);
  105910. fts3PoslistCopy(0, &p);
  105911. pOut += sqlite3Fts3PutVarint(pOut, delta);
  105912. }
  105913. *pnList = (int)(pOut - aList);
  105914. }
  105915. }
  105916. /*
  105917. ** Return a DocList corresponding to the phrase *pPhrase.
  105918. **
  105919. ** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
  105920. ** then no tokens in the phrase were looked up in the full-text index. This
  105921. ** is only possible when this function is called from within xFilter(). The
  105922. ** caller should assume that all documents match the phrase. The actual
  105923. ** filtering will take place in xNext().
  105924. */
  105925. static int fts3PhraseSelect(
  105926. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  105927. Fts3Phrase *pPhrase, /* Phrase to return a doclist for */
  105928. int isReqPos, /* True if output should contain positions */
  105929. char **paOut, /* OUT: Pointer to malloc'd result buffer */
  105930. int *pnOut /* OUT: Size of buffer at *paOut */
  105931. ){
  105932. char *pOut = 0;
  105933. int nOut = 0;
  105934. int rc = SQLITE_OK;
  105935. int ii;
  105936. int iCol = pPhrase->iColumn;
  105937. int isTermPos = (pPhrase->nToken>1 || isReqPos);
  105938. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  105939. int isFirst = 1;
  105940. int iPrevTok = 0;
  105941. int nDoc = 0;
  105942. /* If this is an xFilter() evaluation, create a segment-reader for each
  105943. ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
  105944. ** evaluation, only create segment-readers if there are no Fts3DeferredToken
  105945. ** objects attached to the phrase-tokens.
  105946. */
  105947. for(ii=0; ii<pPhrase->nToken; ii++){
  105948. Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
  105949. if( pTok->pSegcsr==0 ){
  105950. if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
  105951. || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0)
  105952. || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext)
  105953. ){
  105954. rc = fts3TermSegReaderCursor(
  105955. pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
  105956. );
  105957. if( rc!=SQLITE_OK ) return rc;
  105958. }
  105959. }
  105960. }
  105961. for(ii=0; ii<pPhrase->nToken; ii++){
  105962. Fts3PhraseToken *pTok; /* Token to find doclist for */
  105963. int iTok = 0; /* The token being queried this iteration */
  105964. char *pList = 0; /* Pointer to token doclist */
  105965. int nList = 0; /* Size of buffer at pList */
  105966. /* Select a token to process. If this is an xFilter() call, then tokens
  105967. ** are processed in order from least to most costly. Otherwise, tokens
  105968. ** are processed in the order in which they occur in the phrase.
  105969. */
  105970. if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
  105971. assert( isReqPos );
  105972. iTok = ii;
  105973. pTok = &pPhrase->aToken[iTok];
  105974. if( pTok->bFulltext==0 ) continue;
  105975. }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
  105976. iTok = ii;
  105977. pTok = &pPhrase->aToken[iTok];
  105978. }else{
  105979. int nMinCost = 0x7FFFFFFF;
  105980. int jj;
  105981. /* Find the remaining token with the lowest cost. */
  105982. for(jj=0; jj<pPhrase->nToken; jj++){
  105983. Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[jj].pSegcsr;
  105984. if( pSegcsr && pSegcsr->nCost<nMinCost ){
  105985. iTok = jj;
  105986. nMinCost = pSegcsr->nCost;
  105987. }
  105988. }
  105989. pTok = &pPhrase->aToken[iTok];
  105990. /* This branch is taken if it is determined that loading the doclist
  105991. ** for the next token would require more IO than loading all documents
  105992. ** currently identified by doclist pOut/nOut. No further doclists will
  105993. ** be loaded from the full-text index for this phrase.
  105994. */
  105995. if( nMinCost>nDoc && ii>0 ){
  105996. rc = fts3DeferExpression(pCsr, pCsr->pExpr);
  105997. break;
  105998. }
  105999. }
  106000. if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
  106001. rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
  106002. }else{
  106003. if( pTok->pSegcsr ){
  106004. rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
  106005. }
  106006. pTok->bFulltext = 1;
  106007. }
  106008. assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pSegcsr==0 );
  106009. if( rc!=SQLITE_OK ) break;
  106010. if( isFirst ){
  106011. pOut = pList;
  106012. nOut = nList;
  106013. if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
  106014. nDoc = fts3DoclistCountDocids(1, pOut, nOut);
  106015. }
  106016. isFirst = 0;
  106017. iPrevTok = iTok;
  106018. }else{
  106019. /* Merge the new term list and the current output. */
  106020. char *aLeft, *aRight;
  106021. int nLeft, nRight;
  106022. int nDist;
  106023. int mt;
  106024. /* If this is the final token of the phrase, and positions were not
  106025. ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
  106026. ** This drops the position information from the output list.
  106027. */
  106028. mt = MERGE_POS_PHRASE;
  106029. if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
  106030. assert( iPrevTok!=iTok );
  106031. if( iPrevTok<iTok ){
  106032. aLeft = pOut;
  106033. nLeft = nOut;
  106034. aRight = pList;
  106035. nRight = nList;
  106036. nDist = iTok-iPrevTok;
  106037. iPrevTok = iTok;
  106038. }else{
  106039. aRight = pOut;
  106040. nRight = nOut;
  106041. aLeft = pList;
  106042. nLeft = nList;
  106043. nDist = iPrevTok-iTok;
  106044. }
  106045. pOut = aRight;
  106046. fts3DoclistMerge(
  106047. mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
  106048. );
  106049. sqlite3_free(aLeft);
  106050. }
  106051. assert( nOut==0 || pOut!=0 );
  106052. }
  106053. if( rc==SQLITE_OK ){
  106054. if( ii!=pPhrase->nToken ){
  106055. assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
  106056. fts3DoclistStripPositions(pOut, &nOut);
  106057. }
  106058. *paOut = pOut;
  106059. *pnOut = nOut;
  106060. }else{
  106061. sqlite3_free(pOut);
  106062. }
  106063. return rc;
  106064. }
  106065. /*
  106066. ** This function merges two doclists according to the requirements of a
  106067. ** NEAR operator.
  106068. **
  106069. ** Both input doclists must include position information. The output doclist
  106070. ** includes position information if the first argument to this function
  106071. ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
  106072. */
  106073. static int fts3NearMerge(
  106074. int mergetype, /* MERGE_POS_NEAR or MERGE_NEAR */
  106075. int nNear, /* Parameter to NEAR operator */
  106076. int nTokenLeft, /* Number of tokens in LHS phrase arg */
  106077. char *aLeft, /* Doclist for LHS (incl. positions) */
  106078. int nLeft, /* Size of LHS doclist in bytes */
  106079. int nTokenRight, /* As nTokenLeft */
  106080. char *aRight, /* As aLeft */
  106081. int nRight, /* As nRight */
  106082. char **paOut, /* OUT: Results of merge (malloced) */
  106083. int *pnOut /* OUT: Sized of output buffer */
  106084. ){
  106085. char *aOut; /* Buffer to write output doclist to */
  106086. int rc; /* Return code */
  106087. assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
  106088. aOut = sqlite3_malloc(nLeft+nRight+1);
  106089. if( aOut==0 ){
  106090. rc = SQLITE_NOMEM;
  106091. }else{
  106092. rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft,
  106093. aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
  106094. );
  106095. if( rc!=SQLITE_OK ){
  106096. sqlite3_free(aOut);
  106097. aOut = 0;
  106098. }
  106099. }
  106100. *paOut = aOut;
  106101. return rc;
  106102. }
  106103. /*
  106104. ** This function is used as part of the processing for the snippet() and
  106105. ** offsets() functions.
  106106. **
  106107. ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
  106108. ** have their respective doclists (including position information) loaded
  106109. ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
  106110. ** each doclist that are not within nNear tokens of a corresponding entry
  106111. ** in the other doclist.
  106112. */
  106113. SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
  106114. int rc; /* Return code */
  106115. assert( pLeft->eType==FTSQUERY_PHRASE );
  106116. assert( pRight->eType==FTSQUERY_PHRASE );
  106117. assert( pLeft->isLoaded && pRight->isLoaded );
  106118. if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
  106119. sqlite3_free(pLeft->aDoclist);
  106120. sqlite3_free(pRight->aDoclist);
  106121. pRight->aDoclist = 0;
  106122. pLeft->aDoclist = 0;
  106123. rc = SQLITE_OK;
  106124. }else{
  106125. char *aOut; /* Buffer in which to assemble new doclist */
  106126. int nOut; /* Size of buffer aOut in bytes */
  106127. rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
  106128. pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
  106129. pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
  106130. &aOut, &nOut
  106131. );
  106132. if( rc!=SQLITE_OK ) return rc;
  106133. sqlite3_free(pRight->aDoclist);
  106134. pRight->aDoclist = aOut;
  106135. pRight->nDoclist = nOut;
  106136. rc = fts3NearMerge(MERGE_POS_NEAR, nNear,
  106137. pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
  106138. pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
  106139. &aOut, &nOut
  106140. );
  106141. sqlite3_free(pLeft->aDoclist);
  106142. pLeft->aDoclist = aOut;
  106143. pLeft->nDoclist = nOut;
  106144. }
  106145. return rc;
  106146. }
  106147. /*
  106148. ** Allocate an Fts3SegReaderArray for each token in the expression pExpr.
  106149. ** The allocated objects are stored in the Fts3PhraseToken.pArray member
  106150. ** variables of each token structure.
  106151. */
  106152. static int fts3ExprAllocateSegReaders(
  106153. Fts3Cursor *pCsr, /* FTS3 table */
  106154. Fts3Expr *pExpr, /* Expression to create seg-readers for */
  106155. int *pnExpr /* OUT: Number of AND'd expressions */
  106156. ){
  106157. int rc = SQLITE_OK; /* Return code */
  106158. assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
  106159. if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
  106160. (*pnExpr)++;
  106161. pnExpr = 0;
  106162. }
  106163. if( pExpr->eType==FTSQUERY_PHRASE ){
  106164. Fts3Phrase *pPhrase = pExpr->pPhrase;
  106165. int ii;
  106166. for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
  106167. Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
  106168. if( pTok->pSegcsr==0 ){
  106169. rc = fts3TermSegReaderCursor(
  106170. pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pSegcsr
  106171. );
  106172. }
  106173. }
  106174. }else{
  106175. rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
  106176. if( rc==SQLITE_OK ){
  106177. rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
  106178. }
  106179. }
  106180. return rc;
  106181. }
  106182. /*
  106183. ** Free the Fts3SegReaderArray objects associated with each token in the
  106184. ** expression pExpr. In other words, this function frees the resources
  106185. ** allocated by fts3ExprAllocateSegReaders().
  106186. */
  106187. static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
  106188. if( pExpr ){
  106189. Fts3Phrase *pPhrase = pExpr->pPhrase;
  106190. if( pPhrase ){
  106191. int kk;
  106192. for(kk=0; kk<pPhrase->nToken; kk++){
  106193. fts3SegReaderCursorFree(pPhrase->aToken[kk].pSegcsr);
  106194. pPhrase->aToken[kk].pSegcsr = 0;
  106195. }
  106196. }
  106197. fts3ExprFreeSegReaders(pExpr->pLeft);
  106198. fts3ExprFreeSegReaders(pExpr->pRight);
  106199. }
  106200. }
  106201. /*
  106202. ** Return the sum of the costs of all tokens in the expression pExpr. This
  106203. ** function must be called after Fts3SegReaderArrays have been allocated
  106204. ** for all tokens using fts3ExprAllocateSegReaders().
  106205. */
  106206. static int fts3ExprCost(Fts3Expr *pExpr){
  106207. int nCost; /* Return value */
  106208. if( pExpr->eType==FTSQUERY_PHRASE ){
  106209. Fts3Phrase *pPhrase = pExpr->pPhrase;
  106210. int ii;
  106211. nCost = 0;
  106212. for(ii=0; ii<pPhrase->nToken; ii++){
  106213. Fts3SegReaderCursor *pSegcsr = pPhrase->aToken[ii].pSegcsr;
  106214. if( pSegcsr ) nCost += pSegcsr->nCost;
  106215. }
  106216. }else{
  106217. nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
  106218. }
  106219. return nCost;
  106220. }
  106221. /*
  106222. ** The following is a helper function (and type) for fts3EvalExpr(). It
  106223. ** must be called after Fts3SegReaders have been allocated for every token
  106224. ** in the expression. See the context it is called from in fts3EvalExpr()
  106225. ** for further explanation.
  106226. */
  106227. typedef struct ExprAndCost ExprAndCost;
  106228. struct ExprAndCost {
  106229. Fts3Expr *pExpr;
  106230. int nCost;
  106231. };
  106232. static void fts3ExprAssignCosts(
  106233. Fts3Expr *pExpr, /* Expression to create seg-readers for */
  106234. ExprAndCost **ppExprCost /* OUT: Write to *ppExprCost */
  106235. ){
  106236. if( pExpr->eType==FTSQUERY_AND ){
  106237. fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
  106238. fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
  106239. }else{
  106240. (*ppExprCost)->pExpr = pExpr;
  106241. (*ppExprCost)->nCost = fts3ExprCost(pExpr);
  106242. (*ppExprCost)++;
  106243. }
  106244. }
  106245. /*
  106246. ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
  106247. ** the resulting doclist in *paOut and *pnOut. This routine mallocs for
  106248. ** the space needed to store the output. The caller is responsible for
  106249. ** freeing the space when it has finished.
  106250. **
  106251. ** This function is called in two distinct contexts:
  106252. **
  106253. ** * From within the virtual table xFilter() method. In this case, the
  106254. ** output doclist contains entries for all rows in the table, based on
  106255. ** data read from the full-text index.
  106256. **
  106257. ** In this case, if the query expression contains one or more tokens that
  106258. ** are very common, then the returned doclist may contain a superset of
  106259. ** the documents that actually match the expression.
  106260. **
  106261. ** * From within the virtual table xNext() method. This call is only made
  106262. ** if the call from within xFilter() found that there were very common
  106263. ** tokens in the query expression and did return a superset of the
  106264. ** matching documents. In this case the returned doclist contains only
  106265. ** entries that correspond to the current row of the table. Instead of
  106266. ** reading the data for each token from the full-text index, the data is
  106267. ** already available in-memory in the Fts3PhraseToken.pDeferred structures.
  106268. ** See fts3EvalDeferred() for how it gets there.
  106269. **
  106270. ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
  106271. ** required) Fts3Cursor.doDeferred==1.
  106272. **
  106273. ** If the SQLite invokes the snippet(), offsets() or matchinfo() function
  106274. ** as part of a SELECT on an FTS3 table, this function is called on each
  106275. ** individual phrase expression in the query. If there were very common tokens
  106276. ** found in the xFilter() call, then this function is called once for phrase
  106277. ** for each row visited, and the returned doclist contains entries for the
  106278. ** current row only. Otherwise, if there were no very common tokens, then this
  106279. ** function is called once only for each phrase in the query and the returned
  106280. ** doclist contains entries for all rows of the table.
  106281. **
  106282. ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
  106283. ** result of a snippet(), offsets() or matchinfo() invocation.
  106284. */
  106285. static int fts3EvalExpr(
  106286. Fts3Cursor *p, /* Virtual table cursor handle */
  106287. Fts3Expr *pExpr, /* Parsed fts3 expression */
  106288. char **paOut, /* OUT: Pointer to malloc'd result buffer */
  106289. int *pnOut, /* OUT: Size of buffer at *paOut */
  106290. int isReqPos /* Require positions in output buffer */
  106291. ){
  106292. int rc = SQLITE_OK; /* Return code */
  106293. /* Zero the output parameters. */
  106294. *paOut = 0;
  106295. *pnOut = 0;
  106296. if( pExpr ){
  106297. assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
  106298. || pExpr->eType==FTSQUERY_AND || pExpr->eType==FTSQUERY_NOT
  106299. || pExpr->eType==FTSQUERY_PHRASE
  106300. );
  106301. assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
  106302. if( pExpr->eType==FTSQUERY_PHRASE ){
  106303. rc = fts3PhraseSelect(p, pExpr->pPhrase,
  106304. isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
  106305. paOut, pnOut
  106306. );
  106307. fts3ExprFreeSegReaders(pExpr);
  106308. }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
  106309. ExprAndCost *aExpr = 0; /* Array of AND'd expressions and costs */
  106310. int nExpr = 0; /* Size of aExpr[] */
  106311. char *aRet = 0; /* Doclist to return to caller */
  106312. int nRet = 0; /* Length of aRet[] in bytes */
  106313. int nDoc = 0x7FFFFFFF;
  106314. assert( !isReqPos );
  106315. rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
  106316. if( rc==SQLITE_OK ){
  106317. assert( nExpr>1 );
  106318. aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
  106319. if( !aExpr ) rc = SQLITE_NOMEM;
  106320. }
  106321. if( rc==SQLITE_OK ){
  106322. int ii; /* Used to iterate through expressions */
  106323. fts3ExprAssignCosts(pExpr, &aExpr);
  106324. aExpr -= nExpr;
  106325. for(ii=0; ii<nExpr; ii++){
  106326. char *aNew;
  106327. int nNew;
  106328. int jj;
  106329. ExprAndCost *pBest = 0;
  106330. for(jj=0; jj<nExpr; jj++){
  106331. ExprAndCost *pCand = &aExpr[jj];
  106332. if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
  106333. pBest = pCand;
  106334. }
  106335. }
  106336. if( pBest->nCost>nDoc ){
  106337. rc = fts3DeferExpression(p, p->pExpr);
  106338. break;
  106339. }else{
  106340. rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
  106341. if( rc!=SQLITE_OK ) break;
  106342. pBest->pExpr = 0;
  106343. if( ii==0 ){
  106344. aRet = aNew;
  106345. nRet = nNew;
  106346. nDoc = fts3DoclistCountDocids(0, aRet, nRet);
  106347. }else{
  106348. fts3DoclistMerge(
  106349. MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
  106350. );
  106351. sqlite3_free(aNew);
  106352. }
  106353. }
  106354. }
  106355. }
  106356. if( rc==SQLITE_OK ){
  106357. *paOut = aRet;
  106358. *pnOut = nRet;
  106359. }else{
  106360. assert( *paOut==0 );
  106361. sqlite3_free(aRet);
  106362. }
  106363. sqlite3_free(aExpr);
  106364. fts3ExprFreeSegReaders(pExpr);
  106365. }else{
  106366. char *aLeft;
  106367. char *aRight;
  106368. int nLeft;
  106369. int nRight;
  106370. assert( pExpr->eType==FTSQUERY_NEAR
  106371. || pExpr->eType==FTSQUERY_OR
  106372. || pExpr->eType==FTSQUERY_NOT
  106373. || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
  106374. );
  106375. if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
  106376. && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
  106377. ){
  106378. switch( pExpr->eType ){
  106379. case FTSQUERY_NEAR: {
  106380. Fts3Expr *pLeft;
  106381. Fts3Expr *pRight;
  106382. int mergetype = MERGE_NEAR;
  106383. if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
  106384. mergetype = MERGE_POS_NEAR;
  106385. }
  106386. pLeft = pExpr->pLeft;
  106387. while( pLeft->eType==FTSQUERY_NEAR ){
  106388. pLeft=pLeft->pRight;
  106389. }
  106390. pRight = pExpr->pRight;
  106391. assert( pRight->eType==FTSQUERY_PHRASE );
  106392. assert( pLeft->eType==FTSQUERY_PHRASE );
  106393. rc = fts3NearMerge(mergetype, pExpr->nNear,
  106394. pLeft->pPhrase->nToken, aLeft, nLeft,
  106395. pRight->pPhrase->nToken, aRight, nRight,
  106396. paOut, pnOut
  106397. );
  106398. sqlite3_free(aLeft);
  106399. break;
  106400. }
  106401. case FTSQUERY_OR: {
  106402. /* Allocate a buffer for the output. The maximum size is the
  106403. ** sum of the sizes of the two input buffers. The +1 term is
  106404. ** so that a buffer of zero bytes is never allocated - this can
  106405. ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
  106406. */
  106407. char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
  106408. rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
  106409. aLeft, nLeft, aRight, nRight, 0
  106410. );
  106411. *paOut = aBuffer;
  106412. sqlite3_free(aLeft);
  106413. break;
  106414. }
  106415. default: {
  106416. assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
  106417. fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
  106418. aLeft, nLeft, aRight, nRight, 0
  106419. );
  106420. *paOut = aLeft;
  106421. break;
  106422. }
  106423. }
  106424. }
  106425. sqlite3_free(aRight);
  106426. }
  106427. }
  106428. assert( rc==SQLITE_OK || *paOut==0 );
  106429. return rc;
  106430. }
  106431. /*
  106432. ** This function is called from within xNext() for each row visited by
  106433. ** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
  106434. ** was able to determine the exact set of matching rows, this function sets
  106435. ** *pbRes to true and returns SQLITE_IO immediately.
  106436. **
  106437. ** Otherwise, if evaluating the query expression within xFilter() returned a
  106438. ** superset of the matching documents instead of an exact set (this happens
  106439. ** when the query includes very common tokens and it is deemed too expensive to
  106440. ** load their doclists from disk), this function tests if the current row
  106441. ** really does match the FTS3 query.
  106442. **
  106443. ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
  106444. ** is returned and *pbRes is set to true if the current row matches the
  106445. ** FTS3 query (and should be included in the results returned to SQLite), or
  106446. ** false otherwise.
  106447. */
  106448. static int fts3EvalDeferred(
  106449. Fts3Cursor *pCsr, /* FTS3 cursor pointing at row to test */
  106450. int *pbRes /* OUT: Set to true if row is a match */
  106451. ){
  106452. int rc = SQLITE_OK;
  106453. if( pCsr->pDeferred==0 ){
  106454. *pbRes = 1;
  106455. }else{
  106456. rc = fts3CursorSeek(0, pCsr);
  106457. if( rc==SQLITE_OK ){
  106458. sqlite3Fts3FreeDeferredDoclists(pCsr);
  106459. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  106460. }
  106461. if( rc==SQLITE_OK ){
  106462. char *a = 0;
  106463. int n = 0;
  106464. rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
  106465. assert( n>=0 );
  106466. *pbRes = (n>0);
  106467. sqlite3_free(a);
  106468. }
  106469. }
  106470. return rc;
  106471. }
  106472. /*
  106473. ** Advance the cursor to the next row in the %_content table that
  106474. ** matches the search criteria. For a MATCH search, this will be
  106475. ** the next row that matches. For a full-table scan, this will be
  106476. ** simply the next row in the %_content table. For a docid lookup,
  106477. ** this routine simply sets the EOF flag.
  106478. **
  106479. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  106480. ** even if we reach end-of-file. The fts3EofMethod() will be called
  106481. ** subsequently to determine whether or not an EOF was hit.
  106482. */
  106483. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  106484. int res;
  106485. int rc = SQLITE_OK; /* Return code */
  106486. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  106487. pCsr->eEvalmode = FTS3_EVAL_NEXT;
  106488. do {
  106489. if( pCsr->aDoclist==0 ){
  106490. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  106491. pCsr->isEof = 1;
  106492. rc = sqlite3_reset(pCsr->pStmt);
  106493. break;
  106494. }
  106495. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  106496. }else{
  106497. if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
  106498. pCsr->isEof = 1;
  106499. break;
  106500. }
  106501. sqlite3_reset(pCsr->pStmt);
  106502. fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
  106503. pCsr->isRequireSeek = 1;
  106504. pCsr->isMatchinfoNeeded = 1;
  106505. }
  106506. }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
  106507. return rc;
  106508. }
  106509. /*
  106510. ** This is the xFilter interface for the virtual table. See
  106511. ** the virtual table xFilter method documentation for additional
  106512. ** information.
  106513. **
  106514. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  106515. ** the %_content table.
  106516. **
  106517. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  106518. ** in the %_content table.
  106519. **
  106520. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  106521. ** column on the left-hand side of the MATCH operator is column
  106522. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  106523. ** side of the MATCH operator.
  106524. */
  106525. static int fts3FilterMethod(
  106526. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  106527. int idxNum, /* Strategy index */
  106528. const char *idxStr, /* Unused */
  106529. int nVal, /* Number of elements in apVal */
  106530. sqlite3_value **apVal /* Arguments for the indexing scheme */
  106531. ){
  106532. const char *azSql[] = {
  106533. "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?", /* non-full-scan */
  106534. "SELECT %s FROM %Q.'%q_content' AS x ", /* full-scan */
  106535. };
  106536. int rc; /* Return code */
  106537. char *zSql; /* SQL statement used to access %_content */
  106538. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  106539. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  106540. UNUSED_PARAMETER(idxStr);
  106541. UNUSED_PARAMETER(nVal);
  106542. assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  106543. assert( nVal==0 || nVal==1 );
  106544. assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
  106545. assert( p->pSegments==0 );
  106546. /* In case the cursor has been used before, clear it now. */
  106547. sqlite3_finalize(pCsr->pStmt);
  106548. sqlite3_free(pCsr->aDoclist);
  106549. sqlite3Fts3ExprFree(pCsr->pExpr);
  106550. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  106551. if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
  106552. int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
  106553. const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
  106554. if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  106555. return SQLITE_NOMEM;
  106556. }
  106557. rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
  106558. iCol, zQuery, -1, &pCsr->pExpr
  106559. );
  106560. if( rc!=SQLITE_OK ){
  106561. if( rc==SQLITE_ERROR ){
  106562. p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
  106563. zQuery);
  106564. }
  106565. return rc;
  106566. }
  106567. rc = sqlite3Fts3ReadLock(p);
  106568. if( rc!=SQLITE_OK ) return rc;
  106569. rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
  106570. sqlite3Fts3SegmentsClose(p);
  106571. if( rc!=SQLITE_OK ) return rc;
  106572. pCsr->pNextId = pCsr->aDoclist;
  106573. pCsr->iPrevId = 0;
  106574. }
  106575. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  106576. ** statement loops through all rows of the %_content table. For a
  106577. ** full-text query or docid lookup, the statement retrieves a single
  106578. ** row by docid.
  106579. */
  106580. zSql = (char *)azSql[idxNum==FTS3_FULLSCAN_SEARCH];
  106581. zSql = sqlite3_mprintf(zSql, p->zReadExprlist, p->zDb, p->zName);
  106582. if( !zSql ){
  106583. rc = SQLITE_NOMEM;
  106584. }else{
  106585. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  106586. sqlite3_free(zSql);
  106587. }
  106588. if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
  106589. rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  106590. }
  106591. pCsr->eSearch = (i16)idxNum;
  106592. if( rc!=SQLITE_OK ) return rc;
  106593. return fts3NextMethod(pCursor);
  106594. }
  106595. /*
  106596. ** This is the xEof method of the virtual table. SQLite calls this
  106597. ** routine to find out if it has reached the end of a result set.
  106598. */
  106599. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  106600. return ((Fts3Cursor *)pCursor)->isEof;
  106601. }
  106602. /*
  106603. ** This is the xRowid method. The SQLite core calls this routine to
  106604. ** retrieve the rowid for the current row of the result set. fts3
  106605. ** exposes %_content.docid as the rowid for the virtual table. The
  106606. ** rowid should be written to *pRowid.
  106607. */
  106608. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  106609. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  106610. if( pCsr->aDoclist ){
  106611. *pRowid = pCsr->iPrevId;
  106612. }else{
  106613. /* This branch runs if the query is implemented using a full-table scan
  106614. ** (not using the full-text index). In this case grab the rowid from the
  106615. ** SELECT statement.
  106616. */
  106617. assert( pCsr->isRequireSeek==0 );
  106618. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  106619. }
  106620. return SQLITE_OK;
  106621. }
  106622. /*
  106623. ** This is the xColumn method, called by SQLite to request a value from
  106624. ** the row that the supplied cursor currently points to.
  106625. */
  106626. static int fts3ColumnMethod(
  106627. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  106628. sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
  106629. int iCol /* Index of column to read value from */
  106630. ){
  106631. int rc; /* Return Code */
  106632. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  106633. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  106634. /* The column value supplied by SQLite must be in range. */
  106635. assert( iCol>=0 && iCol<=p->nColumn+1 );
  106636. if( iCol==p->nColumn+1 ){
  106637. /* This call is a request for the "docid" column. Since "docid" is an
  106638. ** alias for "rowid", use the xRowid() method to obtain the value.
  106639. */
  106640. sqlite3_int64 iRowid;
  106641. rc = fts3RowidMethod(pCursor, &iRowid);
  106642. sqlite3_result_int64(pContext, iRowid);
  106643. }else if( iCol==p->nColumn ){
  106644. /* The extra column whose name is the same as the table.
  106645. ** Return a blob which is a pointer to the cursor.
  106646. */
  106647. sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  106648. rc = SQLITE_OK;
  106649. }else{
  106650. rc = fts3CursorSeek(0, pCsr);
  106651. if( rc==SQLITE_OK ){
  106652. sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
  106653. }
  106654. }
  106655. return rc;
  106656. }
  106657. /*
  106658. ** This function is the implementation of the xUpdate callback used by
  106659. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  106660. ** inserted, updated or deleted.
  106661. */
  106662. static int fts3UpdateMethod(
  106663. sqlite3_vtab *pVtab, /* Virtual table handle */
  106664. int nArg, /* Size of argument array */
  106665. sqlite3_value **apVal, /* Array of arguments */
  106666. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  106667. ){
  106668. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  106669. }
  106670. /*
  106671. ** Implementation of xSync() method. Flush the contents of the pending-terms
  106672. ** hash-table to the database.
  106673. */
  106674. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  106675. int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
  106676. sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
  106677. return rc;
  106678. }
  106679. /*
  106680. ** Implementation of xBegin() method. This is a no-op.
  106681. */
  106682. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  106683. UNUSED_PARAMETER(pVtab);
  106684. assert( ((Fts3Table *)pVtab)->nPendingData==0 );
  106685. return SQLITE_OK;
  106686. }
  106687. /*
  106688. ** Implementation of xCommit() method. This is a no-op. The contents of
  106689. ** the pending-terms hash-table have already been flushed into the database
  106690. ** by fts3SyncMethod().
  106691. */
  106692. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  106693. UNUSED_PARAMETER(pVtab);
  106694. assert( ((Fts3Table *)pVtab)->nPendingData==0 );
  106695. return SQLITE_OK;
  106696. }
  106697. /*
  106698. ** Implementation of xRollback(). Discard the contents of the pending-terms
  106699. ** hash-table. Any changes made to the database are reverted by SQLite.
  106700. */
  106701. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  106702. sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
  106703. return SQLITE_OK;
  106704. }
  106705. /*
  106706. ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
  106707. ** The loaded doclist contains positions as well as the document ids.
  106708. ** This is used by the matchinfo(), snippet() and offsets() auxillary
  106709. ** functions.
  106710. */
  106711. SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
  106712. int rc;
  106713. assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
  106714. assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
  106715. rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
  106716. return rc;
  106717. }
  106718. SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
  106719. Fts3Cursor *pCsr,
  106720. Fts3Expr *pExpr,
  106721. char **paDoclist,
  106722. int *pnDoclist
  106723. ){
  106724. int rc;
  106725. assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
  106726. assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
  106727. pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
  106728. rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
  106729. pCsr->eEvalmode = FTS3_EVAL_NEXT;
  106730. return rc;
  106731. }
  106732. /*
  106733. ** After ExprLoadDoclist() (see above) has been called, this function is
  106734. ** used to iterate/search through the position lists that make up the doclist
  106735. ** stored in pExpr->aDoclist.
  106736. */
  106737. SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
  106738. Fts3Expr *pExpr, /* Access this expressions doclist */
  106739. sqlite3_int64 iDocid, /* Docid associated with requested pos-list */
  106740. int iCol /* Column of requested pos-list */
  106741. ){
  106742. assert( pExpr->isLoaded );
  106743. if( pExpr->aDoclist ){
  106744. char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
  106745. char *pCsr;
  106746. if( pExpr->pCurrent==0 ){
  106747. pExpr->pCurrent = pExpr->aDoclist;
  106748. pExpr->iCurrent = 0;
  106749. pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
  106750. }
  106751. pCsr = pExpr->pCurrent;
  106752. assert( pCsr );
  106753. while( pCsr<pEnd ){
  106754. if( pExpr->iCurrent<iDocid ){
  106755. fts3PoslistCopy(0, &pCsr);
  106756. if( pCsr<pEnd ){
  106757. fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
  106758. }
  106759. pExpr->pCurrent = pCsr;
  106760. }else{
  106761. if( pExpr->iCurrent==iDocid ){
  106762. int iThis = 0;
  106763. if( iCol<0 ){
  106764. /* If iCol is negative, return a pointer to the start of the
  106765. ** position-list (instead of a pointer to the start of a list
  106766. ** of offsets associated with a specific column).
  106767. */
  106768. return pCsr;
  106769. }
  106770. while( iThis<iCol ){
  106771. fts3ColumnlistCopy(0, &pCsr);
  106772. if( *pCsr==0x00 ) return 0;
  106773. pCsr++;
  106774. pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
  106775. }
  106776. if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
  106777. }
  106778. return 0;
  106779. }
  106780. }
  106781. }
  106782. return 0;
  106783. }
  106784. /*
  106785. ** Helper function used by the implementation of the overloaded snippet(),
  106786. ** offsets() and optimize() SQL functions.
  106787. **
  106788. ** If the value passed as the third argument is a blob of size
  106789. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  106790. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  106791. ** message is written to context pContext and SQLITE_ERROR returned. The
  106792. ** string passed via zFunc is used as part of the error message.
  106793. */
  106794. static int fts3FunctionArg(
  106795. sqlite3_context *pContext, /* SQL function call context */
  106796. const char *zFunc, /* Function name */
  106797. sqlite3_value *pVal, /* argv[0] passed to function */
  106798. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  106799. ){
  106800. Fts3Cursor *pRet;
  106801. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  106802. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  106803. ){
  106804. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  106805. sqlite3_result_error(pContext, zErr, -1);
  106806. sqlite3_free(zErr);
  106807. return SQLITE_ERROR;
  106808. }
  106809. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  106810. *ppCsr = pRet;
  106811. return SQLITE_OK;
  106812. }
  106813. /*
  106814. ** Implementation of the snippet() function for FTS3
  106815. */
  106816. static void fts3SnippetFunc(
  106817. sqlite3_context *pContext, /* SQLite function call context */
  106818. int nVal, /* Size of apVal[] array */
  106819. sqlite3_value **apVal /* Array of arguments */
  106820. ){
  106821. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  106822. const char *zStart = "<b>";
  106823. const char *zEnd = "</b>";
  106824. const char *zEllipsis = "<b>...</b>";
  106825. int iCol = -1;
  106826. int nToken = 15; /* Default number of tokens in snippet */
  106827. /* There must be at least one argument passed to this function (otherwise
  106828. ** the non-overloaded version would have been called instead of this one).
  106829. */
  106830. assert( nVal>=1 );
  106831. if( nVal>6 ){
  106832. sqlite3_result_error(pContext,
  106833. "wrong number of arguments to function snippet()", -1);
  106834. return;
  106835. }
  106836. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  106837. switch( nVal ){
  106838. case 6: nToken = sqlite3_value_int(apVal[5]);
  106839. case 5: iCol = sqlite3_value_int(apVal[4]);
  106840. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  106841. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  106842. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  106843. }
  106844. if( !zEllipsis || !zEnd || !zStart ){
  106845. sqlite3_result_error_nomem(pContext);
  106846. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  106847. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  106848. }
  106849. }
  106850. /*
  106851. ** Implementation of the offsets() function for FTS3
  106852. */
  106853. static void fts3OffsetsFunc(
  106854. sqlite3_context *pContext, /* SQLite function call context */
  106855. int nVal, /* Size of argument array */
  106856. sqlite3_value **apVal /* Array of arguments */
  106857. ){
  106858. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  106859. UNUSED_PARAMETER(nVal);
  106860. assert( nVal==1 );
  106861. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  106862. assert( pCsr );
  106863. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  106864. sqlite3Fts3Offsets(pContext, pCsr);
  106865. }
  106866. }
  106867. /*
  106868. ** Implementation of the special optimize() function for FTS3. This
  106869. ** function merges all segments in the database to a single segment.
  106870. ** Example usage is:
  106871. **
  106872. ** SELECT optimize(t) FROM t LIMIT 1;
  106873. **
  106874. ** where 't' is the name of an FTS3 table.
  106875. */
  106876. static void fts3OptimizeFunc(
  106877. sqlite3_context *pContext, /* SQLite function call context */
  106878. int nVal, /* Size of argument array */
  106879. sqlite3_value **apVal /* Array of arguments */
  106880. ){
  106881. int rc; /* Return code */
  106882. Fts3Table *p; /* Virtual table handle */
  106883. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  106884. UNUSED_PARAMETER(nVal);
  106885. assert( nVal==1 );
  106886. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  106887. p = (Fts3Table *)pCursor->base.pVtab;
  106888. assert( p );
  106889. rc = sqlite3Fts3Optimize(p);
  106890. switch( rc ){
  106891. case SQLITE_OK:
  106892. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  106893. break;
  106894. case SQLITE_DONE:
  106895. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  106896. break;
  106897. default:
  106898. sqlite3_result_error_code(pContext, rc);
  106899. break;
  106900. }
  106901. }
  106902. /*
  106903. ** Implementation of the matchinfo() function for FTS3
  106904. */
  106905. static void fts3MatchinfoFunc(
  106906. sqlite3_context *pContext, /* SQLite function call context */
  106907. int nVal, /* Size of argument array */
  106908. sqlite3_value **apVal /* Array of arguments */
  106909. ){
  106910. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  106911. assert( nVal==1 || nVal==2 );
  106912. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  106913. const char *zArg = 0;
  106914. if( nVal>1 ){
  106915. zArg = (const char *)sqlite3_value_text(apVal[1]);
  106916. }
  106917. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  106918. }
  106919. }
  106920. /*
  106921. ** This routine implements the xFindFunction method for the FTS3
  106922. ** virtual table.
  106923. */
  106924. static int fts3FindFunctionMethod(
  106925. sqlite3_vtab *pVtab, /* Virtual table handle */
  106926. int nArg, /* Number of SQL function arguments */
  106927. const char *zName, /* Name of SQL function */
  106928. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  106929. void **ppArg /* Unused */
  106930. ){
  106931. struct Overloaded {
  106932. const char *zName;
  106933. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  106934. } aOverload[] = {
  106935. { "snippet", fts3SnippetFunc },
  106936. { "offsets", fts3OffsetsFunc },
  106937. { "optimize", fts3OptimizeFunc },
  106938. { "matchinfo", fts3MatchinfoFunc },
  106939. };
  106940. int i; /* Iterator variable */
  106941. UNUSED_PARAMETER(pVtab);
  106942. UNUSED_PARAMETER(nArg);
  106943. UNUSED_PARAMETER(ppArg);
  106944. for(i=0; i<SizeofArray(aOverload); i++){
  106945. if( strcmp(zName, aOverload[i].zName)==0 ){
  106946. *pxFunc = aOverload[i].xFunc;
  106947. return 1;
  106948. }
  106949. }
  106950. /* No function of the specified name was found. Return 0. */
  106951. return 0;
  106952. }
  106953. /*
  106954. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  106955. */
  106956. static int fts3RenameMethod(
  106957. sqlite3_vtab *pVtab, /* Virtual table handle */
  106958. const char *zName /* New name of table */
  106959. ){
  106960. Fts3Table *p = (Fts3Table *)pVtab;
  106961. sqlite3 *db = p->db; /* Database connection */
  106962. int rc; /* Return Code */
  106963. rc = sqlite3Fts3PendingTermsFlush(p);
  106964. if( rc!=SQLITE_OK ){
  106965. return rc;
  106966. }
  106967. fts3DbExec(&rc, db,
  106968. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  106969. p->zDb, p->zName, zName
  106970. );
  106971. if( p->bHasDocsize ){
  106972. fts3DbExec(&rc, db,
  106973. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  106974. p->zDb, p->zName, zName
  106975. );
  106976. }
  106977. if( p->bHasStat ){
  106978. fts3DbExec(&rc, db,
  106979. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  106980. p->zDb, p->zName, zName
  106981. );
  106982. }
  106983. fts3DbExec(&rc, db,
  106984. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  106985. p->zDb, p->zName, zName
  106986. );
  106987. fts3DbExec(&rc, db,
  106988. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  106989. p->zDb, p->zName, zName
  106990. );
  106991. return rc;
  106992. }
  106993. static const sqlite3_module fts3Module = {
  106994. /* iVersion */ 0,
  106995. /* xCreate */ fts3CreateMethod,
  106996. /* xConnect */ fts3ConnectMethod,
  106997. /* xBestIndex */ fts3BestIndexMethod,
  106998. /* xDisconnect */ fts3DisconnectMethod,
  106999. /* xDestroy */ fts3DestroyMethod,
  107000. /* xOpen */ fts3OpenMethod,
  107001. /* xClose */ fts3CloseMethod,
  107002. /* xFilter */ fts3FilterMethod,
  107003. /* xNext */ fts3NextMethod,
  107004. /* xEof */ fts3EofMethod,
  107005. /* xColumn */ fts3ColumnMethod,
  107006. /* xRowid */ fts3RowidMethod,
  107007. /* xUpdate */ fts3UpdateMethod,
  107008. /* xBegin */ fts3BeginMethod,
  107009. /* xSync */ fts3SyncMethod,
  107010. /* xCommit */ fts3CommitMethod,
  107011. /* xRollback */ fts3RollbackMethod,
  107012. /* xFindFunction */ fts3FindFunctionMethod,
  107013. /* xRename */ fts3RenameMethod,
  107014. };
  107015. /*
  107016. ** This function is registered as the module destructor (called when an
  107017. ** FTS3 enabled database connection is closed). It frees the memory
  107018. ** allocated for the tokenizer hash table.
  107019. */
  107020. static void hashDestroy(void *p){
  107021. Fts3Hash *pHash = (Fts3Hash *)p;
  107022. sqlite3Fts3HashClear(pHash);
  107023. sqlite3_free(pHash);
  107024. }
  107025. /*
  107026. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  107027. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  107028. ** respectively. The following three forward declarations are for functions
  107029. ** declared in these files used to retrieve the respective implementations.
  107030. **
  107031. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  107032. ** to by the argument to point to the "simple" tokenizer implementation.
  107033. ** And so on.
  107034. */
  107035. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  107036. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  107037. #ifdef SQLITE_ENABLE_ICU
  107038. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  107039. #endif
  107040. /*
  107041. ** Initialise the fts3 extension. If this extension is built as part
  107042. ** of the sqlite library, then this function is called directly by
  107043. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  107044. ** function is called by the sqlite3_extension_init() entry point.
  107045. */
  107046. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  107047. int rc = SQLITE_OK;
  107048. Fts3Hash *pHash = 0;
  107049. const sqlite3_tokenizer_module *pSimple = 0;
  107050. const sqlite3_tokenizer_module *pPorter = 0;
  107051. #ifdef SQLITE_ENABLE_ICU
  107052. const sqlite3_tokenizer_module *pIcu = 0;
  107053. sqlite3Fts3IcuTokenizerModule(&pIcu);
  107054. #endif
  107055. rc = sqlite3Fts3InitAux(db);
  107056. if( rc!=SQLITE_OK ) return rc;
  107057. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  107058. sqlite3Fts3PorterTokenizerModule(&pPorter);
  107059. /* Allocate and initialise the hash-table used to store tokenizers. */
  107060. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  107061. if( !pHash ){
  107062. rc = SQLITE_NOMEM;
  107063. }else{
  107064. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  107065. }
  107066. /* Load the built-in tokenizers into the hash table */
  107067. if( rc==SQLITE_OK ){
  107068. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  107069. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  107070. #ifdef SQLITE_ENABLE_ICU
  107071. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  107072. #endif
  107073. ){
  107074. rc = SQLITE_NOMEM;
  107075. }
  107076. }
  107077. #ifdef SQLITE_TEST
  107078. if( rc==SQLITE_OK ){
  107079. rc = sqlite3Fts3ExprInitTestInterface(db);
  107080. }
  107081. #endif
  107082. /* Create the virtual table wrapper around the hash-table and overload
  107083. ** the two scalar functions. If this is successful, register the
  107084. ** module with sqlite.
  107085. */
  107086. if( SQLITE_OK==rc
  107087. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  107088. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  107089. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  107090. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  107091. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  107092. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  107093. ){
  107094. rc = sqlite3_create_module_v2(
  107095. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  107096. );
  107097. if( rc==SQLITE_OK ){
  107098. rc = sqlite3_create_module_v2(
  107099. db, "fts4", &fts3Module, (void *)pHash, 0
  107100. );
  107101. }
  107102. return rc;
  107103. }
  107104. /* An error has occurred. Delete the hash table and return the error code. */
  107105. assert( rc!=SQLITE_OK );
  107106. if( pHash ){
  107107. sqlite3Fts3HashClear(pHash);
  107108. sqlite3_free(pHash);
  107109. }
  107110. return rc;
  107111. }
  107112. #if !SQLITE_CORE
  107113. SQLITE_API int sqlite3_extension_init(
  107114. sqlite3 *db,
  107115. char **pzErrMsg,
  107116. const sqlite3_api_routines *pApi
  107117. ){
  107118. SQLITE_EXTENSION_INIT2(pApi)
  107119. return sqlite3Fts3Init(db);
  107120. }
  107121. #endif
  107122. #endif
  107123. /************** End of fts3.c ************************************************/
  107124. /************** Begin file fts3_aux.c ****************************************/
  107125. /*
  107126. ** 2011 Jan 27
  107127. **
  107128. ** The author disclaims copyright to this source code. In place of
  107129. ** a legal notice, here is a blessing:
  107130. **
  107131. ** May you do good and not evil.
  107132. ** May you find forgiveness for yourself and forgive others.
  107133. ** May you share freely, never taking more than you give.
  107134. **
  107135. ******************************************************************************
  107136. **
  107137. */
  107138. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  107139. typedef struct Fts3auxTable Fts3auxTable;
  107140. typedef struct Fts3auxCursor Fts3auxCursor;
  107141. struct Fts3auxTable {
  107142. sqlite3_vtab base; /* Base class used by SQLite core */
  107143. Fts3Table *pFts3Tab;
  107144. };
  107145. struct Fts3auxCursor {
  107146. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  107147. Fts3SegReaderCursor csr; /* Must be right after "base" */
  107148. Fts3SegFilter filter;
  107149. char *zStop;
  107150. int nStop; /* Byte-length of string zStop */
  107151. int isEof; /* True if cursor is at EOF */
  107152. sqlite3_int64 iRowid; /* Current rowid */
  107153. int iCol; /* Current value of 'col' column */
  107154. int nStat; /* Size of aStat[] array */
  107155. struct Fts3auxColstats {
  107156. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  107157. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  107158. } *aStat;
  107159. };
  107160. /*
  107161. ** Schema of the terms table.
  107162. */
  107163. #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
  107164. /*
  107165. ** This function does all the work for both the xConnect and xCreate methods.
  107166. ** These tables have no persistent representation of their own, so xConnect
  107167. ** and xCreate are identical operations.
  107168. */
  107169. static int fts3auxConnectMethod(
  107170. sqlite3 *db, /* Database connection */
  107171. void *pUnused, /* Unused */
  107172. int argc, /* Number of elements in argv array */
  107173. const char * const *argv, /* xCreate/xConnect argument array */
  107174. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  107175. char **pzErr /* OUT: sqlite3_malloc'd error message */
  107176. ){
  107177. char const *zDb; /* Name of database (e.g. "main") */
  107178. char const *zFts3; /* Name of fts3 table */
  107179. int nDb; /* Result of strlen(zDb) */
  107180. int nFts3; /* Result of strlen(zFts3) */
  107181. int nByte; /* Bytes of space to allocate here */
  107182. int rc; /* value returned by declare_vtab() */
  107183. Fts3auxTable *p; /* Virtual table object to return */
  107184. UNUSED_PARAMETER(pUnused);
  107185. /* The user should specify a single argument - the name of an fts3 table. */
  107186. if( argc!=4 ){
  107187. *pzErr = sqlite3_mprintf(
  107188. "wrong number of arguments to fts4aux constructor"
  107189. );
  107190. return SQLITE_ERROR;
  107191. }
  107192. zDb = argv[1];
  107193. nDb = strlen(zDb);
  107194. zFts3 = argv[3];
  107195. nFts3 = strlen(zFts3);
  107196. rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
  107197. if( rc!=SQLITE_OK ) return rc;
  107198. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  107199. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  107200. if( !p ) return SQLITE_NOMEM;
  107201. memset(p, 0, nByte);
  107202. p->pFts3Tab = (Fts3Table *)&p[1];
  107203. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  107204. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  107205. p->pFts3Tab->db = db;
  107206. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  107207. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  107208. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  107209. *ppVtab = (sqlite3_vtab *)p;
  107210. return SQLITE_OK;
  107211. }
  107212. /*
  107213. ** This function does the work for both the xDisconnect and xDestroy methods.
  107214. ** These tables have no persistent representation of their own, so xDisconnect
  107215. ** and xDestroy are identical operations.
  107216. */
  107217. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  107218. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  107219. Fts3Table *pFts3 = p->pFts3Tab;
  107220. int i;
  107221. /* Free any prepared statements held */
  107222. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  107223. sqlite3_finalize(pFts3->aStmt[i]);
  107224. }
  107225. sqlite3_free(pFts3->zSegmentsTbl);
  107226. sqlite3_free(p);
  107227. return SQLITE_OK;
  107228. }
  107229. #define FTS4AUX_EQ_CONSTRAINT 1
  107230. #define FTS4AUX_GE_CONSTRAINT 2
  107231. #define FTS4AUX_LE_CONSTRAINT 4
  107232. /*
  107233. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  107234. */
  107235. static int fts3auxBestIndexMethod(
  107236. sqlite3_vtab *pVTab,
  107237. sqlite3_index_info *pInfo
  107238. ){
  107239. int i;
  107240. int iEq = -1;
  107241. int iGe = -1;
  107242. int iLe = -1;
  107243. UNUSED_PARAMETER(pVTab);
  107244. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  107245. if( pInfo->nOrderBy==1
  107246. && pInfo->aOrderBy[0].iColumn==0
  107247. && pInfo->aOrderBy[0].desc==0
  107248. ){
  107249. pInfo->orderByConsumed = 1;
  107250. }
  107251. /* Search for equality and range constraints on the "term" column. */
  107252. for(i=0; i<pInfo->nConstraint; i++){
  107253. if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
  107254. int op = pInfo->aConstraint[i].op;
  107255. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  107256. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  107257. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  107258. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  107259. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  107260. }
  107261. }
  107262. if( iEq>=0 ){
  107263. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  107264. pInfo->aConstraintUsage[iEq].argvIndex = 1;
  107265. pInfo->estimatedCost = 5;
  107266. }else{
  107267. pInfo->idxNum = 0;
  107268. pInfo->estimatedCost = 20000;
  107269. if( iGe>=0 ){
  107270. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  107271. pInfo->aConstraintUsage[iGe].argvIndex = 1;
  107272. pInfo->estimatedCost /= 2;
  107273. }
  107274. if( iLe>=0 ){
  107275. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  107276. pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
  107277. pInfo->estimatedCost /= 2;
  107278. }
  107279. }
  107280. return SQLITE_OK;
  107281. }
  107282. /*
  107283. ** xOpen - Open a cursor.
  107284. */
  107285. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  107286. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  107287. UNUSED_PARAMETER(pVTab);
  107288. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  107289. if( !pCsr ) return SQLITE_NOMEM;
  107290. memset(pCsr, 0, sizeof(Fts3auxCursor));
  107291. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  107292. return SQLITE_OK;
  107293. }
  107294. /*
  107295. ** xClose - Close a cursor.
  107296. */
  107297. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  107298. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  107299. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  107300. sqlite3Fts3SegmentsClose(pFts3);
  107301. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  107302. sqlite3_free((void *)pCsr->filter.zTerm);
  107303. sqlite3_free(pCsr->zStop);
  107304. sqlite3_free(pCsr->aStat);
  107305. sqlite3_free(pCsr);
  107306. return SQLITE_OK;
  107307. }
  107308. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  107309. if( nSize>pCsr->nStat ){
  107310. struct Fts3auxColstats *aNew;
  107311. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  107312. sizeof(struct Fts3auxColstats) * nSize
  107313. );
  107314. if( aNew==0 ) return SQLITE_NOMEM;
  107315. memset(&aNew[pCsr->nStat], 0,
  107316. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  107317. );
  107318. pCsr->aStat = aNew;
  107319. pCsr->nStat = nSize;
  107320. }
  107321. return SQLITE_OK;
  107322. }
  107323. /*
  107324. ** xNext - Advance the cursor to the next row, if any.
  107325. */
  107326. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  107327. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  107328. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  107329. int rc;
  107330. /* Increment our pretend rowid value. */
  107331. pCsr->iRowid++;
  107332. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  107333. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  107334. }
  107335. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  107336. if( rc==SQLITE_ROW ){
  107337. int i = 0;
  107338. int nDoclist = pCsr->csr.nDoclist;
  107339. char *aDoclist = pCsr->csr.aDoclist;
  107340. int iCol;
  107341. int eState = 0;
  107342. if( pCsr->zStop ){
  107343. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  107344. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  107345. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  107346. pCsr->isEof = 1;
  107347. return SQLITE_OK;
  107348. }
  107349. }
  107350. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  107351. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  107352. iCol = 0;
  107353. while( i<nDoclist ){
  107354. sqlite3_int64 v = 0;
  107355. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  107356. switch( eState ){
  107357. /* State 0. In this state the integer just read was a docid. */
  107358. case 0:
  107359. pCsr->aStat[0].nDoc++;
  107360. eState = 1;
  107361. iCol = 0;
  107362. break;
  107363. /* State 1. In this state we are expecting either a 1, indicating
  107364. ** that the following integer will be a column number, or the
  107365. ** start of a position list for column 0.
  107366. **
  107367. ** The only difference between state 1 and state 2 is that if the
  107368. ** integer encountered in state 1 is not 0 or 1, then we need to
  107369. ** increment the column 0 "nDoc" count for this term.
  107370. */
  107371. case 1:
  107372. assert( iCol==0 );
  107373. if( v>1 ){
  107374. pCsr->aStat[1].nDoc++;
  107375. }
  107376. eState = 2;
  107377. /* fall through */
  107378. case 2:
  107379. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  107380. eState = 0;
  107381. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  107382. eState = 3;
  107383. }else{ /* 2 or greater. A position. */
  107384. pCsr->aStat[iCol+1].nOcc++;
  107385. pCsr->aStat[0].nOcc++;
  107386. }
  107387. break;
  107388. /* State 3. The integer just read is a column number. */
  107389. default: assert( eState==3 );
  107390. iCol = (int)v;
  107391. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  107392. pCsr->aStat[iCol+1].nDoc++;
  107393. eState = 2;
  107394. break;
  107395. }
  107396. }
  107397. pCsr->iCol = 0;
  107398. rc = SQLITE_OK;
  107399. }else{
  107400. pCsr->isEof = 1;
  107401. }
  107402. return rc;
  107403. }
  107404. /*
  107405. ** xFilter - Initialize a cursor to point at the start of its data.
  107406. */
  107407. static int fts3auxFilterMethod(
  107408. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  107409. int idxNum, /* Strategy index */
  107410. const char *idxStr, /* Unused */
  107411. int nVal, /* Number of elements in apVal */
  107412. sqlite3_value **apVal /* Arguments for the indexing scheme */
  107413. ){
  107414. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  107415. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  107416. int rc;
  107417. int isScan;
  107418. UNUSED_PARAMETER(nVal);
  107419. assert( idxStr==0 );
  107420. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  107421. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  107422. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  107423. );
  107424. isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
  107425. /* In case this cursor is being reused, close and zero it. */
  107426. testcase(pCsr->filter.zTerm);
  107427. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  107428. sqlite3_free((void *)pCsr->filter.zTerm);
  107429. sqlite3_free(pCsr->aStat);
  107430. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  107431. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  107432. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  107433. if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
  107434. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  107435. if( zStr ){
  107436. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  107437. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  107438. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  107439. }
  107440. }
  107441. if( idxNum&FTS4AUX_LE_CONSTRAINT ){
  107442. int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
  107443. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
  107444. pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
  107445. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  107446. }
  107447. rc = sqlite3Fts3SegReaderCursor(pFts3, FTS3_SEGCURSOR_ALL,
  107448. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  107449. );
  107450. if( rc==SQLITE_OK ){
  107451. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  107452. }
  107453. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  107454. return rc;
  107455. }
  107456. /*
  107457. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  107458. */
  107459. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  107460. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  107461. return pCsr->isEof;
  107462. }
  107463. /*
  107464. ** xColumn - Return a column value.
  107465. */
  107466. static int fts3auxColumnMethod(
  107467. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  107468. sqlite3_context *pContext, /* Context for sqlite3_result_xxx() calls */
  107469. int iCol /* Index of column to read value from */
  107470. ){
  107471. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  107472. assert( p->isEof==0 );
  107473. if( iCol==0 ){ /* Column "term" */
  107474. sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  107475. }else if( iCol==1 ){ /* Column "col" */
  107476. if( p->iCol ){
  107477. sqlite3_result_int(pContext, p->iCol-1);
  107478. }else{
  107479. sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
  107480. }
  107481. }else if( iCol==2 ){ /* Column "documents" */
  107482. sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
  107483. }else{ /* Column "occurrences" */
  107484. sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
  107485. }
  107486. return SQLITE_OK;
  107487. }
  107488. /*
  107489. ** xRowid - Return the current rowid for the cursor.
  107490. */
  107491. static int fts3auxRowidMethod(
  107492. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  107493. sqlite_int64 *pRowid /* OUT: Rowid value */
  107494. ){
  107495. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  107496. *pRowid = pCsr->iRowid;
  107497. return SQLITE_OK;
  107498. }
  107499. /*
  107500. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  107501. ** if successful or an error code if sqlite3_create_module() fails.
  107502. */
  107503. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  107504. static const sqlite3_module fts3aux_module = {
  107505. 0, /* iVersion */
  107506. fts3auxConnectMethod, /* xCreate */
  107507. fts3auxConnectMethod, /* xConnect */
  107508. fts3auxBestIndexMethod, /* xBestIndex */
  107509. fts3auxDisconnectMethod, /* xDisconnect */
  107510. fts3auxDisconnectMethod, /* xDestroy */
  107511. fts3auxOpenMethod, /* xOpen */
  107512. fts3auxCloseMethod, /* xClose */
  107513. fts3auxFilterMethod, /* xFilter */
  107514. fts3auxNextMethod, /* xNext */
  107515. fts3auxEofMethod, /* xEof */
  107516. fts3auxColumnMethod, /* xColumn */
  107517. fts3auxRowidMethod, /* xRowid */
  107518. 0, /* xUpdate */
  107519. 0, /* xBegin */
  107520. 0, /* xSync */
  107521. 0, /* xCommit */
  107522. 0, /* xRollback */
  107523. 0, /* xFindFunction */
  107524. 0 /* xRename */
  107525. };
  107526. int rc; /* Return code */
  107527. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  107528. return rc;
  107529. }
  107530. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  107531. /************** End of fts3_aux.c ********************************************/
  107532. /************** Begin file fts3_expr.c ***************************************/
  107533. /*
  107534. ** 2008 Nov 28
  107535. **
  107536. ** The author disclaims copyright to this source code. In place of
  107537. ** a legal notice, here is a blessing:
  107538. **
  107539. ** May you do good and not evil.
  107540. ** May you find forgiveness for yourself and forgive others.
  107541. ** May you share freely, never taking more than you give.
  107542. **
  107543. ******************************************************************************
  107544. **
  107545. ** This module contains code that implements a parser for fts3 query strings
  107546. ** (the right-hand argument to the MATCH operator). Because the supported
  107547. ** syntax is relatively simple, the whole tokenizer/parser system is
  107548. ** hand-coded.
  107549. */
  107550. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  107551. /*
  107552. ** By default, this module parses the legacy syntax that has been
  107553. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  107554. ** is defined, then it uses the new syntax. The differences between
  107555. ** the new and the old syntaxes are:
  107556. **
  107557. ** a) The new syntax supports parenthesis. The old does not.
  107558. **
  107559. ** b) The new syntax supports the AND and NOT operators. The old does not.
  107560. **
  107561. ** c) The old syntax supports the "-" token qualifier. This is not
  107562. ** supported by the new syntax (it is replaced by the NOT operator).
  107563. **
  107564. ** d) When using the old syntax, the OR operator has a greater precedence
  107565. ** than an implicit AND. When using the new, both implicity and explicit
  107566. ** AND operators have a higher precedence than OR.
  107567. **
  107568. ** If compiled with SQLITE_TEST defined, then this module exports the
  107569. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  107570. ** to zero causes the module to use the old syntax. If it is set to
  107571. ** non-zero the new syntax is activated. This is so both syntaxes can
  107572. ** be tested using a single build of testfixture.
  107573. **
  107574. ** The following describes the syntax supported by the fts3 MATCH
  107575. ** operator in a similar format to that used by the lemon parser
  107576. ** generator. This module does not use actually lemon, it uses a
  107577. ** custom parser.
  107578. **
  107579. ** query ::= andexpr (OR andexpr)*.
  107580. **
  107581. ** andexpr ::= notexpr (AND? notexpr)*.
  107582. **
  107583. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  107584. ** notexpr ::= LP query RP.
  107585. **
  107586. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  107587. **
  107588. ** distance_opt ::= .
  107589. ** distance_opt ::= / INTEGER.
  107590. **
  107591. ** phrase ::= TOKEN.
  107592. ** phrase ::= COLUMN:TOKEN.
  107593. ** phrase ::= "TOKEN TOKEN TOKEN...".
  107594. */
  107595. #ifdef SQLITE_TEST
  107596. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  107597. #else
  107598. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  107599. # define sqlite3_fts3_enable_parentheses 1
  107600. # else
  107601. # define sqlite3_fts3_enable_parentheses 0
  107602. # endif
  107603. #endif
  107604. /*
  107605. ** Default span for NEAR operators.
  107606. */
  107607. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  107608. typedef struct ParseContext ParseContext;
  107609. struct ParseContext {
  107610. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  107611. const char **azCol; /* Array of column names for fts3 table */
  107612. int nCol; /* Number of entries in azCol[] */
  107613. int iDefaultCol; /* Default column to query */
  107614. sqlite3_context *pCtx; /* Write error message here */
  107615. int nNest; /* Number of nested brackets */
  107616. };
  107617. /*
  107618. ** This function is equivalent to the standard isspace() function.
  107619. **
  107620. ** The standard isspace() can be awkward to use safely, because although it
  107621. ** is defined to accept an argument of type int, its behaviour when passed
  107622. ** an integer that falls outside of the range of the unsigned char type
  107623. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  107624. ** is defined to accept an argument of type char, and always returns 0 for
  107625. ** any values that fall outside of the range of the unsigned char type (i.e.
  107626. ** negative values).
  107627. */
  107628. static int fts3isspace(char c){
  107629. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  107630. }
  107631. /*
  107632. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  107633. ** zero the memory before returning a pointer to it. If unsuccessful,
  107634. ** return NULL.
  107635. */
  107636. static void *fts3MallocZero(int nByte){
  107637. void *pRet = sqlite3_malloc(nByte);
  107638. if( pRet ) memset(pRet, 0, nByte);
  107639. return pRet;
  107640. }
  107641. /*
  107642. ** Extract the next token from buffer z (length n) using the tokenizer
  107643. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  107644. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  107645. ** single token and set *ppExpr to point to it. If the end of the buffer is
  107646. ** reached before a token is found, set *ppExpr to zero. It is the
  107647. ** responsibility of the caller to eventually deallocate the allocated
  107648. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  107649. **
  107650. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  107651. ** fails.
  107652. */
  107653. static int getNextToken(
  107654. ParseContext *pParse, /* fts3 query parse context */
  107655. int iCol, /* Value for Fts3Phrase.iColumn */
  107656. const char *z, int n, /* Input string */
  107657. Fts3Expr **ppExpr, /* OUT: expression */
  107658. int *pnConsumed /* OUT: Number of bytes consumed */
  107659. ){
  107660. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  107661. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  107662. int rc;
  107663. sqlite3_tokenizer_cursor *pCursor;
  107664. Fts3Expr *pRet = 0;
  107665. int nConsumed = 0;
  107666. rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
  107667. if( rc==SQLITE_OK ){
  107668. const char *zToken;
  107669. int nToken, iStart, iEnd, iPosition;
  107670. int nByte; /* total space to allocate */
  107671. pCursor->pTokenizer = pTokenizer;
  107672. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  107673. if( rc==SQLITE_OK ){
  107674. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  107675. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  107676. if( !pRet ){
  107677. rc = SQLITE_NOMEM;
  107678. }else{
  107679. pRet->eType = FTSQUERY_PHRASE;
  107680. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  107681. pRet->pPhrase->nToken = 1;
  107682. pRet->pPhrase->iColumn = iCol;
  107683. pRet->pPhrase->aToken[0].n = nToken;
  107684. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  107685. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  107686. if( iEnd<n && z[iEnd]=='*' ){
  107687. pRet->pPhrase->aToken[0].isPrefix = 1;
  107688. iEnd++;
  107689. }
  107690. if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
  107691. pRet->pPhrase->isNot = 1;
  107692. }
  107693. }
  107694. nConsumed = iEnd;
  107695. }
  107696. pModule->xClose(pCursor);
  107697. }
  107698. *pnConsumed = nConsumed;
  107699. *ppExpr = pRet;
  107700. return rc;
  107701. }
  107702. /*
  107703. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  107704. ** then free the old allocation.
  107705. */
  107706. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  107707. void *pRet = sqlite3_realloc(pOrig, nNew);
  107708. if( !pRet ){
  107709. sqlite3_free(pOrig);
  107710. }
  107711. return pRet;
  107712. }
  107713. /*
  107714. ** Buffer zInput, length nInput, contains the contents of a quoted string
  107715. ** that appeared as part of an fts3 query expression. Neither quote character
  107716. ** is included in the buffer. This function attempts to tokenize the entire
  107717. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  107718. ** containing the results.
  107719. **
  107720. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  107721. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  107722. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  107723. ** to 0.
  107724. */
  107725. static int getNextString(
  107726. ParseContext *pParse, /* fts3 query parse context */
  107727. const char *zInput, int nInput, /* Input string */
  107728. Fts3Expr **ppExpr /* OUT: expression */
  107729. ){
  107730. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  107731. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  107732. int rc;
  107733. Fts3Expr *p = 0;
  107734. sqlite3_tokenizer_cursor *pCursor = 0;
  107735. char *zTemp = 0;
  107736. int nTemp = 0;
  107737. rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
  107738. if( rc==SQLITE_OK ){
  107739. int ii;
  107740. pCursor->pTokenizer = pTokenizer;
  107741. for(ii=0; rc==SQLITE_OK; ii++){
  107742. const char *zToken;
  107743. int nToken, iBegin, iEnd, iPos;
  107744. rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
  107745. if( rc==SQLITE_OK ){
  107746. int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  107747. p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
  107748. zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
  107749. if( !p || !zTemp ){
  107750. goto no_mem;
  107751. }
  107752. if( ii==0 ){
  107753. memset(p, 0, nByte);
  107754. p->pPhrase = (Fts3Phrase *)&p[1];
  107755. }
  107756. p->pPhrase = (Fts3Phrase *)&p[1];
  107757. memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
  107758. p->pPhrase->nToken = ii+1;
  107759. p->pPhrase->aToken[ii].n = nToken;
  107760. memcpy(&zTemp[nTemp], zToken, nToken);
  107761. nTemp += nToken;
  107762. if( iEnd<nInput && zInput[iEnd]=='*' ){
  107763. p->pPhrase->aToken[ii].isPrefix = 1;
  107764. }else{
  107765. p->pPhrase->aToken[ii].isPrefix = 0;
  107766. }
  107767. }
  107768. }
  107769. pModule->xClose(pCursor);
  107770. pCursor = 0;
  107771. }
  107772. if( rc==SQLITE_DONE ){
  107773. int jj;
  107774. char *zNew = NULL;
  107775. int nNew = 0;
  107776. int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  107777. nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
  107778. p = fts3ReallocOrFree(p, nByte + nTemp);
  107779. if( !p ){
  107780. goto no_mem;
  107781. }
  107782. if( zTemp ){
  107783. zNew = &(((char *)p)[nByte]);
  107784. memcpy(zNew, zTemp, nTemp);
  107785. }else{
  107786. memset(p, 0, nByte+nTemp);
  107787. }
  107788. p->pPhrase = (Fts3Phrase *)&p[1];
  107789. for(jj=0; jj<p->pPhrase->nToken; jj++){
  107790. p->pPhrase->aToken[jj].z = &zNew[nNew];
  107791. nNew += p->pPhrase->aToken[jj].n;
  107792. }
  107793. sqlite3_free(zTemp);
  107794. p->eType = FTSQUERY_PHRASE;
  107795. p->pPhrase->iColumn = pParse->iDefaultCol;
  107796. rc = SQLITE_OK;
  107797. }
  107798. *ppExpr = p;
  107799. return rc;
  107800. no_mem:
  107801. if( pCursor ){
  107802. pModule->xClose(pCursor);
  107803. }
  107804. sqlite3_free(zTemp);
  107805. sqlite3_free(p);
  107806. *ppExpr = 0;
  107807. return SQLITE_NOMEM;
  107808. }
  107809. /*
  107810. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  107811. ** call fts3ExprParse(). So this forward declaration is required.
  107812. */
  107813. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  107814. /*
  107815. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  107816. ** structure, or set to 0 if the end of the input buffer is reached.
  107817. **
  107818. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  107819. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  107820. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  107821. */
  107822. static int getNextNode(
  107823. ParseContext *pParse, /* fts3 query parse context */
  107824. const char *z, int n, /* Input string */
  107825. Fts3Expr **ppExpr, /* OUT: expression */
  107826. int *pnConsumed /* OUT: Number of bytes consumed */
  107827. ){
  107828. static const struct Fts3Keyword {
  107829. char *z; /* Keyword text */
  107830. unsigned char n; /* Length of the keyword */
  107831. unsigned char parenOnly; /* Only valid in paren mode */
  107832. unsigned char eType; /* Keyword code */
  107833. } aKeyword[] = {
  107834. { "OR" , 2, 0, FTSQUERY_OR },
  107835. { "AND", 3, 1, FTSQUERY_AND },
  107836. { "NOT", 3, 1, FTSQUERY_NOT },
  107837. { "NEAR", 4, 0, FTSQUERY_NEAR }
  107838. };
  107839. int ii;
  107840. int iCol;
  107841. int iColLen;
  107842. int rc;
  107843. Fts3Expr *pRet = 0;
  107844. const char *zInput = z;
  107845. int nInput = n;
  107846. /* Skip over any whitespace before checking for a keyword, an open or
  107847. ** close bracket, or a quoted string.
  107848. */
  107849. while( nInput>0 && fts3isspace(*zInput) ){
  107850. nInput--;
  107851. zInput++;
  107852. }
  107853. if( nInput==0 ){
  107854. return SQLITE_DONE;
  107855. }
  107856. /* See if we are dealing with a keyword. */
  107857. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  107858. const struct Fts3Keyword *pKey = &aKeyword[ii];
  107859. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  107860. continue;
  107861. }
  107862. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  107863. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  107864. int nKey = pKey->n;
  107865. char cNext;
  107866. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  107867. if( pKey->eType==FTSQUERY_NEAR ){
  107868. assert( nKey==4 );
  107869. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  107870. nNear = 0;
  107871. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  107872. nNear = nNear * 10 + (zInput[nKey] - '0');
  107873. }
  107874. }
  107875. }
  107876. /* At this point this is probably a keyword. But for that to be true,
  107877. ** the next byte must contain either whitespace, an open or close
  107878. ** parenthesis, a quote character, or EOF.
  107879. */
  107880. cNext = zInput[nKey];
  107881. if( fts3isspace(cNext)
  107882. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  107883. ){
  107884. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  107885. if( !pRet ){
  107886. return SQLITE_NOMEM;
  107887. }
  107888. pRet->eType = pKey->eType;
  107889. pRet->nNear = nNear;
  107890. *ppExpr = pRet;
  107891. *pnConsumed = (int)((zInput - z) + nKey);
  107892. return SQLITE_OK;
  107893. }
  107894. /* Turns out that wasn't a keyword after all. This happens if the
  107895. ** user has supplied a token such as "ORacle". Continue.
  107896. */
  107897. }
  107898. }
  107899. /* Check for an open bracket. */
  107900. if( sqlite3_fts3_enable_parentheses ){
  107901. if( *zInput=='(' ){
  107902. int nConsumed;
  107903. pParse->nNest++;
  107904. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  107905. if( rc==SQLITE_OK && !*ppExpr ){
  107906. rc = SQLITE_DONE;
  107907. }
  107908. *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
  107909. return rc;
  107910. }
  107911. /* Check for a close bracket. */
  107912. if( *zInput==')' ){
  107913. pParse->nNest--;
  107914. *pnConsumed = (int)((zInput - z) + 1);
  107915. return SQLITE_DONE;
  107916. }
  107917. }
  107918. /* See if we are dealing with a quoted phrase. If this is the case, then
  107919. ** search for the closing quote and pass the whole string to getNextString()
  107920. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  107921. ** a quote character embedded in a string.
  107922. */
  107923. if( *zInput=='"' ){
  107924. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  107925. *pnConsumed = (int)((zInput - z) + ii + 1);
  107926. if( ii==nInput ){
  107927. return SQLITE_ERROR;
  107928. }
  107929. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  107930. }
  107931. /* If control flows to this point, this must be a regular token, or
  107932. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  107933. ** interface. Before doing so, figure out if there is an explicit
  107934. ** column specifier for the token.
  107935. **
  107936. ** TODO: Strangely, it is not possible to associate a column specifier
  107937. ** with a quoted phrase, only with a single token. Not sure if this was
  107938. ** an implementation artifact or an intentional decision when fts3 was
  107939. ** first implemented. Whichever it was, this module duplicates the
  107940. ** limitation.
  107941. */
  107942. iCol = pParse->iDefaultCol;
  107943. iColLen = 0;
  107944. for(ii=0; ii<pParse->nCol; ii++){
  107945. const char *zStr = pParse->azCol[ii];
  107946. int nStr = (int)strlen(zStr);
  107947. if( nInput>nStr && zInput[nStr]==':'
  107948. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  107949. ){
  107950. iCol = ii;
  107951. iColLen = (int)((zInput - z) + nStr + 1);
  107952. break;
  107953. }
  107954. }
  107955. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  107956. *pnConsumed += iColLen;
  107957. return rc;
  107958. }
  107959. /*
  107960. ** The argument is an Fts3Expr structure for a binary operator (any type
  107961. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  107962. ** precedence of the operator. Lower values have a higher precedence (i.e.
  107963. ** group more tightly). For example, in the C language, the == operator
  107964. ** groups more tightly than ||, and would therefore have a higher precedence.
  107965. **
  107966. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  107967. ** is defined), the order of the operators in precedence from highest to
  107968. ** lowest is:
  107969. **
  107970. ** NEAR
  107971. ** NOT
  107972. ** AND (including implicit ANDs)
  107973. ** OR
  107974. **
  107975. ** Note that when using the old query syntax, the OR operator has a higher
  107976. ** precedence than the AND operator.
  107977. */
  107978. static int opPrecedence(Fts3Expr *p){
  107979. assert( p->eType!=FTSQUERY_PHRASE );
  107980. if( sqlite3_fts3_enable_parentheses ){
  107981. return p->eType;
  107982. }else if( p->eType==FTSQUERY_NEAR ){
  107983. return 1;
  107984. }else if( p->eType==FTSQUERY_OR ){
  107985. return 2;
  107986. }
  107987. assert( p->eType==FTSQUERY_AND );
  107988. return 3;
  107989. }
  107990. /*
  107991. ** Argument ppHead contains a pointer to the current head of a query
  107992. ** expression tree being parsed. pPrev is the expression node most recently
  107993. ** inserted into the tree. This function adds pNew, which is always a binary
  107994. ** operator node, into the expression tree based on the relative precedence
  107995. ** of pNew and the existing nodes of the tree. This may result in the head
  107996. ** of the tree changing, in which case *ppHead is set to the new root node.
  107997. */
  107998. static void insertBinaryOperator(
  107999. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  108000. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  108001. Fts3Expr *pNew /* New binary node to insert into expression tree */
  108002. ){
  108003. Fts3Expr *pSplit = pPrev;
  108004. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  108005. pSplit = pSplit->pParent;
  108006. }
  108007. if( pSplit->pParent ){
  108008. assert( pSplit->pParent->pRight==pSplit );
  108009. pSplit->pParent->pRight = pNew;
  108010. pNew->pParent = pSplit->pParent;
  108011. }else{
  108012. *ppHead = pNew;
  108013. }
  108014. pNew->pLeft = pSplit;
  108015. pSplit->pParent = pNew;
  108016. }
  108017. /*
  108018. ** Parse the fts3 query expression found in buffer z, length n. This function
  108019. ** returns either when the end of the buffer is reached or an unmatched
  108020. ** closing bracket - ')' - is encountered.
  108021. **
  108022. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  108023. ** parsed form of the expression and *pnConsumed is set to the number of
  108024. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  108025. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  108026. */
  108027. static int fts3ExprParse(
  108028. ParseContext *pParse, /* fts3 query parse context */
  108029. const char *z, int n, /* Text of MATCH query */
  108030. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  108031. int *pnConsumed /* OUT: Number of bytes consumed */
  108032. ){
  108033. Fts3Expr *pRet = 0;
  108034. Fts3Expr *pPrev = 0;
  108035. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  108036. int nIn = n;
  108037. const char *zIn = z;
  108038. int rc = SQLITE_OK;
  108039. int isRequirePhrase = 1;
  108040. while( rc==SQLITE_OK ){
  108041. Fts3Expr *p = 0;
  108042. int nByte = 0;
  108043. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  108044. if( rc==SQLITE_OK ){
  108045. int isPhrase;
  108046. if( !sqlite3_fts3_enable_parentheses
  108047. && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
  108048. ){
  108049. /* Create an implicit NOT operator. */
  108050. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  108051. if( !pNot ){
  108052. sqlite3Fts3ExprFree(p);
  108053. rc = SQLITE_NOMEM;
  108054. goto exprparse_out;
  108055. }
  108056. pNot->eType = FTSQUERY_NOT;
  108057. pNot->pRight = p;
  108058. if( pNotBranch ){
  108059. pNot->pLeft = pNotBranch;
  108060. }
  108061. pNotBranch = pNot;
  108062. p = pPrev;
  108063. }else{
  108064. int eType = p->eType;
  108065. assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
  108066. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  108067. /* The isRequirePhrase variable is set to true if a phrase or
  108068. ** an expression contained in parenthesis is required. If a
  108069. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  108070. ** isRequirePhrase is set, this is a syntax error.
  108071. */
  108072. if( !isPhrase && isRequirePhrase ){
  108073. sqlite3Fts3ExprFree(p);
  108074. rc = SQLITE_ERROR;
  108075. goto exprparse_out;
  108076. }
  108077. if( isPhrase && !isRequirePhrase ){
  108078. /* Insert an implicit AND operator. */
  108079. Fts3Expr *pAnd;
  108080. assert( pRet && pPrev );
  108081. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  108082. if( !pAnd ){
  108083. sqlite3Fts3ExprFree(p);
  108084. rc = SQLITE_NOMEM;
  108085. goto exprparse_out;
  108086. }
  108087. pAnd->eType = FTSQUERY_AND;
  108088. insertBinaryOperator(&pRet, pPrev, pAnd);
  108089. pPrev = pAnd;
  108090. }
  108091. /* This test catches attempts to make either operand of a NEAR
  108092. ** operator something other than a phrase. For example, either of
  108093. ** the following:
  108094. **
  108095. ** (bracketed expression) NEAR phrase
  108096. ** phrase NEAR (bracketed expression)
  108097. **
  108098. ** Return an error in either case.
  108099. */
  108100. if( pPrev && (
  108101. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  108102. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  108103. )){
  108104. sqlite3Fts3ExprFree(p);
  108105. rc = SQLITE_ERROR;
  108106. goto exprparse_out;
  108107. }
  108108. if( isPhrase ){
  108109. if( pRet ){
  108110. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  108111. pPrev->pRight = p;
  108112. p->pParent = pPrev;
  108113. }else{
  108114. pRet = p;
  108115. }
  108116. }else{
  108117. insertBinaryOperator(&pRet, pPrev, p);
  108118. }
  108119. isRequirePhrase = !isPhrase;
  108120. }
  108121. assert( nByte>0 );
  108122. }
  108123. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  108124. nIn -= nByte;
  108125. zIn += nByte;
  108126. pPrev = p;
  108127. }
  108128. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  108129. rc = SQLITE_ERROR;
  108130. }
  108131. if( rc==SQLITE_DONE ){
  108132. rc = SQLITE_OK;
  108133. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  108134. if( !pRet ){
  108135. rc = SQLITE_ERROR;
  108136. }else{
  108137. Fts3Expr *pIter = pNotBranch;
  108138. while( pIter->pLeft ){
  108139. pIter = pIter->pLeft;
  108140. }
  108141. pIter->pLeft = pRet;
  108142. pRet = pNotBranch;
  108143. }
  108144. }
  108145. }
  108146. *pnConsumed = n - nIn;
  108147. exprparse_out:
  108148. if( rc!=SQLITE_OK ){
  108149. sqlite3Fts3ExprFree(pRet);
  108150. sqlite3Fts3ExprFree(pNotBranch);
  108151. pRet = 0;
  108152. }
  108153. *ppExpr = pRet;
  108154. return rc;
  108155. }
  108156. /*
  108157. ** Parameters z and n contain a pointer to and length of a buffer containing
  108158. ** an fts3 query expression, respectively. This function attempts to parse the
  108159. ** query expression and create a tree of Fts3Expr structures representing the
  108160. ** parsed expression. If successful, *ppExpr is set to point to the head
  108161. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  108162. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  108163. ** error) is returned and *ppExpr is set to 0.
  108164. **
  108165. ** If parameter n is a negative number, then z is assumed to point to a
  108166. ** nul-terminated string and the length is determined using strlen().
  108167. **
  108168. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  108169. ** use to normalize query tokens while parsing the expression. The azCol[]
  108170. ** array, which is assumed to contain nCol entries, should contain the names
  108171. ** of each column in the target fts3 table, in order from left to right.
  108172. ** Column names must be nul-terminated strings.
  108173. **
  108174. ** The iDefaultCol parameter should be passed the index of the table column
  108175. ** that appears on the left-hand-side of the MATCH operator (the default
  108176. ** column to match against for tokens for which a column name is not explicitly
  108177. ** specified as part of the query string), or -1 if tokens may by default
  108178. ** match any table column.
  108179. */
  108180. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  108181. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  108182. char **azCol, /* Array of column names for fts3 table */
  108183. int nCol, /* Number of entries in azCol[] */
  108184. int iDefaultCol, /* Default column to query */
  108185. const char *z, int n, /* Text of MATCH query */
  108186. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  108187. ){
  108188. int nParsed;
  108189. int rc;
  108190. ParseContext sParse;
  108191. sParse.pTokenizer = pTokenizer;
  108192. sParse.azCol = (const char **)azCol;
  108193. sParse.nCol = nCol;
  108194. sParse.iDefaultCol = iDefaultCol;
  108195. sParse.nNest = 0;
  108196. if( z==0 ){
  108197. *ppExpr = 0;
  108198. return SQLITE_OK;
  108199. }
  108200. if( n<0 ){
  108201. n = (int)strlen(z);
  108202. }
  108203. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  108204. /* Check for mismatched parenthesis */
  108205. if( rc==SQLITE_OK && sParse.nNest ){
  108206. rc = SQLITE_ERROR;
  108207. sqlite3Fts3ExprFree(*ppExpr);
  108208. *ppExpr = 0;
  108209. }
  108210. return rc;
  108211. }
  108212. /*
  108213. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  108214. */
  108215. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
  108216. if( p ){
  108217. sqlite3Fts3ExprFree(p->pLeft);
  108218. sqlite3Fts3ExprFree(p->pRight);
  108219. sqlite3_free(p->aDoclist);
  108220. sqlite3_free(p);
  108221. }
  108222. }
  108223. /****************************************************************************
  108224. *****************************************************************************
  108225. ** Everything after this point is just test code.
  108226. */
  108227. #ifdef SQLITE_TEST
  108228. /*
  108229. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  108230. */
  108231. static int queryTestTokenizer(
  108232. sqlite3 *db,
  108233. const char *zName,
  108234. const sqlite3_tokenizer_module **pp
  108235. ){
  108236. int rc;
  108237. sqlite3_stmt *pStmt;
  108238. const char zSql[] = "SELECT fts3_tokenizer(?)";
  108239. *pp = 0;
  108240. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  108241. if( rc!=SQLITE_OK ){
  108242. return rc;
  108243. }
  108244. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  108245. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  108246. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  108247. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  108248. }
  108249. }
  108250. return sqlite3_finalize(pStmt);
  108251. }
  108252. /*
  108253. ** Return a pointer to a buffer containing a text representation of the
  108254. ** expression passed as the first argument. The buffer is obtained from
  108255. ** sqlite3_malloc(). It is the responsibility of the caller to use
  108256. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  108257. ** NULL is returned.
  108258. **
  108259. ** If the second argument is not NULL, then its contents are prepended to
  108260. ** the returned expression text and then freed using sqlite3_free().
  108261. */
  108262. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  108263. switch( pExpr->eType ){
  108264. case FTSQUERY_PHRASE: {
  108265. Fts3Phrase *pPhrase = pExpr->pPhrase;
  108266. int i;
  108267. zBuf = sqlite3_mprintf(
  108268. "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
  108269. for(i=0; zBuf && i<pPhrase->nToken; i++){
  108270. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  108271. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  108272. (pPhrase->aToken[i].isPrefix?"+":"")
  108273. );
  108274. }
  108275. return zBuf;
  108276. }
  108277. case FTSQUERY_NEAR:
  108278. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  108279. break;
  108280. case FTSQUERY_NOT:
  108281. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  108282. break;
  108283. case FTSQUERY_AND:
  108284. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  108285. break;
  108286. case FTSQUERY_OR:
  108287. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  108288. break;
  108289. }
  108290. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  108291. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  108292. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  108293. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  108294. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  108295. return zBuf;
  108296. }
  108297. /*
  108298. ** This is the implementation of a scalar SQL function used to test the
  108299. ** expression parser. It should be called as follows:
  108300. **
  108301. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  108302. **
  108303. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  108304. ** to parse the query expression (see README.tokenizers). The second argument
  108305. ** is the query expression to parse. Each subsequent argument is the name
  108306. ** of a column of the fts3 table that the query expression may refer to.
  108307. ** For example:
  108308. **
  108309. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  108310. */
  108311. static void fts3ExprTest(
  108312. sqlite3_context *context,
  108313. int argc,
  108314. sqlite3_value **argv
  108315. ){
  108316. sqlite3_tokenizer_module const *pModule = 0;
  108317. sqlite3_tokenizer *pTokenizer = 0;
  108318. int rc;
  108319. char **azCol = 0;
  108320. const char *zExpr;
  108321. int nExpr;
  108322. int nCol;
  108323. int ii;
  108324. Fts3Expr *pExpr;
  108325. char *zBuf = 0;
  108326. sqlite3 *db = sqlite3_context_db_handle(context);
  108327. if( argc<3 ){
  108328. sqlite3_result_error(context,
  108329. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  108330. );
  108331. return;
  108332. }
  108333. rc = queryTestTokenizer(db,
  108334. (const char *)sqlite3_value_text(argv[0]), &pModule);
  108335. if( rc==SQLITE_NOMEM ){
  108336. sqlite3_result_error_nomem(context);
  108337. goto exprtest_out;
  108338. }else if( !pModule ){
  108339. sqlite3_result_error(context, "No such tokenizer module", -1);
  108340. goto exprtest_out;
  108341. }
  108342. rc = pModule->xCreate(0, 0, &pTokenizer);
  108343. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  108344. if( rc==SQLITE_NOMEM ){
  108345. sqlite3_result_error_nomem(context);
  108346. goto exprtest_out;
  108347. }
  108348. pTokenizer->pModule = pModule;
  108349. zExpr = (const char *)sqlite3_value_text(argv[1]);
  108350. nExpr = sqlite3_value_bytes(argv[1]);
  108351. nCol = argc-2;
  108352. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  108353. if( !azCol ){
  108354. sqlite3_result_error_nomem(context);
  108355. goto exprtest_out;
  108356. }
  108357. for(ii=0; ii<nCol; ii++){
  108358. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  108359. }
  108360. rc = sqlite3Fts3ExprParse(
  108361. pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
  108362. );
  108363. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  108364. sqlite3_result_error(context, "Error parsing expression", -1);
  108365. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  108366. sqlite3_result_error_nomem(context);
  108367. }else{
  108368. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  108369. sqlite3_free(zBuf);
  108370. }
  108371. sqlite3Fts3ExprFree(pExpr);
  108372. exprtest_out:
  108373. if( pModule && pTokenizer ){
  108374. rc = pModule->xDestroy(pTokenizer);
  108375. }
  108376. sqlite3_free(azCol);
  108377. }
  108378. /*
  108379. ** Register the query expression parser test function fts3_exprtest()
  108380. ** with database connection db.
  108381. */
  108382. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  108383. return sqlite3_create_function(
  108384. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  108385. );
  108386. }
  108387. #endif
  108388. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  108389. /************** End of fts3_expr.c *******************************************/
  108390. /************** Begin file fts3_hash.c ***************************************/
  108391. /*
  108392. ** 2001 September 22
  108393. **
  108394. ** The author disclaims copyright to this source code. In place of
  108395. ** a legal notice, here is a blessing:
  108396. **
  108397. ** May you do good and not evil.
  108398. ** May you find forgiveness for yourself and forgive others.
  108399. ** May you share freely, never taking more than you give.
  108400. **
  108401. *************************************************************************
  108402. ** This is the implementation of generic hash-tables used in SQLite.
  108403. ** We've modified it slightly to serve as a standalone hash table
  108404. ** implementation for the full-text indexing module.
  108405. */
  108406. /*
  108407. ** The code in this file is only compiled if:
  108408. **
  108409. ** * The FTS3 module is being built as an extension
  108410. ** (in which case SQLITE_CORE is not defined), or
  108411. **
  108412. ** * The FTS3 module is being built into the core of
  108413. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  108414. */
  108415. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  108416. /*
  108417. ** Malloc and Free functions
  108418. */
  108419. static void *fts3HashMalloc(int n){
  108420. void *p = sqlite3_malloc(n);
  108421. if( p ){
  108422. memset(p, 0, n);
  108423. }
  108424. return p;
  108425. }
  108426. static void fts3HashFree(void *p){
  108427. sqlite3_free(p);
  108428. }
  108429. /* Turn bulk memory into a hash table object by initializing the
  108430. ** fields of the Hash structure.
  108431. **
  108432. ** "pNew" is a pointer to the hash table that is to be initialized.
  108433. ** keyClass is one of the constants
  108434. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  108435. ** determines what kind of key the hash table will use. "copyKey" is
  108436. ** true if the hash table should make its own private copy of keys and
  108437. ** false if it should just use the supplied pointer.
  108438. */
  108439. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  108440. assert( pNew!=0 );
  108441. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  108442. pNew->keyClass = keyClass;
  108443. pNew->copyKey = copyKey;
  108444. pNew->first = 0;
  108445. pNew->count = 0;
  108446. pNew->htsize = 0;
  108447. pNew->ht = 0;
  108448. }
  108449. /* Remove all entries from a hash table. Reclaim all memory.
  108450. ** Call this routine to delete a hash table or to reset a hash table
  108451. ** to the empty state.
  108452. */
  108453. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  108454. Fts3HashElem *elem; /* For looping over all elements of the table */
  108455. assert( pH!=0 );
  108456. elem = pH->first;
  108457. pH->first = 0;
  108458. fts3HashFree(pH->ht);
  108459. pH->ht = 0;
  108460. pH->htsize = 0;
  108461. while( elem ){
  108462. Fts3HashElem *next_elem = elem->next;
  108463. if( pH->copyKey && elem->pKey ){
  108464. fts3HashFree(elem->pKey);
  108465. }
  108466. fts3HashFree(elem);
  108467. elem = next_elem;
  108468. }
  108469. pH->count = 0;
  108470. }
  108471. /*
  108472. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  108473. */
  108474. static int fts3StrHash(const void *pKey, int nKey){
  108475. const char *z = (const char *)pKey;
  108476. int h = 0;
  108477. if( nKey<=0 ) nKey = (int) strlen(z);
  108478. while( nKey > 0 ){
  108479. h = (h<<3) ^ h ^ *z++;
  108480. nKey--;
  108481. }
  108482. return h & 0x7fffffff;
  108483. }
  108484. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  108485. if( n1!=n2 ) return 1;
  108486. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  108487. }
  108488. /*
  108489. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  108490. */
  108491. static int fts3BinHash(const void *pKey, int nKey){
  108492. int h = 0;
  108493. const char *z = (const char *)pKey;
  108494. while( nKey-- > 0 ){
  108495. h = (h<<3) ^ h ^ *(z++);
  108496. }
  108497. return h & 0x7fffffff;
  108498. }
  108499. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  108500. if( n1!=n2 ) return 1;
  108501. return memcmp(pKey1,pKey2,n1);
  108502. }
  108503. /*
  108504. ** Return a pointer to the appropriate hash function given the key class.
  108505. **
  108506. ** The C syntax in this function definition may be unfamilar to some
  108507. ** programmers, so we provide the following additional explanation:
  108508. **
  108509. ** The name of the function is "ftsHashFunction". The function takes a
  108510. ** single parameter "keyClass". The return value of ftsHashFunction()
  108511. ** is a pointer to another function. Specifically, the return value
  108512. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  108513. ** with types "const void*" and "int" and returns an "int".
  108514. */
  108515. static int (*ftsHashFunction(int keyClass))(const void*,int){
  108516. if( keyClass==FTS3_HASH_STRING ){
  108517. return &fts3StrHash;
  108518. }else{
  108519. assert( keyClass==FTS3_HASH_BINARY );
  108520. return &fts3BinHash;
  108521. }
  108522. }
  108523. /*
  108524. ** Return a pointer to the appropriate hash function given the key class.
  108525. **
  108526. ** For help in interpreted the obscure C code in the function definition,
  108527. ** see the header comment on the previous function.
  108528. */
  108529. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  108530. if( keyClass==FTS3_HASH_STRING ){
  108531. return &fts3StrCompare;
  108532. }else{
  108533. assert( keyClass==FTS3_HASH_BINARY );
  108534. return &fts3BinCompare;
  108535. }
  108536. }
  108537. /* Link an element into the hash table
  108538. */
  108539. static void fts3HashInsertElement(
  108540. Fts3Hash *pH, /* The complete hash table */
  108541. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  108542. Fts3HashElem *pNew /* The element to be inserted */
  108543. ){
  108544. Fts3HashElem *pHead; /* First element already in pEntry */
  108545. pHead = pEntry->chain;
  108546. if( pHead ){
  108547. pNew->next = pHead;
  108548. pNew->prev = pHead->prev;
  108549. if( pHead->prev ){ pHead->prev->next = pNew; }
  108550. else { pH->first = pNew; }
  108551. pHead->prev = pNew;
  108552. }else{
  108553. pNew->next = pH->first;
  108554. if( pH->first ){ pH->first->prev = pNew; }
  108555. pNew->prev = 0;
  108556. pH->first = pNew;
  108557. }
  108558. pEntry->count++;
  108559. pEntry->chain = pNew;
  108560. }
  108561. /* Resize the hash table so that it cantains "new_size" buckets.
  108562. ** "new_size" must be a power of 2. The hash table might fail
  108563. ** to resize if sqliteMalloc() fails.
  108564. **
  108565. ** Return non-zero if a memory allocation error occurs.
  108566. */
  108567. static int fts3Rehash(Fts3Hash *pH, int new_size){
  108568. struct _fts3ht *new_ht; /* The new hash table */
  108569. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  108570. int (*xHash)(const void*,int); /* The hash function */
  108571. assert( (new_size & (new_size-1))==0 );
  108572. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  108573. if( new_ht==0 ) return 1;
  108574. fts3HashFree(pH->ht);
  108575. pH->ht = new_ht;
  108576. pH->htsize = new_size;
  108577. xHash = ftsHashFunction(pH->keyClass);
  108578. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  108579. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  108580. next_elem = elem->next;
  108581. fts3HashInsertElement(pH, &new_ht[h], elem);
  108582. }
  108583. return 0;
  108584. }
  108585. /* This function (for internal use only) locates an element in an
  108586. ** hash table that matches the given key. The hash for this key has
  108587. ** already been computed and is passed as the 4th parameter.
  108588. */
  108589. static Fts3HashElem *fts3FindElementByHash(
  108590. const Fts3Hash *pH, /* The pH to be searched */
  108591. const void *pKey, /* The key we are searching for */
  108592. int nKey,
  108593. int h /* The hash for this key. */
  108594. ){
  108595. Fts3HashElem *elem; /* Used to loop thru the element list */
  108596. int count; /* Number of elements left to test */
  108597. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  108598. if( pH->ht ){
  108599. struct _fts3ht *pEntry = &pH->ht[h];
  108600. elem = pEntry->chain;
  108601. count = pEntry->count;
  108602. xCompare = ftsCompareFunction(pH->keyClass);
  108603. while( count-- && elem ){
  108604. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  108605. return elem;
  108606. }
  108607. elem = elem->next;
  108608. }
  108609. }
  108610. return 0;
  108611. }
  108612. /* Remove a single entry from the hash table given a pointer to that
  108613. ** element and a hash on the element's key.
  108614. */
  108615. static void fts3RemoveElementByHash(
  108616. Fts3Hash *pH, /* The pH containing "elem" */
  108617. Fts3HashElem* elem, /* The element to be removed from the pH */
  108618. int h /* Hash value for the element */
  108619. ){
  108620. struct _fts3ht *pEntry;
  108621. if( elem->prev ){
  108622. elem->prev->next = elem->next;
  108623. }else{
  108624. pH->first = elem->next;
  108625. }
  108626. if( elem->next ){
  108627. elem->next->prev = elem->prev;
  108628. }
  108629. pEntry = &pH->ht[h];
  108630. if( pEntry->chain==elem ){
  108631. pEntry->chain = elem->next;
  108632. }
  108633. pEntry->count--;
  108634. if( pEntry->count<=0 ){
  108635. pEntry->chain = 0;
  108636. }
  108637. if( pH->copyKey && elem->pKey ){
  108638. fts3HashFree(elem->pKey);
  108639. }
  108640. fts3HashFree( elem );
  108641. pH->count--;
  108642. if( pH->count<=0 ){
  108643. assert( pH->first==0 );
  108644. assert( pH->count==0 );
  108645. fts3HashClear(pH);
  108646. }
  108647. }
  108648. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  108649. const Fts3Hash *pH,
  108650. const void *pKey,
  108651. int nKey
  108652. ){
  108653. int h; /* A hash on key */
  108654. int (*xHash)(const void*,int); /* The hash function */
  108655. if( pH==0 || pH->ht==0 ) return 0;
  108656. xHash = ftsHashFunction(pH->keyClass);
  108657. assert( xHash!=0 );
  108658. h = (*xHash)(pKey,nKey);
  108659. assert( (pH->htsize & (pH->htsize-1))==0 );
  108660. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  108661. }
  108662. /*
  108663. ** Attempt to locate an element of the hash table pH with a key
  108664. ** that matches pKey,nKey. Return the data for this element if it is
  108665. ** found, or NULL if there is no match.
  108666. */
  108667. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  108668. Fts3HashElem *pElem; /* The element that matches key (if any) */
  108669. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  108670. return pElem ? pElem->data : 0;
  108671. }
  108672. /* Insert an element into the hash table pH. The key is pKey,nKey
  108673. ** and the data is "data".
  108674. **
  108675. ** If no element exists with a matching key, then a new
  108676. ** element is created. A copy of the key is made if the copyKey
  108677. ** flag is set. NULL is returned.
  108678. **
  108679. ** If another element already exists with the same key, then the
  108680. ** new data replaces the old data and the old data is returned.
  108681. ** The key is not copied in this instance. If a malloc fails, then
  108682. ** the new data is returned and the hash table is unchanged.
  108683. **
  108684. ** If the "data" parameter to this function is NULL, then the
  108685. ** element corresponding to "key" is removed from the hash table.
  108686. */
  108687. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  108688. Fts3Hash *pH, /* The hash table to insert into */
  108689. const void *pKey, /* The key */
  108690. int nKey, /* Number of bytes in the key */
  108691. void *data /* The data */
  108692. ){
  108693. int hraw; /* Raw hash value of the key */
  108694. int h; /* the hash of the key modulo hash table size */
  108695. Fts3HashElem *elem; /* Used to loop thru the element list */
  108696. Fts3HashElem *new_elem; /* New element added to the pH */
  108697. int (*xHash)(const void*,int); /* The hash function */
  108698. assert( pH!=0 );
  108699. xHash = ftsHashFunction(pH->keyClass);
  108700. assert( xHash!=0 );
  108701. hraw = (*xHash)(pKey, nKey);
  108702. assert( (pH->htsize & (pH->htsize-1))==0 );
  108703. h = hraw & (pH->htsize-1);
  108704. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  108705. if( elem ){
  108706. void *old_data = elem->data;
  108707. if( data==0 ){
  108708. fts3RemoveElementByHash(pH,elem,h);
  108709. }else{
  108710. elem->data = data;
  108711. }
  108712. return old_data;
  108713. }
  108714. if( data==0 ) return 0;
  108715. if( (pH->htsize==0 && fts3Rehash(pH,8))
  108716. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  108717. ){
  108718. pH->count = 0;
  108719. return data;
  108720. }
  108721. assert( pH->htsize>0 );
  108722. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  108723. if( new_elem==0 ) return data;
  108724. if( pH->copyKey && pKey!=0 ){
  108725. new_elem->pKey = fts3HashMalloc( nKey );
  108726. if( new_elem->pKey==0 ){
  108727. fts3HashFree(new_elem);
  108728. return data;
  108729. }
  108730. memcpy((void*)new_elem->pKey, pKey, nKey);
  108731. }else{
  108732. new_elem->pKey = (void*)pKey;
  108733. }
  108734. new_elem->nKey = nKey;
  108735. pH->count++;
  108736. assert( pH->htsize>0 );
  108737. assert( (pH->htsize & (pH->htsize-1))==0 );
  108738. h = hraw & (pH->htsize-1);
  108739. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  108740. new_elem->data = data;
  108741. return 0;
  108742. }
  108743. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  108744. /************** End of fts3_hash.c *******************************************/
  108745. /************** Begin file fts3_porter.c *************************************/
  108746. /*
  108747. ** 2006 September 30
  108748. **
  108749. ** The author disclaims copyright to this source code. In place of
  108750. ** a legal notice, here is a blessing:
  108751. **
  108752. ** May you do good and not evil.
  108753. ** May you find forgiveness for yourself and forgive others.
  108754. ** May you share freely, never taking more than you give.
  108755. **
  108756. *************************************************************************
  108757. ** Implementation of the full-text-search tokenizer that implements
  108758. ** a Porter stemmer.
  108759. */
  108760. /*
  108761. ** The code in this file is only compiled if:
  108762. **
  108763. ** * The FTS3 module is being built as an extension
  108764. ** (in which case SQLITE_CORE is not defined), or
  108765. **
  108766. ** * The FTS3 module is being built into the core of
  108767. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  108768. */
  108769. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  108770. /*
  108771. ** Class derived from sqlite3_tokenizer
  108772. */
  108773. typedef struct porter_tokenizer {
  108774. sqlite3_tokenizer base; /* Base class */
  108775. } porter_tokenizer;
  108776. /*
  108777. ** Class derived from sqlit3_tokenizer_cursor
  108778. */
  108779. typedef struct porter_tokenizer_cursor {
  108780. sqlite3_tokenizer_cursor base;
  108781. const char *zInput; /* input we are tokenizing */
  108782. int nInput; /* size of the input */
  108783. int iOffset; /* current position in zInput */
  108784. int iToken; /* index of next token to be returned */
  108785. char *zToken; /* storage for current token */
  108786. int nAllocated; /* space allocated to zToken buffer */
  108787. } porter_tokenizer_cursor;
  108788. /*
  108789. ** Create a new tokenizer instance.
  108790. */
  108791. static int porterCreate(
  108792. int argc, const char * const *argv,
  108793. sqlite3_tokenizer **ppTokenizer
  108794. ){
  108795. porter_tokenizer *t;
  108796. UNUSED_PARAMETER(argc);
  108797. UNUSED_PARAMETER(argv);
  108798. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  108799. if( t==NULL ) return SQLITE_NOMEM;
  108800. memset(t, 0, sizeof(*t));
  108801. *ppTokenizer = &t->base;
  108802. return SQLITE_OK;
  108803. }
  108804. /*
  108805. ** Destroy a tokenizer
  108806. */
  108807. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  108808. sqlite3_free(pTokenizer);
  108809. return SQLITE_OK;
  108810. }
  108811. /*
  108812. ** Prepare to begin tokenizing a particular string. The input
  108813. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  108814. ** used to incrementally tokenize this string is returned in
  108815. ** *ppCursor.
  108816. */
  108817. static int porterOpen(
  108818. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  108819. const char *zInput, int nInput, /* String to be tokenized */
  108820. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  108821. ){
  108822. porter_tokenizer_cursor *c;
  108823. UNUSED_PARAMETER(pTokenizer);
  108824. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  108825. if( c==NULL ) return SQLITE_NOMEM;
  108826. c->zInput = zInput;
  108827. if( zInput==0 ){
  108828. c->nInput = 0;
  108829. }else if( nInput<0 ){
  108830. c->nInput = (int)strlen(zInput);
  108831. }else{
  108832. c->nInput = nInput;
  108833. }
  108834. c->iOffset = 0; /* start tokenizing at the beginning */
  108835. c->iToken = 0;
  108836. c->zToken = NULL; /* no space allocated, yet. */
  108837. c->nAllocated = 0;
  108838. *ppCursor = &c->base;
  108839. return SQLITE_OK;
  108840. }
  108841. /*
  108842. ** Close a tokenization cursor previously opened by a call to
  108843. ** porterOpen() above.
  108844. */
  108845. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  108846. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  108847. sqlite3_free(c->zToken);
  108848. sqlite3_free(c);
  108849. return SQLITE_OK;
  108850. }
  108851. /*
  108852. ** Vowel or consonant
  108853. */
  108854. static const char cType[] = {
  108855. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  108856. 1, 1, 1, 2, 1
  108857. };
  108858. /*
  108859. ** isConsonant() and isVowel() determine if their first character in
  108860. ** the string they point to is a consonant or a vowel, according
  108861. ** to Porter ruls.
  108862. **
  108863. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  108864. ** 'Y' is a consonant unless it follows another consonant,
  108865. ** in which case it is a vowel.
  108866. **
  108867. ** In these routine, the letters are in reverse order. So the 'y' rule
  108868. ** is that 'y' is a consonant unless it is followed by another
  108869. ** consonent.
  108870. */
  108871. static int isVowel(const char*);
  108872. static int isConsonant(const char *z){
  108873. int j;
  108874. char x = *z;
  108875. if( x==0 ) return 0;
  108876. assert( x>='a' && x<='z' );
  108877. j = cType[x-'a'];
  108878. if( j<2 ) return j;
  108879. return z[1]==0 || isVowel(z + 1);
  108880. }
  108881. static int isVowel(const char *z){
  108882. int j;
  108883. char x = *z;
  108884. if( x==0 ) return 0;
  108885. assert( x>='a' && x<='z' );
  108886. j = cType[x-'a'];
  108887. if( j<2 ) return 1-j;
  108888. return isConsonant(z + 1);
  108889. }
  108890. /*
  108891. ** Let any sequence of one or more vowels be represented by V and let
  108892. ** C be sequence of one or more consonants. Then every word can be
  108893. ** represented as:
  108894. **
  108895. ** [C] (VC){m} [V]
  108896. **
  108897. ** In prose: A word is an optional consonant followed by zero or
  108898. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  108899. ** number of vowel consonant pairs. This routine computes the value
  108900. ** of m for the first i bytes of a word.
  108901. **
  108902. ** Return true if the m-value for z is 1 or more. In other words,
  108903. ** return true if z contains at least one vowel that is followed
  108904. ** by a consonant.
  108905. **
  108906. ** In this routine z[] is in reverse order. So we are really looking
  108907. ** for an instance of of a consonant followed by a vowel.
  108908. */
  108909. static int m_gt_0(const char *z){
  108910. while( isVowel(z) ){ z++; }
  108911. if( *z==0 ) return 0;
  108912. while( isConsonant(z) ){ z++; }
  108913. return *z!=0;
  108914. }
  108915. /* Like mgt0 above except we are looking for a value of m which is
  108916. ** exactly 1
  108917. */
  108918. static int m_eq_1(const char *z){
  108919. while( isVowel(z) ){ z++; }
  108920. if( *z==0 ) return 0;
  108921. while( isConsonant(z) ){ z++; }
  108922. if( *z==0 ) return 0;
  108923. while( isVowel(z) ){ z++; }
  108924. if( *z==0 ) return 1;
  108925. while( isConsonant(z) ){ z++; }
  108926. return *z==0;
  108927. }
  108928. /* Like mgt0 above except we are looking for a value of m>1 instead
  108929. ** or m>0
  108930. */
  108931. static int m_gt_1(const char *z){
  108932. while( isVowel(z) ){ z++; }
  108933. if( *z==0 ) return 0;
  108934. while( isConsonant(z) ){ z++; }
  108935. if( *z==0 ) return 0;
  108936. while( isVowel(z) ){ z++; }
  108937. if( *z==0 ) return 0;
  108938. while( isConsonant(z) ){ z++; }
  108939. return *z!=0;
  108940. }
  108941. /*
  108942. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  108943. */
  108944. static int hasVowel(const char *z){
  108945. while( isConsonant(z) ){ z++; }
  108946. return *z!=0;
  108947. }
  108948. /*
  108949. ** Return TRUE if the word ends in a double consonant.
  108950. **
  108951. ** The text is reversed here. So we are really looking at
  108952. ** the first two characters of z[].
  108953. */
  108954. static int doubleConsonant(const char *z){
  108955. return isConsonant(z) && z[0]==z[1];
  108956. }
  108957. /*
  108958. ** Return TRUE if the word ends with three letters which
  108959. ** are consonant-vowel-consonent and where the final consonant
  108960. ** is not 'w', 'x', or 'y'.
  108961. **
  108962. ** The word is reversed here. So we are really checking the
  108963. ** first three letters and the first one cannot be in [wxy].
  108964. */
  108965. static int star_oh(const char *z){
  108966. return
  108967. isConsonant(z) &&
  108968. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  108969. isVowel(z+1) &&
  108970. isConsonant(z+2);
  108971. }
  108972. /*
  108973. ** If the word ends with zFrom and xCond() is true for the stem
  108974. ** of the word that preceeds the zFrom ending, then change the
  108975. ** ending to zTo.
  108976. **
  108977. ** The input word *pz and zFrom are both in reverse order. zTo
  108978. ** is in normal order.
  108979. **
  108980. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  108981. ** match. Not that TRUE is returned even if xCond() fails and
  108982. ** no substitution occurs.
  108983. */
  108984. static int stem(
  108985. char **pz, /* The word being stemmed (Reversed) */
  108986. const char *zFrom, /* If the ending matches this... (Reversed) */
  108987. const char *zTo, /* ... change the ending to this (not reversed) */
  108988. int (*xCond)(const char*) /* Condition that must be true */
  108989. ){
  108990. char *z = *pz;
  108991. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  108992. if( *zFrom!=0 ) return 0;
  108993. if( xCond && !xCond(z) ) return 1;
  108994. while( *zTo ){
  108995. *(--z) = *(zTo++);
  108996. }
  108997. *pz = z;
  108998. return 1;
  108999. }
  109000. /*
  109001. ** This is the fallback stemmer used when the porter stemmer is
  109002. ** inappropriate. The input word is copied into the output with
  109003. ** US-ASCII case folding. If the input word is too long (more
  109004. ** than 20 bytes if it contains no digits or more than 6 bytes if
  109005. ** it contains digits) then word is truncated to 20 or 6 bytes
  109006. ** by taking 10 or 3 bytes from the beginning and end.
  109007. */
  109008. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  109009. int i, mx, j;
  109010. int hasDigit = 0;
  109011. for(i=0; i<nIn; i++){
  109012. char c = zIn[i];
  109013. if( c>='A' && c<='Z' ){
  109014. zOut[i] = c - 'A' + 'a';
  109015. }else{
  109016. if( c>='0' && c<='9' ) hasDigit = 1;
  109017. zOut[i] = c;
  109018. }
  109019. }
  109020. mx = hasDigit ? 3 : 10;
  109021. if( nIn>mx*2 ){
  109022. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  109023. zOut[j] = zOut[i];
  109024. }
  109025. i = j;
  109026. }
  109027. zOut[i] = 0;
  109028. *pnOut = i;
  109029. }
  109030. /*
  109031. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  109032. ** zOut is at least big enough to hold nIn bytes. Write the actual
  109033. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  109034. **
  109035. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  109036. ** are converted to lower case. Upper-case UTF characters are
  109037. ** unchanged.
  109038. **
  109039. ** Words that are longer than about 20 bytes are stemmed by retaining
  109040. ** a few bytes from the beginning and the end of the word. If the
  109041. ** word contains digits, 3 bytes are taken from the beginning and
  109042. ** 3 bytes from the end. For long words without digits, 10 bytes
  109043. ** are taken from each end. US-ASCII case folding still applies.
  109044. **
  109045. ** If the input word contains not digits but does characters not
  109046. ** in [a-zA-Z] then no stemming is attempted and this routine just
  109047. ** copies the input into the input into the output with US-ASCII
  109048. ** case folding.
  109049. **
  109050. ** Stemming never increases the length of the word. So there is
  109051. ** no chance of overflowing the zOut buffer.
  109052. */
  109053. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  109054. int i, j;
  109055. char zReverse[28];
  109056. char *z, *z2;
  109057. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  109058. /* The word is too big or too small for the porter stemmer.
  109059. ** Fallback to the copy stemmer */
  109060. copy_stemmer(zIn, nIn, zOut, pnOut);
  109061. return;
  109062. }
  109063. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  109064. char c = zIn[i];
  109065. if( c>='A' && c<='Z' ){
  109066. zReverse[j] = c + 'a' - 'A';
  109067. }else if( c>='a' && c<='z' ){
  109068. zReverse[j] = c;
  109069. }else{
  109070. /* The use of a character not in [a-zA-Z] means that we fallback
  109071. ** to the copy stemmer */
  109072. copy_stemmer(zIn, nIn, zOut, pnOut);
  109073. return;
  109074. }
  109075. }
  109076. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  109077. z = &zReverse[j+1];
  109078. /* Step 1a */
  109079. if( z[0]=='s' ){
  109080. if(
  109081. !stem(&z, "sess", "ss", 0) &&
  109082. !stem(&z, "sei", "i", 0) &&
  109083. !stem(&z, "ss", "ss", 0)
  109084. ){
  109085. z++;
  109086. }
  109087. }
  109088. /* Step 1b */
  109089. z2 = z;
  109090. if( stem(&z, "dee", "ee", m_gt_0) ){
  109091. /* Do nothing. The work was all in the test */
  109092. }else if(
  109093. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  109094. && z!=z2
  109095. ){
  109096. if( stem(&z, "ta", "ate", 0) ||
  109097. stem(&z, "lb", "ble", 0) ||
  109098. stem(&z, "zi", "ize", 0) ){
  109099. /* Do nothing. The work was all in the test */
  109100. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  109101. z++;
  109102. }else if( m_eq_1(z) && star_oh(z) ){
  109103. *(--z) = 'e';
  109104. }
  109105. }
  109106. /* Step 1c */
  109107. if( z[0]=='y' && hasVowel(z+1) ){
  109108. z[0] = 'i';
  109109. }
  109110. /* Step 2 */
  109111. switch( z[1] ){
  109112. case 'a':
  109113. stem(&z, "lanoita", "ate", m_gt_0) ||
  109114. stem(&z, "lanoit", "tion", m_gt_0);
  109115. break;
  109116. case 'c':
  109117. stem(&z, "icne", "ence", m_gt_0) ||
  109118. stem(&z, "icna", "ance", m_gt_0);
  109119. break;
  109120. case 'e':
  109121. stem(&z, "rezi", "ize", m_gt_0);
  109122. break;
  109123. case 'g':
  109124. stem(&z, "igol", "log", m_gt_0);
  109125. break;
  109126. case 'l':
  109127. stem(&z, "ilb", "ble", m_gt_0) ||
  109128. stem(&z, "illa", "al", m_gt_0) ||
  109129. stem(&z, "iltne", "ent", m_gt_0) ||
  109130. stem(&z, "ile", "e", m_gt_0) ||
  109131. stem(&z, "ilsuo", "ous", m_gt_0);
  109132. break;
  109133. case 'o':
  109134. stem(&z, "noitazi", "ize", m_gt_0) ||
  109135. stem(&z, "noita", "ate", m_gt_0) ||
  109136. stem(&z, "rota", "ate", m_gt_0);
  109137. break;
  109138. case 's':
  109139. stem(&z, "msila", "al", m_gt_0) ||
  109140. stem(&z, "ssenevi", "ive", m_gt_0) ||
  109141. stem(&z, "ssenluf", "ful", m_gt_0) ||
  109142. stem(&z, "ssensuo", "ous", m_gt_0);
  109143. break;
  109144. case 't':
  109145. stem(&z, "itila", "al", m_gt_0) ||
  109146. stem(&z, "itivi", "ive", m_gt_0) ||
  109147. stem(&z, "itilib", "ble", m_gt_0);
  109148. break;
  109149. }
  109150. /* Step 3 */
  109151. switch( z[0] ){
  109152. case 'e':
  109153. stem(&z, "etaci", "ic", m_gt_0) ||
  109154. stem(&z, "evita", "", m_gt_0) ||
  109155. stem(&z, "ezila", "al", m_gt_0);
  109156. break;
  109157. case 'i':
  109158. stem(&z, "itici", "ic", m_gt_0);
  109159. break;
  109160. case 'l':
  109161. stem(&z, "laci", "ic", m_gt_0) ||
  109162. stem(&z, "luf", "", m_gt_0);
  109163. break;
  109164. case 's':
  109165. stem(&z, "ssen", "", m_gt_0);
  109166. break;
  109167. }
  109168. /* Step 4 */
  109169. switch( z[1] ){
  109170. case 'a':
  109171. if( z[0]=='l' && m_gt_1(z+2) ){
  109172. z += 2;
  109173. }
  109174. break;
  109175. case 'c':
  109176. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  109177. z += 4;
  109178. }
  109179. break;
  109180. case 'e':
  109181. if( z[0]=='r' && m_gt_1(z+2) ){
  109182. z += 2;
  109183. }
  109184. break;
  109185. case 'i':
  109186. if( z[0]=='c' && m_gt_1(z+2) ){
  109187. z += 2;
  109188. }
  109189. break;
  109190. case 'l':
  109191. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  109192. z += 4;
  109193. }
  109194. break;
  109195. case 'n':
  109196. if( z[0]=='t' ){
  109197. if( z[2]=='a' ){
  109198. if( m_gt_1(z+3) ){
  109199. z += 3;
  109200. }
  109201. }else if( z[2]=='e' ){
  109202. stem(&z, "tneme", "", m_gt_1) ||
  109203. stem(&z, "tnem", "", m_gt_1) ||
  109204. stem(&z, "tne", "", m_gt_1);
  109205. }
  109206. }
  109207. break;
  109208. case 'o':
  109209. if( z[0]=='u' ){
  109210. if( m_gt_1(z+2) ){
  109211. z += 2;
  109212. }
  109213. }else if( z[3]=='s' || z[3]=='t' ){
  109214. stem(&z, "noi", "", m_gt_1);
  109215. }
  109216. break;
  109217. case 's':
  109218. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  109219. z += 3;
  109220. }
  109221. break;
  109222. case 't':
  109223. stem(&z, "eta", "", m_gt_1) ||
  109224. stem(&z, "iti", "", m_gt_1);
  109225. break;
  109226. case 'u':
  109227. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  109228. z += 3;
  109229. }
  109230. break;
  109231. case 'v':
  109232. case 'z':
  109233. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  109234. z += 3;
  109235. }
  109236. break;
  109237. }
  109238. /* Step 5a */
  109239. if( z[0]=='e' ){
  109240. if( m_gt_1(z+1) ){
  109241. z++;
  109242. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  109243. z++;
  109244. }
  109245. }
  109246. /* Step 5b */
  109247. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  109248. z++;
  109249. }
  109250. /* z[] is now the stemmed word in reverse order. Flip it back
  109251. ** around into forward order and return.
  109252. */
  109253. *pnOut = i = (int)strlen(z);
  109254. zOut[i] = 0;
  109255. while( *z ){
  109256. zOut[--i] = *(z++);
  109257. }
  109258. }
  109259. /*
  109260. ** Characters that can be part of a token. We assume any character
  109261. ** whose value is greater than 0x80 (any UTF character) can be
  109262. ** part of a token. In other words, delimiters all must have
  109263. ** values of 0x7f or lower.
  109264. */
  109265. static const char porterIdChar[] = {
  109266. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  109267. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  109268. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  109269. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  109270. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  109271. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  109272. };
  109273. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  109274. /*
  109275. ** Extract the next token from a tokenization cursor. The cursor must
  109276. ** have been opened by a prior call to porterOpen().
  109277. */
  109278. static int porterNext(
  109279. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  109280. const char **pzToken, /* OUT: *pzToken is the token text */
  109281. int *pnBytes, /* OUT: Number of bytes in token */
  109282. int *piStartOffset, /* OUT: Starting offset of token */
  109283. int *piEndOffset, /* OUT: Ending offset of token */
  109284. int *piPosition /* OUT: Position integer of token */
  109285. ){
  109286. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  109287. const char *z = c->zInput;
  109288. while( c->iOffset<c->nInput ){
  109289. int iStartOffset, ch;
  109290. /* Scan past delimiter characters */
  109291. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  109292. c->iOffset++;
  109293. }
  109294. /* Count non-delimiter characters. */
  109295. iStartOffset = c->iOffset;
  109296. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  109297. c->iOffset++;
  109298. }
  109299. if( c->iOffset>iStartOffset ){
  109300. int n = c->iOffset-iStartOffset;
  109301. if( n>c->nAllocated ){
  109302. char *pNew;
  109303. c->nAllocated = n+20;
  109304. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  109305. if( !pNew ) return SQLITE_NOMEM;
  109306. c->zToken = pNew;
  109307. }
  109308. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  109309. *pzToken = c->zToken;
  109310. *piStartOffset = iStartOffset;
  109311. *piEndOffset = c->iOffset;
  109312. *piPosition = c->iToken++;
  109313. return SQLITE_OK;
  109314. }
  109315. }
  109316. return SQLITE_DONE;
  109317. }
  109318. /*
  109319. ** The set of routines that implement the porter-stemmer tokenizer
  109320. */
  109321. static const sqlite3_tokenizer_module porterTokenizerModule = {
  109322. 0,
  109323. porterCreate,
  109324. porterDestroy,
  109325. porterOpen,
  109326. porterClose,
  109327. porterNext,
  109328. };
  109329. /*
  109330. ** Allocate a new porter tokenizer. Return a pointer to the new
  109331. ** tokenizer in *ppModule
  109332. */
  109333. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  109334. sqlite3_tokenizer_module const**ppModule
  109335. ){
  109336. *ppModule = &porterTokenizerModule;
  109337. }
  109338. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  109339. /************** End of fts3_porter.c *****************************************/
  109340. /************** Begin file fts3_tokenizer.c **********************************/
  109341. /*
  109342. ** 2007 June 22
  109343. **
  109344. ** The author disclaims copyright to this source code. In place of
  109345. ** a legal notice, here is a blessing:
  109346. **
  109347. ** May you do good and not evil.
  109348. ** May you find forgiveness for yourself and forgive others.
  109349. ** May you share freely, never taking more than you give.
  109350. **
  109351. ******************************************************************************
  109352. **
  109353. ** This is part of an SQLite module implementing full-text search.
  109354. ** This particular file implements the generic tokenizer interface.
  109355. */
  109356. /*
  109357. ** The code in this file is only compiled if:
  109358. **
  109359. ** * The FTS3 module is being built as an extension
  109360. ** (in which case SQLITE_CORE is not defined), or
  109361. **
  109362. ** * The FTS3 module is being built into the core of
  109363. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  109364. */
  109365. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  109366. #ifndef SQLITE_CORE
  109367. SQLITE_EXTENSION_INIT1
  109368. #endif
  109369. /*
  109370. ** Implementation of the SQL scalar function for accessing the underlying
  109371. ** hash table. This function may be called as follows:
  109372. **
  109373. ** SELECT <function-name>(<key-name>);
  109374. ** SELECT <function-name>(<key-name>, <pointer>);
  109375. **
  109376. ** where <function-name> is the name passed as the second argument
  109377. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  109378. **
  109379. ** If the <pointer> argument is specified, it must be a blob value
  109380. ** containing a pointer to be stored as the hash data corresponding
  109381. ** to the string <key-name>. If <pointer> is not specified, then
  109382. ** the string <key-name> must already exist in the has table. Otherwise,
  109383. ** an error is returned.
  109384. **
  109385. ** Whether or not the <pointer> argument is specified, the value returned
  109386. ** is a blob containing the pointer stored as the hash data corresponding
  109387. ** to string <key-name> (after the hash-table is updated, if applicable).
  109388. */
  109389. static void scalarFunc(
  109390. sqlite3_context *context,
  109391. int argc,
  109392. sqlite3_value **argv
  109393. ){
  109394. Fts3Hash *pHash;
  109395. void *pPtr = 0;
  109396. const unsigned char *zName;
  109397. int nName;
  109398. assert( argc==1 || argc==2 );
  109399. pHash = (Fts3Hash *)sqlite3_user_data(context);
  109400. zName = sqlite3_value_text(argv[0]);
  109401. nName = sqlite3_value_bytes(argv[0])+1;
  109402. if( argc==2 ){
  109403. void *pOld;
  109404. int n = sqlite3_value_bytes(argv[1]);
  109405. if( n!=sizeof(pPtr) ){
  109406. sqlite3_result_error(context, "argument type mismatch", -1);
  109407. return;
  109408. }
  109409. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  109410. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  109411. if( pOld==pPtr ){
  109412. sqlite3_result_error(context, "out of memory", -1);
  109413. return;
  109414. }
  109415. }else{
  109416. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  109417. if( !pPtr ){
  109418. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  109419. sqlite3_result_error(context, zErr, -1);
  109420. sqlite3_free(zErr);
  109421. return;
  109422. }
  109423. }
  109424. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  109425. }
  109426. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  109427. static const char isFtsIdChar[] = {
  109428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  109429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  109430. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  109431. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  109432. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  109433. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  109434. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  109435. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  109436. };
  109437. return (c&0x80 || isFtsIdChar[(int)(c)]);
  109438. }
  109439. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  109440. const char *z1;
  109441. const char *z2 = 0;
  109442. /* Find the start of the next token. */
  109443. z1 = zStr;
  109444. while( z2==0 ){
  109445. char c = *z1;
  109446. switch( c ){
  109447. case '\0': return 0; /* No more tokens here */
  109448. case '\'':
  109449. case '"':
  109450. case '`': {
  109451. z2 = z1;
  109452. while( *++z2 && (*z2!=c || *++z2==c) );
  109453. break;
  109454. }
  109455. case '[':
  109456. z2 = &z1[1];
  109457. while( *z2 && z2[0]!=']' ) z2++;
  109458. if( *z2 ) z2++;
  109459. break;
  109460. default:
  109461. if( sqlite3Fts3IsIdChar(*z1) ){
  109462. z2 = &z1[1];
  109463. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  109464. }else{
  109465. z1++;
  109466. }
  109467. }
  109468. }
  109469. *pn = (int)(z2-z1);
  109470. return z1;
  109471. }
  109472. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  109473. Fts3Hash *pHash, /* Tokenizer hash table */
  109474. const char *zArg, /* Tokenizer name */
  109475. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  109476. char **pzErr /* OUT: Set to malloced error message */
  109477. ){
  109478. int rc;
  109479. char *z = (char *)zArg;
  109480. int n;
  109481. char *zCopy;
  109482. char *zEnd; /* Pointer to nul-term of zCopy */
  109483. sqlite3_tokenizer_module *m;
  109484. zCopy = sqlite3_mprintf("%s", zArg);
  109485. if( !zCopy ) return SQLITE_NOMEM;
  109486. zEnd = &zCopy[strlen(zCopy)];
  109487. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  109488. z[n] = '\0';
  109489. sqlite3Fts3Dequote(z);
  109490. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  109491. if( !m ){
  109492. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  109493. rc = SQLITE_ERROR;
  109494. }else{
  109495. char const **aArg = 0;
  109496. int iArg = 0;
  109497. z = &z[n+1];
  109498. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  109499. int nNew = sizeof(char *)*(iArg+1);
  109500. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  109501. if( !aNew ){
  109502. sqlite3_free(zCopy);
  109503. sqlite3_free((void *)aArg);
  109504. return SQLITE_NOMEM;
  109505. }
  109506. aArg = aNew;
  109507. aArg[iArg++] = z;
  109508. z[n] = '\0';
  109509. sqlite3Fts3Dequote(z);
  109510. z = &z[n+1];
  109511. }
  109512. rc = m->xCreate(iArg, aArg, ppTok);
  109513. assert( rc!=SQLITE_OK || *ppTok );
  109514. if( rc!=SQLITE_OK ){
  109515. *pzErr = sqlite3_mprintf("unknown tokenizer");
  109516. }else{
  109517. (*ppTok)->pModule = m;
  109518. }
  109519. sqlite3_free((void *)aArg);
  109520. }
  109521. sqlite3_free(zCopy);
  109522. return rc;
  109523. }
  109524. #ifdef SQLITE_TEST
  109525. /*
  109526. ** Implementation of a special SQL scalar function for testing tokenizers
  109527. ** designed to be used in concert with the Tcl testing framework. This
  109528. ** function must be called with two arguments:
  109529. **
  109530. ** SELECT <function-name>(<key-name>, <input-string>);
  109531. ** SELECT <function-name>(<key-name>, <pointer>);
  109532. **
  109533. ** where <function-name> is the name passed as the second argument
  109534. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  109535. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  109536. **
  109537. ** The return value is a string that may be interpreted as a Tcl
  109538. ** list. For each token in the <input-string>, three elements are
  109539. ** added to the returned list. The first is the token position, the
  109540. ** second is the token text (folded, stemmed, etc.) and the third is the
  109541. ** substring of <input-string> associated with the token. For example,
  109542. ** using the built-in "simple" tokenizer:
  109543. **
  109544. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  109545. **
  109546. ** will return the string:
  109547. **
  109548. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  109549. **
  109550. */
  109551. static void testFunc(
  109552. sqlite3_context *context,
  109553. int argc,
  109554. sqlite3_value **argv
  109555. ){
  109556. Fts3Hash *pHash;
  109557. sqlite3_tokenizer_module *p;
  109558. sqlite3_tokenizer *pTokenizer = 0;
  109559. sqlite3_tokenizer_cursor *pCsr = 0;
  109560. const char *zErr = 0;
  109561. const char *zName;
  109562. int nName;
  109563. const char *zInput;
  109564. int nInput;
  109565. const char *zArg = 0;
  109566. const char *zToken;
  109567. int nToken;
  109568. int iStart;
  109569. int iEnd;
  109570. int iPos;
  109571. Tcl_Obj *pRet;
  109572. assert( argc==2 || argc==3 );
  109573. nName = sqlite3_value_bytes(argv[0]);
  109574. zName = (const char *)sqlite3_value_text(argv[0]);
  109575. nInput = sqlite3_value_bytes(argv[argc-1]);
  109576. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  109577. if( argc==3 ){
  109578. zArg = (const char *)sqlite3_value_text(argv[1]);
  109579. }
  109580. pHash = (Fts3Hash *)sqlite3_user_data(context);
  109581. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  109582. if( !p ){
  109583. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  109584. sqlite3_result_error(context, zErr, -1);
  109585. sqlite3_free(zErr);
  109586. return;
  109587. }
  109588. pRet = Tcl_NewObj();
  109589. Tcl_IncrRefCount(pRet);
  109590. if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
  109591. zErr = "error in xCreate()";
  109592. goto finish;
  109593. }
  109594. pTokenizer->pModule = p;
  109595. if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
  109596. zErr = "error in xOpen()";
  109597. goto finish;
  109598. }
  109599. pCsr->pTokenizer = pTokenizer;
  109600. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  109601. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  109602. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  109603. zToken = &zInput[iStart];
  109604. nToken = iEnd-iStart;
  109605. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  109606. }
  109607. if( SQLITE_OK!=p->xClose(pCsr) ){
  109608. zErr = "error in xClose()";
  109609. goto finish;
  109610. }
  109611. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  109612. zErr = "error in xDestroy()";
  109613. goto finish;
  109614. }
  109615. finish:
  109616. if( zErr ){
  109617. sqlite3_result_error(context, zErr, -1);
  109618. }else{
  109619. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  109620. }
  109621. Tcl_DecrRefCount(pRet);
  109622. }
  109623. static
  109624. int registerTokenizer(
  109625. sqlite3 *db,
  109626. char *zName,
  109627. const sqlite3_tokenizer_module *p
  109628. ){
  109629. int rc;
  109630. sqlite3_stmt *pStmt;
  109631. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  109632. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  109633. if( rc!=SQLITE_OK ){
  109634. return rc;
  109635. }
  109636. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  109637. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  109638. sqlite3_step(pStmt);
  109639. return sqlite3_finalize(pStmt);
  109640. }
  109641. static
  109642. int queryTokenizer(
  109643. sqlite3 *db,
  109644. char *zName,
  109645. const sqlite3_tokenizer_module **pp
  109646. ){
  109647. int rc;
  109648. sqlite3_stmt *pStmt;
  109649. const char zSql[] = "SELECT fts3_tokenizer(?)";
  109650. *pp = 0;
  109651. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  109652. if( rc!=SQLITE_OK ){
  109653. return rc;
  109654. }
  109655. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  109656. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  109657. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  109658. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  109659. }
  109660. }
  109661. return sqlite3_finalize(pStmt);
  109662. }
  109663. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  109664. /*
  109665. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  109666. ** This function is used for testing only, it is not included in the
  109667. ** build unless SQLITE_TEST is defined.
  109668. **
  109669. ** The purpose of this is to test that the fts3_tokenizer() function
  109670. ** can be used as designed by the C-code in the queryTokenizer and
  109671. ** registerTokenizer() functions above. These two functions are repeated
  109672. ** in the README.tokenizer file as an example, so it is important to
  109673. ** test them.
  109674. **
  109675. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  109676. ** function with no arguments. An assert() will fail if a problem is
  109677. ** detected. i.e.:
  109678. **
  109679. ** SELECT fts3_tokenizer_internal_test();
  109680. **
  109681. */
  109682. static void intTestFunc(
  109683. sqlite3_context *context,
  109684. int argc,
  109685. sqlite3_value **argv
  109686. ){
  109687. int rc;
  109688. const sqlite3_tokenizer_module *p1;
  109689. const sqlite3_tokenizer_module *p2;
  109690. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  109691. UNUSED_PARAMETER(argc);
  109692. UNUSED_PARAMETER(argv);
  109693. /* Test the query function */
  109694. sqlite3Fts3SimpleTokenizerModule(&p1);
  109695. rc = queryTokenizer(db, "simple", &p2);
  109696. assert( rc==SQLITE_OK );
  109697. assert( p1==p2 );
  109698. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  109699. assert( rc==SQLITE_ERROR );
  109700. assert( p2==0 );
  109701. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  109702. /* Test the storage function */
  109703. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  109704. assert( rc==SQLITE_OK );
  109705. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  109706. assert( rc==SQLITE_OK );
  109707. assert( p2==p1 );
  109708. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  109709. }
  109710. #endif
  109711. /*
  109712. ** Set up SQL objects in database db used to access the contents of
  109713. ** the hash table pointed to by argument pHash. The hash table must
  109714. ** been initialised to use string keys, and to take a private copy
  109715. ** of the key when a value is inserted. i.e. by a call similar to:
  109716. **
  109717. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  109718. **
  109719. ** This function adds a scalar function (see header comment above
  109720. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  109721. ** defined at compilation time, a temporary virtual table (see header
  109722. ** comment above struct HashTableVtab) to the database schema. Both
  109723. ** provide read/write access to the contents of *pHash.
  109724. **
  109725. ** The third argument to this function, zName, is used as the name
  109726. ** of both the scalar and, if created, the virtual table.
  109727. */
  109728. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  109729. sqlite3 *db,
  109730. Fts3Hash *pHash,
  109731. const char *zName
  109732. ){
  109733. int rc = SQLITE_OK;
  109734. void *p = (void *)pHash;
  109735. const int any = SQLITE_ANY;
  109736. #ifdef SQLITE_TEST
  109737. char *zTest = 0;
  109738. char *zTest2 = 0;
  109739. void *pdb = (void *)db;
  109740. zTest = sqlite3_mprintf("%s_test", zName);
  109741. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  109742. if( !zTest || !zTest2 ){
  109743. rc = SQLITE_NOMEM;
  109744. }
  109745. #endif
  109746. if( SQLITE_OK==rc ){
  109747. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  109748. }
  109749. if( SQLITE_OK==rc ){
  109750. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  109751. }
  109752. #ifdef SQLITE_TEST
  109753. if( SQLITE_OK==rc ){
  109754. rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
  109755. }
  109756. if( SQLITE_OK==rc ){
  109757. rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
  109758. }
  109759. if( SQLITE_OK==rc ){
  109760. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  109761. }
  109762. #endif
  109763. #ifdef SQLITE_TEST
  109764. sqlite3_free(zTest);
  109765. sqlite3_free(zTest2);
  109766. #endif
  109767. return rc;
  109768. }
  109769. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  109770. /************** End of fts3_tokenizer.c **************************************/
  109771. /************** Begin file fts3_tokenizer1.c *********************************/
  109772. /*
  109773. ** 2006 Oct 10
  109774. **
  109775. ** The author disclaims copyright to this source code. In place of
  109776. ** a legal notice, here is a blessing:
  109777. **
  109778. ** May you do good and not evil.
  109779. ** May you find forgiveness for yourself and forgive others.
  109780. ** May you share freely, never taking more than you give.
  109781. **
  109782. ******************************************************************************
  109783. **
  109784. ** Implementation of the "simple" full-text-search tokenizer.
  109785. */
  109786. /*
  109787. ** The code in this file is only compiled if:
  109788. **
  109789. ** * The FTS3 module is being built as an extension
  109790. ** (in which case SQLITE_CORE is not defined), or
  109791. **
  109792. ** * The FTS3 module is being built into the core of
  109793. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  109794. */
  109795. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  109796. typedef struct simple_tokenizer {
  109797. sqlite3_tokenizer base;
  109798. char delim[128]; /* flag ASCII delimiters */
  109799. } simple_tokenizer;
  109800. typedef struct simple_tokenizer_cursor {
  109801. sqlite3_tokenizer_cursor base;
  109802. const char *pInput; /* input we are tokenizing */
  109803. int nBytes; /* size of the input */
  109804. int iOffset; /* current position in pInput */
  109805. int iToken; /* index of next token to be returned */
  109806. char *pToken; /* storage for current token */
  109807. int nTokenAllocated; /* space allocated to zToken buffer */
  109808. } simple_tokenizer_cursor;
  109809. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  109810. return c<0x80 && t->delim[c];
  109811. }
  109812. static int fts3_isalnum(int x){
  109813. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  109814. }
  109815. /*
  109816. ** Create a new tokenizer instance.
  109817. */
  109818. static int simpleCreate(
  109819. int argc, const char * const *argv,
  109820. sqlite3_tokenizer **ppTokenizer
  109821. ){
  109822. simple_tokenizer *t;
  109823. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  109824. if( t==NULL ) return SQLITE_NOMEM;
  109825. memset(t, 0, sizeof(*t));
  109826. /* TODO(shess) Delimiters need to remain the same from run to run,
  109827. ** else we need to reindex. One solution would be a meta-table to
  109828. ** track such information in the database, then we'd only want this
  109829. ** information on the initial create.
  109830. */
  109831. if( argc>1 ){
  109832. int i, n = (int)strlen(argv[1]);
  109833. for(i=0; i<n; i++){
  109834. unsigned char ch = argv[1][i];
  109835. /* We explicitly don't support UTF-8 delimiters for now. */
  109836. if( ch>=0x80 ){
  109837. sqlite3_free(t);
  109838. return SQLITE_ERROR;
  109839. }
  109840. t->delim[ch] = 1;
  109841. }
  109842. } else {
  109843. /* Mark non-alphanumeric ASCII characters as delimiters */
  109844. int i;
  109845. for(i=1; i<0x80; i++){
  109846. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  109847. }
  109848. }
  109849. *ppTokenizer = &t->base;
  109850. return SQLITE_OK;
  109851. }
  109852. /*
  109853. ** Destroy a tokenizer
  109854. */
  109855. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  109856. sqlite3_free(pTokenizer);
  109857. return SQLITE_OK;
  109858. }
  109859. /*
  109860. ** Prepare to begin tokenizing a particular string. The input
  109861. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  109862. ** used to incrementally tokenize this string is returned in
  109863. ** *ppCursor.
  109864. */
  109865. static int simpleOpen(
  109866. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  109867. const char *pInput, int nBytes, /* String to be tokenized */
  109868. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  109869. ){
  109870. simple_tokenizer_cursor *c;
  109871. UNUSED_PARAMETER(pTokenizer);
  109872. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  109873. if( c==NULL ) return SQLITE_NOMEM;
  109874. c->pInput = pInput;
  109875. if( pInput==0 ){
  109876. c->nBytes = 0;
  109877. }else if( nBytes<0 ){
  109878. c->nBytes = (int)strlen(pInput);
  109879. }else{
  109880. c->nBytes = nBytes;
  109881. }
  109882. c->iOffset = 0; /* start tokenizing at the beginning */
  109883. c->iToken = 0;
  109884. c->pToken = NULL; /* no space allocated, yet. */
  109885. c->nTokenAllocated = 0;
  109886. *ppCursor = &c->base;
  109887. return SQLITE_OK;
  109888. }
  109889. /*
  109890. ** Close a tokenization cursor previously opened by a call to
  109891. ** simpleOpen() above.
  109892. */
  109893. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  109894. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  109895. sqlite3_free(c->pToken);
  109896. sqlite3_free(c);
  109897. return SQLITE_OK;
  109898. }
  109899. /*
  109900. ** Extract the next token from a tokenization cursor. The cursor must
  109901. ** have been opened by a prior call to simpleOpen().
  109902. */
  109903. static int simpleNext(
  109904. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  109905. const char **ppToken, /* OUT: *ppToken is the token text */
  109906. int *pnBytes, /* OUT: Number of bytes in token */
  109907. int *piStartOffset, /* OUT: Starting offset of token */
  109908. int *piEndOffset, /* OUT: Ending offset of token */
  109909. int *piPosition /* OUT: Position integer of token */
  109910. ){
  109911. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  109912. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  109913. unsigned char *p = (unsigned char *)c->pInput;
  109914. while( c->iOffset<c->nBytes ){
  109915. int iStartOffset;
  109916. /* Scan past delimiter characters */
  109917. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  109918. c->iOffset++;
  109919. }
  109920. /* Count non-delimiter characters. */
  109921. iStartOffset = c->iOffset;
  109922. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  109923. c->iOffset++;
  109924. }
  109925. if( c->iOffset>iStartOffset ){
  109926. int i, n = c->iOffset-iStartOffset;
  109927. if( n>c->nTokenAllocated ){
  109928. char *pNew;
  109929. c->nTokenAllocated = n+20;
  109930. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  109931. if( !pNew ) return SQLITE_NOMEM;
  109932. c->pToken = pNew;
  109933. }
  109934. for(i=0; i<n; i++){
  109935. /* TODO(shess) This needs expansion to handle UTF-8
  109936. ** case-insensitivity.
  109937. */
  109938. unsigned char ch = p[iStartOffset+i];
  109939. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  109940. }
  109941. *ppToken = c->pToken;
  109942. *pnBytes = n;
  109943. *piStartOffset = iStartOffset;
  109944. *piEndOffset = c->iOffset;
  109945. *piPosition = c->iToken++;
  109946. return SQLITE_OK;
  109947. }
  109948. }
  109949. return SQLITE_DONE;
  109950. }
  109951. /*
  109952. ** The set of routines that implement the simple tokenizer
  109953. */
  109954. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  109955. 0,
  109956. simpleCreate,
  109957. simpleDestroy,
  109958. simpleOpen,
  109959. simpleClose,
  109960. simpleNext,
  109961. };
  109962. /*
  109963. ** Allocate a new simple tokenizer. Return a pointer to the new
  109964. ** tokenizer in *ppModule
  109965. */
  109966. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  109967. sqlite3_tokenizer_module const**ppModule
  109968. ){
  109969. *ppModule = &simpleTokenizerModule;
  109970. }
  109971. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  109972. /************** End of fts3_tokenizer1.c *************************************/
  109973. /************** Begin file fts3_write.c **************************************/
  109974. /*
  109975. ** 2009 Oct 23
  109976. **
  109977. ** The author disclaims copyright to this source code. In place of
  109978. ** a legal notice, here is a blessing:
  109979. **
  109980. ** May you do good and not evil.
  109981. ** May you find forgiveness for yourself and forgive others.
  109982. ** May you share freely, never taking more than you give.
  109983. **
  109984. ******************************************************************************
  109985. **
  109986. ** This file is part of the SQLite FTS3 extension module. Specifically,
  109987. ** this file contains code to insert, update and delete rows from FTS3
  109988. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  109989. ** of the sub-routines used to merge segments are also used by the query
  109990. ** code in fts3.c.
  109991. */
  109992. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  109993. /*
  109994. ** When full-text index nodes are loaded from disk, the buffer that they
  109995. ** are loaded into has the following number of bytes of padding at the end
  109996. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  109997. ** of 920 bytes is allocated for it.
  109998. **
  109999. ** This means that if we have a pointer into a buffer containing node data,
  110000. ** it is always safe to read up to two varints from it without risking an
  110001. ** overread, even if the node data is corrupted.
  110002. */
  110003. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  110004. typedef struct PendingList PendingList;
  110005. typedef struct SegmentNode SegmentNode;
  110006. typedef struct SegmentWriter SegmentWriter;
  110007. /*
  110008. ** Data structure used while accumulating terms in the pending-terms hash
  110009. ** table. The hash table entry maps from term (a string) to a malloc'd
  110010. ** instance of this structure.
  110011. */
  110012. struct PendingList {
  110013. int nData;
  110014. char *aData;
  110015. int nSpace;
  110016. sqlite3_int64 iLastDocid;
  110017. sqlite3_int64 iLastCol;
  110018. sqlite3_int64 iLastPos;
  110019. };
  110020. /*
  110021. ** Each cursor has a (possibly empty) linked list of the following objects.
  110022. */
  110023. struct Fts3DeferredToken {
  110024. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  110025. int iCol; /* Column token must occur in */
  110026. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  110027. PendingList *pList; /* Doclist is assembled here */
  110028. };
  110029. /*
  110030. ** An instance of this structure is used to iterate through the terms on
  110031. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  110032. ** this structure are only manipulated by code in this file, opaque handles
  110033. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  110034. ** terms when querying the full-text index. See functions:
  110035. **
  110036. ** sqlite3Fts3SegReaderNew()
  110037. ** sqlite3Fts3SegReaderFree()
  110038. ** sqlite3Fts3SegReaderCost()
  110039. ** sqlite3Fts3SegReaderIterate()
  110040. **
  110041. ** Methods used to manipulate Fts3SegReader structures:
  110042. **
  110043. ** fts3SegReaderNext()
  110044. ** fts3SegReaderFirstDocid()
  110045. ** fts3SegReaderNextDocid()
  110046. */
  110047. struct Fts3SegReader {
  110048. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  110049. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  110050. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  110051. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  110052. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  110053. char *aNode; /* Pointer to node data (or NULL) */
  110054. int nNode; /* Size of buffer at aNode (or 0) */
  110055. Fts3HashElem **ppNextElem;
  110056. /* Variables set by fts3SegReaderNext(). These may be read directly
  110057. ** by the caller. They are valid from the time SegmentReaderNew() returns
  110058. ** until SegmentReaderNext() returns something other than SQLITE_OK
  110059. ** (i.e. SQLITE_DONE).
  110060. */
  110061. int nTerm; /* Number of bytes in current term */
  110062. char *zTerm; /* Pointer to current term */
  110063. int nTermAlloc; /* Allocated size of zTerm buffer */
  110064. char *aDoclist; /* Pointer to doclist of current entry */
  110065. int nDoclist; /* Size of doclist in current entry */
  110066. /* The following variables are used to iterate through the current doclist */
  110067. char *pOffsetList;
  110068. sqlite3_int64 iDocid;
  110069. };
  110070. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  110071. #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
  110072. /*
  110073. ** An instance of this structure is used to create a segment b-tree in the
  110074. ** database. The internal details of this type are only accessed by the
  110075. ** following functions:
  110076. **
  110077. ** fts3SegWriterAdd()
  110078. ** fts3SegWriterFlush()
  110079. ** fts3SegWriterFree()
  110080. */
  110081. struct SegmentWriter {
  110082. SegmentNode *pTree; /* Pointer to interior tree structure */
  110083. sqlite3_int64 iFirst; /* First slot in %_segments written */
  110084. sqlite3_int64 iFree; /* Next free slot in %_segments */
  110085. char *zTerm; /* Pointer to previous term buffer */
  110086. int nTerm; /* Number of bytes in zTerm */
  110087. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  110088. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  110089. int nSize; /* Size of allocation at aData */
  110090. int nData; /* Bytes of data in aData */
  110091. char *aData; /* Pointer to block from malloc() */
  110092. };
  110093. /*
  110094. ** Type SegmentNode is used by the following three functions to create
  110095. ** the interior part of the segment b+-tree structures (everything except
  110096. ** the leaf nodes). These functions and type are only ever used by code
  110097. ** within the fts3SegWriterXXX() family of functions described above.
  110098. **
  110099. ** fts3NodeAddTerm()
  110100. ** fts3NodeWrite()
  110101. ** fts3NodeFree()
  110102. */
  110103. struct SegmentNode {
  110104. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  110105. SegmentNode *pRight; /* Pointer to right-sibling */
  110106. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  110107. int nEntry; /* Number of terms written to node so far */
  110108. char *zTerm; /* Pointer to previous term buffer */
  110109. int nTerm; /* Number of bytes in zTerm */
  110110. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  110111. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  110112. int nData; /* Bytes of valid data so far */
  110113. char *aData; /* Node data */
  110114. };
  110115. /*
  110116. ** Valid values for the second argument to fts3SqlStmt().
  110117. */
  110118. #define SQL_DELETE_CONTENT 0
  110119. #define SQL_IS_EMPTY 1
  110120. #define SQL_DELETE_ALL_CONTENT 2
  110121. #define SQL_DELETE_ALL_SEGMENTS 3
  110122. #define SQL_DELETE_ALL_SEGDIR 4
  110123. #define SQL_DELETE_ALL_DOCSIZE 5
  110124. #define SQL_DELETE_ALL_STAT 6
  110125. #define SQL_SELECT_CONTENT_BY_ROWID 7
  110126. #define SQL_NEXT_SEGMENT_INDEX 8
  110127. #define SQL_INSERT_SEGMENTS 9
  110128. #define SQL_NEXT_SEGMENTS_ID 10
  110129. #define SQL_INSERT_SEGDIR 11
  110130. #define SQL_SELECT_LEVEL 12
  110131. #define SQL_SELECT_ALL_LEVEL 13
  110132. #define SQL_SELECT_LEVEL_COUNT 14
  110133. #define SQL_SELECT_SEGDIR_COUNT_MAX 15
  110134. #define SQL_DELETE_SEGDIR_BY_LEVEL 16
  110135. #define SQL_DELETE_SEGMENTS_RANGE 17
  110136. #define SQL_CONTENT_INSERT 18
  110137. #define SQL_DELETE_DOCSIZE 19
  110138. #define SQL_REPLACE_DOCSIZE 20
  110139. #define SQL_SELECT_DOCSIZE 21
  110140. #define SQL_SELECT_DOCTOTAL 22
  110141. #define SQL_REPLACE_DOCTOTAL 23
  110142. /*
  110143. ** This function is used to obtain an SQLite prepared statement handle
  110144. ** for the statement identified by the second argument. If successful,
  110145. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  110146. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  110147. **
  110148. ** If argument apVal is not NULL, then it must point to an array with
  110149. ** at least as many entries as the requested statement has bound
  110150. ** parameters. The values are bound to the statements parameters before
  110151. ** returning.
  110152. */
  110153. static int fts3SqlStmt(
  110154. Fts3Table *p, /* Virtual table handle */
  110155. int eStmt, /* One of the SQL_XXX constants above */
  110156. sqlite3_stmt **pp, /* OUT: Statement handle */
  110157. sqlite3_value **apVal /* Values to bind to statement */
  110158. ){
  110159. const char *azSql[] = {
  110160. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  110161. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  110162. /* 2 */ "DELETE FROM %Q.'%q_content'",
  110163. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  110164. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  110165. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  110166. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  110167. /* 7 */ "SELECT %s FROM %Q.'%q_content' AS x WHERE rowid=?",
  110168. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  110169. /* 9 */ "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  110170. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  110171. /* 11 */ "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  110172. /* Return segments in order from oldest to newest.*/
  110173. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  110174. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  110175. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  110176. "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
  110177. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  110178. /* 15 */ "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
  110179. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  110180. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  110181. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  110182. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  110183. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  110184. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  110185. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=0",
  110186. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
  110187. };
  110188. int rc = SQLITE_OK;
  110189. sqlite3_stmt *pStmt;
  110190. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  110191. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  110192. pStmt = p->aStmt[eStmt];
  110193. if( !pStmt ){
  110194. char *zSql;
  110195. if( eStmt==SQL_CONTENT_INSERT ){
  110196. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  110197. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  110198. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist, p->zDb, p->zName);
  110199. }else{
  110200. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  110201. }
  110202. if( !zSql ){
  110203. rc = SQLITE_NOMEM;
  110204. }else{
  110205. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  110206. sqlite3_free(zSql);
  110207. assert( rc==SQLITE_OK || pStmt==0 );
  110208. p->aStmt[eStmt] = pStmt;
  110209. }
  110210. }
  110211. if( apVal ){
  110212. int i;
  110213. int nParam = sqlite3_bind_parameter_count(pStmt);
  110214. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  110215. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  110216. }
  110217. }
  110218. *pp = pStmt;
  110219. return rc;
  110220. }
  110221. static int fts3SelectDocsize(
  110222. Fts3Table *pTab, /* FTS3 table handle */
  110223. int eStmt, /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
  110224. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  110225. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  110226. ){
  110227. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  110228. int rc; /* Return code */
  110229. assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
  110230. rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
  110231. if( rc==SQLITE_OK ){
  110232. if( eStmt==SQL_SELECT_DOCSIZE ){
  110233. sqlite3_bind_int64(pStmt, 1, iDocid);
  110234. }
  110235. rc = sqlite3_step(pStmt);
  110236. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  110237. rc = sqlite3_reset(pStmt);
  110238. if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
  110239. pStmt = 0;
  110240. }else{
  110241. rc = SQLITE_OK;
  110242. }
  110243. }
  110244. *ppStmt = pStmt;
  110245. return rc;
  110246. }
  110247. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  110248. Fts3Table *pTab, /* Fts3 table handle */
  110249. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  110250. ){
  110251. return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
  110252. }
  110253. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  110254. Fts3Table *pTab, /* Fts3 table handle */
  110255. sqlite3_int64 iDocid, /* Docid to read size data for */
  110256. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  110257. ){
  110258. return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
  110259. }
  110260. /*
  110261. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  110262. ** array apVal[] to the SQL statement identified by eStmt, the statement
  110263. ** is executed.
  110264. **
  110265. ** Returns SQLITE_OK if the statement is successfully executed, or an
  110266. ** SQLite error code otherwise.
  110267. */
  110268. static void fts3SqlExec(
  110269. int *pRC, /* Result code */
  110270. Fts3Table *p, /* The FTS3 table */
  110271. int eStmt, /* Index of statement to evaluate */
  110272. sqlite3_value **apVal /* Parameters to bind */
  110273. ){
  110274. sqlite3_stmt *pStmt;
  110275. int rc;
  110276. if( *pRC ) return;
  110277. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  110278. if( rc==SQLITE_OK ){
  110279. sqlite3_step(pStmt);
  110280. rc = sqlite3_reset(pStmt);
  110281. }
  110282. *pRC = rc;
  110283. }
  110284. /*
  110285. ** This function ensures that the caller has obtained a shared-cache
  110286. ** table-lock on the %_content table. This is required before reading
  110287. ** data from the fts3 table. If this lock is not acquired first, then
  110288. ** the caller may end up holding read-locks on the %_segments and %_segdir
  110289. ** tables, but no read-lock on the %_content table. If this happens
  110290. ** a second connection will be able to write to the fts3 table, but
  110291. ** attempting to commit those writes might return SQLITE_LOCKED or
  110292. ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
  110293. ** write-locks on the %_segments and %_segdir ** tables).
  110294. **
  110295. ** We try to avoid this because if FTS3 returns any error when committing
  110296. ** a transaction, the whole transaction will be rolled back. And this is
  110297. ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
  110298. ** still happen if the user reads data directly from the %_segments or
  110299. ** %_segdir tables instead of going through FTS3 though.
  110300. */
  110301. SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
  110302. int rc; /* Return code */
  110303. sqlite3_stmt *pStmt; /* Statement used to obtain lock */
  110304. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
  110305. if( rc==SQLITE_OK ){
  110306. sqlite3_bind_null(pStmt, 1);
  110307. sqlite3_step(pStmt);
  110308. rc = sqlite3_reset(pStmt);
  110309. }
  110310. return rc;
  110311. }
  110312. /*
  110313. ** Set *ppStmt to a statement handle that may be used to iterate through
  110314. ** all rows in the %_segdir table, from oldest to newest. If successful,
  110315. ** return SQLITE_OK. If an error occurs while preparing the statement,
  110316. ** return an SQLite error code.
  110317. **
  110318. ** There is only ever one instance of this SQL statement compiled for
  110319. ** each FTS3 table.
  110320. **
  110321. ** The statement returns the following columns from the %_segdir table:
  110322. **
  110323. ** 0: idx
  110324. ** 1: start_block
  110325. ** 2: leaves_end_block
  110326. ** 3: end_block
  110327. ** 4: root
  110328. */
  110329. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, int iLevel, sqlite3_stmt **ppStmt){
  110330. int rc;
  110331. sqlite3_stmt *pStmt = 0;
  110332. if( iLevel<0 ){
  110333. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, &pStmt, 0);
  110334. }else{
  110335. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  110336. if( rc==SQLITE_OK ) sqlite3_bind_int(pStmt, 1, iLevel);
  110337. }
  110338. *ppStmt = pStmt;
  110339. return rc;
  110340. }
  110341. /*
  110342. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  110343. ** if successful, or an SQLite error code otherwise.
  110344. **
  110345. ** This function also serves to allocate the PendingList structure itself.
  110346. ** For example, to create a new PendingList structure containing two
  110347. ** varints:
  110348. **
  110349. ** PendingList *p = 0;
  110350. ** fts3PendingListAppendVarint(&p, 1);
  110351. ** fts3PendingListAppendVarint(&p, 2);
  110352. */
  110353. static int fts3PendingListAppendVarint(
  110354. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  110355. sqlite3_int64 i /* Value to append to data */
  110356. ){
  110357. PendingList *p = *pp;
  110358. /* Allocate or grow the PendingList as required. */
  110359. if( !p ){
  110360. p = sqlite3_malloc(sizeof(*p) + 100);
  110361. if( !p ){
  110362. return SQLITE_NOMEM;
  110363. }
  110364. p->nSpace = 100;
  110365. p->aData = (char *)&p[1];
  110366. p->nData = 0;
  110367. }
  110368. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  110369. int nNew = p->nSpace * 2;
  110370. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  110371. if( !p ){
  110372. sqlite3_free(*pp);
  110373. *pp = 0;
  110374. return SQLITE_NOMEM;
  110375. }
  110376. p->nSpace = nNew;
  110377. p->aData = (char *)&p[1];
  110378. }
  110379. /* Append the new serialized varint to the end of the list. */
  110380. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  110381. p->aData[p->nData] = '\0';
  110382. *pp = p;
  110383. return SQLITE_OK;
  110384. }
  110385. /*
  110386. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  110387. ** is returned if the structure is sqlite3_realloced as part of adding
  110388. ** the entry. Otherwise, zero.
  110389. **
  110390. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  110391. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  110392. ** it is set to SQLITE_OK.
  110393. */
  110394. static int fts3PendingListAppend(
  110395. PendingList **pp, /* IN/OUT: PendingList structure */
  110396. sqlite3_int64 iDocid, /* Docid for entry to add */
  110397. sqlite3_int64 iCol, /* Column for entry to add */
  110398. sqlite3_int64 iPos, /* Position of term for entry to add */
  110399. int *pRc /* OUT: Return code */
  110400. ){
  110401. PendingList *p = *pp;
  110402. int rc = SQLITE_OK;
  110403. assert( !p || p->iLastDocid<=iDocid );
  110404. if( !p || p->iLastDocid!=iDocid ){
  110405. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  110406. if( p ){
  110407. assert( p->nData<p->nSpace );
  110408. assert( p->aData[p->nData]==0 );
  110409. p->nData++;
  110410. }
  110411. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  110412. goto pendinglistappend_out;
  110413. }
  110414. p->iLastCol = -1;
  110415. p->iLastPos = 0;
  110416. p->iLastDocid = iDocid;
  110417. }
  110418. if( iCol>0 && p->iLastCol!=iCol ){
  110419. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  110420. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  110421. ){
  110422. goto pendinglistappend_out;
  110423. }
  110424. p->iLastCol = iCol;
  110425. p->iLastPos = 0;
  110426. }
  110427. if( iCol>=0 ){
  110428. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  110429. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  110430. if( rc==SQLITE_OK ){
  110431. p->iLastPos = iPos;
  110432. }
  110433. }
  110434. pendinglistappend_out:
  110435. *pRc = rc;
  110436. if( p!=*pp ){
  110437. *pp = p;
  110438. return 1;
  110439. }
  110440. return 0;
  110441. }
  110442. /*
  110443. ** Tokenize the nul-terminated string zText and add all tokens to the
  110444. ** pending-terms hash-table. The docid used is that currently stored in
  110445. ** p->iPrevDocid, and the column is specified by argument iCol.
  110446. **
  110447. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  110448. */
  110449. static int fts3PendingTermsAdd(
  110450. Fts3Table *p, /* Table into which text will be inserted */
  110451. const char *zText, /* Text of document to be inserted */
  110452. int iCol, /* Column into which text is being inserted */
  110453. u32 *pnWord /* OUT: Number of tokens inserted */
  110454. ){
  110455. int rc;
  110456. int iStart;
  110457. int iEnd;
  110458. int iPos;
  110459. int nWord = 0;
  110460. char const *zToken;
  110461. int nToken;
  110462. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  110463. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  110464. sqlite3_tokenizer_cursor *pCsr;
  110465. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  110466. const char**,int*,int*,int*,int*);
  110467. assert( pTokenizer && pModule );
  110468. rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
  110469. if( rc!=SQLITE_OK ){
  110470. return rc;
  110471. }
  110472. pCsr->pTokenizer = pTokenizer;
  110473. xNext = pModule->xNext;
  110474. while( SQLITE_OK==rc
  110475. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  110476. ){
  110477. PendingList *pList;
  110478. if( iPos>=nWord ) nWord = iPos+1;
  110479. /* Positions cannot be negative; we use -1 as a terminator internally.
  110480. ** Tokens must have a non-zero length.
  110481. */
  110482. if( iPos<0 || !zToken || nToken<=0 ){
  110483. rc = SQLITE_ERROR;
  110484. break;
  110485. }
  110486. pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
  110487. if( pList ){
  110488. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  110489. }
  110490. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  110491. if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
  110492. /* Malloc failed while inserting the new entry. This can only
  110493. ** happen if there was no previous entry for this token.
  110494. */
  110495. assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
  110496. sqlite3_free(pList);
  110497. rc = SQLITE_NOMEM;
  110498. }
  110499. }
  110500. if( rc==SQLITE_OK ){
  110501. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  110502. }
  110503. }
  110504. pModule->xClose(pCsr);
  110505. *pnWord = nWord;
  110506. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  110507. }
  110508. /*
  110509. ** Calling this function indicates that subsequent calls to
  110510. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  110511. ** contents of the document with docid iDocid.
  110512. */
  110513. static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
  110514. /* TODO(shess) Explore whether partially flushing the buffer on
  110515. ** forced-flush would provide better performance. I suspect that if
  110516. ** we ordered the doclists by size and flushed the largest until the
  110517. ** buffer was half empty, that would let the less frequent terms
  110518. ** generate longer doclists.
  110519. */
  110520. if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
  110521. int rc = sqlite3Fts3PendingTermsFlush(p);
  110522. if( rc!=SQLITE_OK ) return rc;
  110523. }
  110524. p->iPrevDocid = iDocid;
  110525. return SQLITE_OK;
  110526. }
  110527. /*
  110528. ** Discard the contents of the pending-terms hash table.
  110529. */
  110530. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  110531. Fts3HashElem *pElem;
  110532. for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
  110533. sqlite3_free(fts3HashData(pElem));
  110534. }
  110535. fts3HashClear(&p->pendingTerms);
  110536. p->nPendingData = 0;
  110537. }
  110538. /*
  110539. ** This function is called by the xUpdate() method as part of an INSERT
  110540. ** operation. It adds entries for each term in the new record to the
  110541. ** pendingTerms hash table.
  110542. **
  110543. ** Argument apVal is the same as the similarly named argument passed to
  110544. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  110545. */
  110546. static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
  110547. int i; /* Iterator variable */
  110548. for(i=2; i<p->nColumn+2; i++){
  110549. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  110550. if( zText ){
  110551. int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
  110552. if( rc!=SQLITE_OK ){
  110553. return rc;
  110554. }
  110555. }
  110556. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  110557. }
  110558. return SQLITE_OK;
  110559. }
  110560. /*
  110561. ** This function is called by the xUpdate() method for an INSERT operation.
  110562. ** The apVal parameter is passed a copy of the apVal argument passed by
  110563. ** SQLite to the xUpdate() method. i.e:
  110564. **
  110565. ** apVal[0] Not used for INSERT.
  110566. ** apVal[1] rowid
  110567. ** apVal[2] Left-most user-defined column
  110568. ** ...
  110569. ** apVal[p->nColumn+1] Right-most user-defined column
  110570. ** apVal[p->nColumn+2] Hidden column with same name as table
  110571. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  110572. */
  110573. static int fts3InsertData(
  110574. Fts3Table *p, /* Full-text table */
  110575. sqlite3_value **apVal, /* Array of values to insert */
  110576. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  110577. ){
  110578. int rc; /* Return code */
  110579. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  110580. /* Locate the statement handle used to insert data into the %_content
  110581. ** table. The SQL for this statement is:
  110582. **
  110583. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  110584. **
  110585. ** The statement features N '?' variables, where N is the number of user
  110586. ** defined columns in the FTS3 table, plus one for the docid field.
  110587. */
  110588. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  110589. if( rc!=SQLITE_OK ){
  110590. return rc;
  110591. }
  110592. /* There is a quirk here. The users INSERT statement may have specified
  110593. ** a value for the "rowid" field, for the "docid" field, or for both.
  110594. ** Which is a problem, since "rowid" and "docid" are aliases for the
  110595. ** same value. For example:
  110596. **
  110597. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  110598. **
  110599. ** In FTS3, this is an error. It is an error to specify non-NULL values
  110600. ** for both docid and some other rowid alias.
  110601. */
  110602. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  110603. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  110604. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  110605. ){
  110606. /* A rowid/docid conflict. */
  110607. return SQLITE_ERROR;
  110608. }
  110609. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  110610. if( rc!=SQLITE_OK ) return rc;
  110611. }
  110612. /* Execute the statement to insert the record. Set *piDocid to the
  110613. ** new docid value.
  110614. */
  110615. sqlite3_step(pContentInsert);
  110616. rc = sqlite3_reset(pContentInsert);
  110617. *piDocid = sqlite3_last_insert_rowid(p->db);
  110618. return rc;
  110619. }
  110620. /*
  110621. ** Remove all data from the FTS3 table. Clear the hash table containing
  110622. ** pending terms.
  110623. */
  110624. static int fts3DeleteAll(Fts3Table *p){
  110625. int rc = SQLITE_OK; /* Return code */
  110626. /* Discard the contents of the pending-terms hash table. */
  110627. sqlite3Fts3PendingTermsClear(p);
  110628. /* Delete everything from the %_content, %_segments and %_segdir tables. */
  110629. fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  110630. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  110631. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  110632. if( p->bHasDocsize ){
  110633. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  110634. }
  110635. if( p->bHasStat ){
  110636. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  110637. }
  110638. return rc;
  110639. }
  110640. /*
  110641. ** The first element in the apVal[] array is assumed to contain the docid
  110642. ** (an integer) of a row about to be deleted. Remove all terms from the
  110643. ** full-text index.
  110644. */
  110645. static void fts3DeleteTerms(
  110646. int *pRC, /* Result code */
  110647. Fts3Table *p, /* The FTS table to delete from */
  110648. sqlite3_value **apVal, /* apVal[] contains the docid to be deleted */
  110649. u32 *aSz /* Sizes of deleted document written here */
  110650. ){
  110651. int rc;
  110652. sqlite3_stmt *pSelect;
  110653. if( *pRC ) return;
  110654. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
  110655. if( rc==SQLITE_OK ){
  110656. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  110657. int i;
  110658. for(i=1; i<=p->nColumn; i++){
  110659. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  110660. rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
  110661. if( rc!=SQLITE_OK ){
  110662. sqlite3_reset(pSelect);
  110663. *pRC = rc;
  110664. return;
  110665. }
  110666. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  110667. }
  110668. }
  110669. rc = sqlite3_reset(pSelect);
  110670. }else{
  110671. sqlite3_reset(pSelect);
  110672. }
  110673. *pRC = rc;
  110674. }
  110675. /*
  110676. ** Forward declaration to account for the circular dependency between
  110677. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  110678. */
  110679. static int fts3SegmentMerge(Fts3Table *, int);
  110680. /*
  110681. ** This function allocates a new level iLevel index in the segdir table.
  110682. ** Usually, indexes are allocated within a level sequentially starting
  110683. ** with 0, so the allocated index is one greater than the value returned
  110684. ** by:
  110685. **
  110686. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  110687. **
  110688. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  110689. ** level, they are merged into a single level (iLevel+1) segment and the
  110690. ** allocated index is 0.
  110691. **
  110692. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  110693. ** returned. Otherwise, an SQLite error code is returned.
  110694. */
  110695. static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
  110696. int rc; /* Return Code */
  110697. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  110698. int iNext = 0; /* Result of query pNextIdx */
  110699. /* Set variable iNext to the next available segdir index at level iLevel. */
  110700. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  110701. if( rc==SQLITE_OK ){
  110702. sqlite3_bind_int(pNextIdx, 1, iLevel);
  110703. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  110704. iNext = sqlite3_column_int(pNextIdx, 0);
  110705. }
  110706. rc = sqlite3_reset(pNextIdx);
  110707. }
  110708. if( rc==SQLITE_OK ){
  110709. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  110710. ** full, merge all segments in level iLevel into a single iLevel+1
  110711. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  110712. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  110713. */
  110714. if( iNext>=FTS3_MERGE_COUNT ){
  110715. rc = fts3SegmentMerge(p, iLevel);
  110716. *piIdx = 0;
  110717. }else{
  110718. *piIdx = iNext;
  110719. }
  110720. }
  110721. return rc;
  110722. }
  110723. /*
  110724. ** The %_segments table is declared as follows:
  110725. **
  110726. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  110727. **
  110728. ** This function reads data from a single row of the %_segments table. The
  110729. ** specific row is identified by the iBlockid parameter. If paBlob is not
  110730. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  110731. ** with the contents of the blob stored in the "block" column of the
  110732. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  110733. ** to the size of the blob in bytes before returning.
  110734. **
  110735. ** If an error occurs, or the table does not contain the specified row,
  110736. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  110737. ** paBlob is non-NULL, then it is the responsibility of the caller to
  110738. ** eventually free the returned buffer.
  110739. **
  110740. ** This function may leave an open sqlite3_blob* handle in the
  110741. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  110742. ** to this function. The handle may be closed by calling the
  110743. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  110744. ** performance improvement, but the blob handle should always be closed
  110745. ** before control is returned to the user (to prevent a lock being held
  110746. ** on the database file for longer than necessary). Thus, any virtual table
  110747. ** method (xFilter etc.) that may directly or indirectly call this function
  110748. ** must call sqlite3Fts3SegmentsClose() before returning.
  110749. */
  110750. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  110751. Fts3Table *p, /* FTS3 table handle */
  110752. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  110753. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  110754. int *pnBlob /* OUT: Size of blob data */
  110755. ){
  110756. int rc; /* Return code */
  110757. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  110758. assert( pnBlob);
  110759. if( p->pSegments ){
  110760. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  110761. }else{
  110762. if( 0==p->zSegmentsTbl ){
  110763. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  110764. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  110765. }
  110766. rc = sqlite3_blob_open(
  110767. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  110768. );
  110769. }
  110770. if( rc==SQLITE_OK ){
  110771. int nByte = sqlite3_blob_bytes(p->pSegments);
  110772. if( paBlob ){
  110773. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  110774. if( !aByte ){
  110775. rc = SQLITE_NOMEM;
  110776. }else{
  110777. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  110778. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  110779. if( rc!=SQLITE_OK ){
  110780. sqlite3_free(aByte);
  110781. aByte = 0;
  110782. }
  110783. }
  110784. *paBlob = aByte;
  110785. }
  110786. *pnBlob = nByte;
  110787. }
  110788. return rc;
  110789. }
  110790. /*
  110791. ** Close the blob handle at p->pSegments, if it is open. See comments above
  110792. ** the sqlite3Fts3ReadBlock() function for details.
  110793. */
  110794. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  110795. sqlite3_blob_close(p->pSegments);
  110796. p->pSegments = 0;
  110797. }
  110798. /*
  110799. ** Move the iterator passed as the first argument to the next term in the
  110800. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  110801. ** SQLITE_DONE. Otherwise, an SQLite error code.
  110802. */
  110803. static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
  110804. char *pNext; /* Cursor variable */
  110805. int nPrefix; /* Number of bytes in term prefix */
  110806. int nSuffix; /* Number of bytes in term suffix */
  110807. if( !pReader->aDoclist ){
  110808. pNext = pReader->aNode;
  110809. }else{
  110810. pNext = &pReader->aDoclist[pReader->nDoclist];
  110811. }
  110812. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  110813. int rc; /* Return code from Fts3ReadBlock() */
  110814. if( fts3SegReaderIsPending(pReader) ){
  110815. Fts3HashElem *pElem = *(pReader->ppNextElem);
  110816. if( pElem==0 ){
  110817. pReader->aNode = 0;
  110818. }else{
  110819. PendingList *pList = (PendingList *)fts3HashData(pElem);
  110820. pReader->zTerm = (char *)fts3HashKey(pElem);
  110821. pReader->nTerm = fts3HashKeysize(pElem);
  110822. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  110823. pReader->aNode = pReader->aDoclist = pList->aData;
  110824. pReader->ppNextElem++;
  110825. assert( pReader->aNode );
  110826. }
  110827. return SQLITE_OK;
  110828. }
  110829. if( !fts3SegReaderIsRootOnly(pReader) ){
  110830. sqlite3_free(pReader->aNode);
  110831. }
  110832. pReader->aNode = 0;
  110833. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  110834. ** blocks have already been traversed. */
  110835. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  110836. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  110837. return SQLITE_OK;
  110838. }
  110839. rc = sqlite3Fts3ReadBlock(
  110840. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
  110841. );
  110842. if( rc!=SQLITE_OK ) return rc;
  110843. pNext = pReader->aNode;
  110844. }
  110845. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  110846. ** safe (no risk of overread) even if the node data is corrupted.
  110847. */
  110848. pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
  110849. pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
  110850. if( nPrefix<0 || nSuffix<=0
  110851. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  110852. ){
  110853. return SQLITE_CORRUPT;
  110854. }
  110855. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  110856. int nNew = (nPrefix+nSuffix)*2;
  110857. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  110858. if( !zNew ){
  110859. return SQLITE_NOMEM;
  110860. }
  110861. pReader->zTerm = zNew;
  110862. pReader->nTermAlloc = nNew;
  110863. }
  110864. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  110865. pReader->nTerm = nPrefix+nSuffix;
  110866. pNext += nSuffix;
  110867. pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
  110868. pReader->aDoclist = pNext;
  110869. pReader->pOffsetList = 0;
  110870. /* Check that the doclist does not appear to extend past the end of the
  110871. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  110872. ** of these statements is untrue, then the data structure is corrupt.
  110873. */
  110874. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  110875. || pReader->aDoclist[pReader->nDoclist-1]
  110876. ){
  110877. return SQLITE_CORRUPT;
  110878. }
  110879. return SQLITE_OK;
  110880. }
  110881. /*
  110882. ** Set the SegReader to point to the first docid in the doclist associated
  110883. ** with the current term.
  110884. */
  110885. static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
  110886. int n;
  110887. assert( pReader->aDoclist );
  110888. assert( !pReader->pOffsetList );
  110889. n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  110890. pReader->pOffsetList = &pReader->aDoclist[n];
  110891. }
  110892. /*
  110893. ** Advance the SegReader to point to the next docid in the doclist
  110894. ** associated with the current term.
  110895. **
  110896. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  110897. ** *ppOffsetList is set to point to the first column-offset list
  110898. ** in the doclist entry (i.e. immediately past the docid varint).
  110899. ** *pnOffsetList is set to the length of the set of column-offset
  110900. ** lists, not including the nul-terminator byte. For example:
  110901. */
  110902. static void fts3SegReaderNextDocid(
  110903. Fts3SegReader *pReader,
  110904. char **ppOffsetList,
  110905. int *pnOffsetList
  110906. ){
  110907. char *p = pReader->pOffsetList;
  110908. char c = 0;
  110909. /* Pointer p currently points at the first byte of an offset list. The
  110910. ** following two lines advance it to point one byte past the end of
  110911. ** the same offset list.
  110912. */
  110913. while( *p | c ) c = *p++ & 0x80;
  110914. p++;
  110915. /* If required, populate the output variables with a pointer to and the
  110916. ** size of the previous offset-list.
  110917. */
  110918. if( ppOffsetList ){
  110919. *ppOffsetList = pReader->pOffsetList;
  110920. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  110921. }
  110922. /* If there are no more entries in the doclist, set pOffsetList to
  110923. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  110924. ** Fts3SegReader.pOffsetList to point to the next offset list before
  110925. ** returning.
  110926. */
  110927. if( p>=&pReader->aDoclist[pReader->nDoclist] ){
  110928. pReader->pOffsetList = 0;
  110929. }else{
  110930. sqlite3_int64 iDelta;
  110931. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  110932. pReader->iDocid += iDelta;
  110933. }
  110934. }
  110935. /*
  110936. ** This function is called to estimate the amount of data that will be
  110937. ** loaded from the disk If SegReaderIterate() is called on this seg-reader,
  110938. ** in units of average document size.
  110939. **
  110940. ** This can be used as follows: If the caller has a small doclist that
  110941. ** contains references to N documents, and is considering merging it with
  110942. ** a large doclist (size X "average documents"), it may opt not to load
  110943. ** the large doclist if X>N.
  110944. */
  110945. SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
  110946. Fts3Cursor *pCsr, /* FTS3 cursor handle */
  110947. Fts3SegReader *pReader, /* Segment-reader handle */
  110948. int *pnCost /* IN/OUT: Number of bytes read */
  110949. ){
  110950. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  110951. int rc = SQLITE_OK; /* Return code */
  110952. int nCost = 0; /* Cost in bytes to return */
  110953. int pgsz = p->nPgsz; /* Database page size */
  110954. /* If this seg-reader is reading the pending-terms table, or if all data
  110955. ** for the segment is stored on the root page of the b-tree, then the cost
  110956. ** is zero. In this case all required data is already in main memory.
  110957. */
  110958. if( p->bHasStat
  110959. && !fts3SegReaderIsPending(pReader)
  110960. && !fts3SegReaderIsRootOnly(pReader)
  110961. ){
  110962. int nBlob = 0;
  110963. sqlite3_int64 iBlock;
  110964. if( pCsr->nRowAvg==0 ){
  110965. /* The average document size, which is required to calculate the cost
  110966. ** of each doclist, has not yet been determined. Read the required
  110967. ** data from the %_stat table to calculate it.
  110968. **
  110969. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  110970. ** varints, where nCol is the number of columns in the FTS3 table.
  110971. ** The first varint is the number of documents currently stored in
  110972. ** the table. The following nCol varints contain the total amount of
  110973. ** data stored in all rows of each column of the table, from left
  110974. ** to right.
  110975. */
  110976. sqlite3_stmt *pStmt;
  110977. sqlite3_int64 nDoc = 0;
  110978. sqlite3_int64 nByte = 0;
  110979. const char *pEnd;
  110980. const char *a;
  110981. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  110982. if( rc!=SQLITE_OK ) return rc;
  110983. a = sqlite3_column_blob(pStmt, 0);
  110984. assert( a );
  110985. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  110986. a += sqlite3Fts3GetVarint(a, &nDoc);
  110987. while( a<pEnd ){
  110988. a += sqlite3Fts3GetVarint(a, &nByte);
  110989. }
  110990. if( nDoc==0 || nByte==0 ){
  110991. sqlite3_reset(pStmt);
  110992. return SQLITE_CORRUPT;
  110993. }
  110994. pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz) / pgsz);
  110995. assert( pCsr->nRowAvg>0 );
  110996. rc = sqlite3_reset(pStmt);
  110997. if( rc!=SQLITE_OK ) return rc;
  110998. }
  110999. /* Assume that a blob flows over onto overflow pages if it is larger
  111000. ** than (pgsz-35) bytes in size (the file-format documentation
  111001. ** confirms this).
  111002. */
  111003. for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
  111004. rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
  111005. if( rc!=SQLITE_OK ) break;
  111006. if( (nBlob+35)>pgsz ){
  111007. int nOvfl = (nBlob + 34)/pgsz;
  111008. nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
  111009. }
  111010. }
  111011. }
  111012. *pnCost += nCost;
  111013. return rc;
  111014. }
  111015. /*
  111016. ** Free all allocations associated with the iterator passed as the
  111017. ** second argument.
  111018. */
  111019. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  111020. if( pReader && !fts3SegReaderIsPending(pReader) ){
  111021. sqlite3_free(pReader->zTerm);
  111022. if( !fts3SegReaderIsRootOnly(pReader) ){
  111023. sqlite3_free(pReader->aNode);
  111024. }
  111025. }
  111026. sqlite3_free(pReader);
  111027. }
  111028. /*
  111029. ** Allocate a new SegReader object.
  111030. */
  111031. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  111032. int iAge, /* Segment "age". */
  111033. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  111034. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  111035. sqlite3_int64 iEndBlock, /* Final block of segment */
  111036. const char *zRoot, /* Buffer containing root node */
  111037. int nRoot, /* Size of buffer containing root node */
  111038. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  111039. ){
  111040. int rc = SQLITE_OK; /* Return code */
  111041. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  111042. int nExtra = 0; /* Bytes to allocate segment root node */
  111043. assert( iStartLeaf<=iEndLeaf );
  111044. if( iStartLeaf==0 ){
  111045. nExtra = nRoot + FTS3_NODE_PADDING;
  111046. }
  111047. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  111048. if( !pReader ){
  111049. return SQLITE_NOMEM;
  111050. }
  111051. memset(pReader, 0, sizeof(Fts3SegReader));
  111052. pReader->iIdx = iAge;
  111053. pReader->iStartBlock = iStartLeaf;
  111054. pReader->iLeafEndBlock = iEndLeaf;
  111055. pReader->iEndBlock = iEndBlock;
  111056. if( nExtra ){
  111057. /* The entire segment is stored in the root node. */
  111058. pReader->aNode = (char *)&pReader[1];
  111059. pReader->nNode = nRoot;
  111060. memcpy(pReader->aNode, zRoot, nRoot);
  111061. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  111062. }else{
  111063. pReader->iCurrentBlock = iStartLeaf-1;
  111064. }
  111065. if( rc==SQLITE_OK ){
  111066. *ppReader = pReader;
  111067. }else{
  111068. sqlite3Fts3SegReaderFree(pReader);
  111069. }
  111070. return rc;
  111071. }
  111072. /*
  111073. ** This is a comparison function used as a qsort() callback when sorting
  111074. ** an array of pending terms by term. This occurs as part of flushing
  111075. ** the contents of the pending-terms hash table to the database.
  111076. */
  111077. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  111078. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  111079. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  111080. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  111081. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  111082. int n = (n1<n2 ? n1 : n2);
  111083. int c = memcmp(z1, z2, n);
  111084. if( c==0 ){
  111085. c = n1 - n2;
  111086. }
  111087. return c;
  111088. }
  111089. /*
  111090. ** This function is used to allocate an Fts3SegReader that iterates through
  111091. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  111092. */
  111093. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  111094. Fts3Table *p, /* Virtual table handle */
  111095. const char *zTerm, /* Term to search for */
  111096. int nTerm, /* Size of buffer zTerm */
  111097. int isPrefix, /* True for a term-prefix query */
  111098. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  111099. ){
  111100. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  111101. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  111102. int nElem = 0; /* Size of array at aElem */
  111103. int rc = SQLITE_OK; /* Return Code */
  111104. if( isPrefix ){
  111105. int nAlloc = 0; /* Size of allocated array at aElem */
  111106. Fts3HashElem *pE = 0; /* Iterator variable */
  111107. for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
  111108. char *zKey = (char *)fts3HashKey(pE);
  111109. int nKey = fts3HashKeysize(pE);
  111110. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  111111. if( nElem==nAlloc ){
  111112. Fts3HashElem **aElem2;
  111113. nAlloc += 16;
  111114. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  111115. aElem, nAlloc*sizeof(Fts3HashElem *)
  111116. );
  111117. if( !aElem2 ){
  111118. rc = SQLITE_NOMEM;
  111119. nElem = 0;
  111120. break;
  111121. }
  111122. aElem = aElem2;
  111123. }
  111124. aElem[nElem++] = pE;
  111125. }
  111126. }
  111127. /* If more than one term matches the prefix, sort the Fts3HashElem
  111128. ** objects in term order using qsort(). This uses the same comparison
  111129. ** callback as is used when flushing terms to disk.
  111130. */
  111131. if( nElem>1 ){
  111132. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  111133. }
  111134. }else{
  111135. Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
  111136. if( pE ){
  111137. aElem = &pE;
  111138. nElem = 1;
  111139. }
  111140. }
  111141. if( nElem>0 ){
  111142. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  111143. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  111144. if( !pReader ){
  111145. rc = SQLITE_NOMEM;
  111146. }else{
  111147. memset(pReader, 0, nByte);
  111148. pReader->iIdx = 0x7FFFFFFF;
  111149. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  111150. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  111151. }
  111152. }
  111153. if( isPrefix ){
  111154. sqlite3_free(aElem);
  111155. }
  111156. *ppReader = pReader;
  111157. return rc;
  111158. }
  111159. /*
  111160. ** Compare the entries pointed to by two Fts3SegReader structures.
  111161. ** Comparison is as follows:
  111162. **
  111163. ** 1) EOF is greater than not EOF.
  111164. **
  111165. ** 2) The current terms (if any) are compared using memcmp(). If one
  111166. ** term is a prefix of another, the longer term is considered the
  111167. ** larger.
  111168. **
  111169. ** 3) By segment age. An older segment is considered larger.
  111170. */
  111171. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  111172. int rc;
  111173. if( pLhs->aNode && pRhs->aNode ){
  111174. int rc2 = pLhs->nTerm - pRhs->nTerm;
  111175. if( rc2<0 ){
  111176. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  111177. }else{
  111178. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  111179. }
  111180. if( rc==0 ){
  111181. rc = rc2;
  111182. }
  111183. }else{
  111184. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  111185. }
  111186. if( rc==0 ){
  111187. rc = pRhs->iIdx - pLhs->iIdx;
  111188. }
  111189. assert( rc!=0 );
  111190. return rc;
  111191. }
  111192. /*
  111193. ** A different comparison function for SegReader structures. In this
  111194. ** version, it is assumed that each SegReader points to an entry in
  111195. ** a doclist for identical terms. Comparison is made as follows:
  111196. **
  111197. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  111198. **
  111199. ** 2) By current docid.
  111200. **
  111201. ** 3) By segment age. An older segment is considered larger.
  111202. */
  111203. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  111204. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  111205. if( rc==0 ){
  111206. if( pLhs->iDocid==pRhs->iDocid ){
  111207. rc = pRhs->iIdx - pLhs->iIdx;
  111208. }else{
  111209. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  111210. }
  111211. }
  111212. assert( pLhs->aNode && pRhs->aNode );
  111213. return rc;
  111214. }
  111215. /*
  111216. ** Compare the term that the Fts3SegReader object passed as the first argument
  111217. ** points to with the term specified by arguments zTerm and nTerm.
  111218. **
  111219. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  111220. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  111221. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  111222. */
  111223. static int fts3SegReaderTermCmp(
  111224. Fts3SegReader *pSeg, /* Segment reader object */
  111225. const char *zTerm, /* Term to compare to */
  111226. int nTerm /* Size of term zTerm in bytes */
  111227. ){
  111228. int res = 0;
  111229. if( pSeg->aNode ){
  111230. if( pSeg->nTerm>nTerm ){
  111231. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  111232. }else{
  111233. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  111234. }
  111235. if( res==0 ){
  111236. res = pSeg->nTerm-nTerm;
  111237. }
  111238. }
  111239. return res;
  111240. }
  111241. /*
  111242. ** Argument apSegment is an array of nSegment elements. It is known that
  111243. ** the final (nSegment-nSuspect) members are already in sorted order
  111244. ** (according to the comparison function provided). This function shuffles
  111245. ** the array around until all entries are in sorted order.
  111246. */
  111247. static void fts3SegReaderSort(
  111248. Fts3SegReader **apSegment, /* Array to sort entries of */
  111249. int nSegment, /* Size of apSegment array */
  111250. int nSuspect, /* Unsorted entry count */
  111251. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  111252. ){
  111253. int i; /* Iterator variable */
  111254. assert( nSuspect<=nSegment );
  111255. if( nSuspect==nSegment ) nSuspect--;
  111256. for(i=nSuspect-1; i>=0; i--){
  111257. int j;
  111258. for(j=i; j<(nSegment-1); j++){
  111259. Fts3SegReader *pTmp;
  111260. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  111261. pTmp = apSegment[j+1];
  111262. apSegment[j+1] = apSegment[j];
  111263. apSegment[j] = pTmp;
  111264. }
  111265. }
  111266. #ifndef NDEBUG
  111267. /* Check that the list really is sorted now. */
  111268. for(i=0; i<(nSuspect-1); i++){
  111269. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  111270. }
  111271. #endif
  111272. }
  111273. /*
  111274. ** Insert a record into the %_segments table.
  111275. */
  111276. static int fts3WriteSegment(
  111277. Fts3Table *p, /* Virtual table handle */
  111278. sqlite3_int64 iBlock, /* Block id for new block */
  111279. char *z, /* Pointer to buffer containing block data */
  111280. int n /* Size of buffer z in bytes */
  111281. ){
  111282. sqlite3_stmt *pStmt;
  111283. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  111284. if( rc==SQLITE_OK ){
  111285. sqlite3_bind_int64(pStmt, 1, iBlock);
  111286. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  111287. sqlite3_step(pStmt);
  111288. rc = sqlite3_reset(pStmt);
  111289. }
  111290. return rc;
  111291. }
  111292. /*
  111293. ** Insert a record into the %_segdir table.
  111294. */
  111295. static int fts3WriteSegdir(
  111296. Fts3Table *p, /* Virtual table handle */
  111297. int iLevel, /* Value for "level" field */
  111298. int iIdx, /* Value for "idx" field */
  111299. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  111300. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  111301. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  111302. char *zRoot, /* Blob value for "root" field */
  111303. int nRoot /* Number of bytes in buffer zRoot */
  111304. ){
  111305. sqlite3_stmt *pStmt;
  111306. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  111307. if( rc==SQLITE_OK ){
  111308. sqlite3_bind_int(pStmt, 1, iLevel);
  111309. sqlite3_bind_int(pStmt, 2, iIdx);
  111310. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  111311. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  111312. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  111313. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  111314. sqlite3_step(pStmt);
  111315. rc = sqlite3_reset(pStmt);
  111316. }
  111317. return rc;
  111318. }
  111319. /*
  111320. ** Return the size of the common prefix (if any) shared by zPrev and
  111321. ** zNext, in bytes. For example,
  111322. **
  111323. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  111324. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  111325. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  111326. */
  111327. static int fts3PrefixCompress(
  111328. const char *zPrev, /* Buffer containing previous term */
  111329. int nPrev, /* Size of buffer zPrev in bytes */
  111330. const char *zNext, /* Buffer containing next term */
  111331. int nNext /* Size of buffer zNext in bytes */
  111332. ){
  111333. int n;
  111334. UNUSED_PARAMETER(nNext);
  111335. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  111336. return n;
  111337. }
  111338. /*
  111339. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  111340. ** (according to memcmp) than the previous term.
  111341. */
  111342. static int fts3NodeAddTerm(
  111343. Fts3Table *p, /* Virtual table handle */
  111344. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  111345. int isCopyTerm, /* True if zTerm/nTerm is transient */
  111346. const char *zTerm, /* Pointer to buffer containing term */
  111347. int nTerm /* Size of term in bytes */
  111348. ){
  111349. SegmentNode *pTree = *ppTree;
  111350. int rc;
  111351. SegmentNode *pNew;
  111352. /* First try to append the term to the current node. Return early if
  111353. ** this is possible.
  111354. */
  111355. if( pTree ){
  111356. int nData = pTree->nData; /* Current size of node in bytes */
  111357. int nReq = nData; /* Required space after adding zTerm */
  111358. int nPrefix; /* Number of bytes of prefix compression */
  111359. int nSuffix; /* Suffix length */
  111360. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  111361. nSuffix = nTerm-nPrefix;
  111362. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  111363. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  111364. if( nReq>p->nNodeSize ){
  111365. /* An unusual case: this is the first term to be added to the node
  111366. ** and the static node buffer (p->nNodeSize bytes) is not large
  111367. ** enough. Use a separately malloced buffer instead This wastes
  111368. ** p->nNodeSize bytes, but since this scenario only comes about when
  111369. ** the database contain two terms that share a prefix of almost 2KB,
  111370. ** this is not expected to be a serious problem.
  111371. */
  111372. assert( pTree->aData==(char *)&pTree[1] );
  111373. pTree->aData = (char *)sqlite3_malloc(nReq);
  111374. if( !pTree->aData ){
  111375. return SQLITE_NOMEM;
  111376. }
  111377. }
  111378. if( pTree->zTerm ){
  111379. /* There is no prefix-length field for first term in a node */
  111380. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  111381. }
  111382. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  111383. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  111384. pTree->nData = nData + nSuffix;
  111385. pTree->nEntry++;
  111386. if( isCopyTerm ){
  111387. if( pTree->nMalloc<nTerm ){
  111388. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  111389. if( !zNew ){
  111390. return SQLITE_NOMEM;
  111391. }
  111392. pTree->nMalloc = nTerm*2;
  111393. pTree->zMalloc = zNew;
  111394. }
  111395. pTree->zTerm = pTree->zMalloc;
  111396. memcpy(pTree->zTerm, zTerm, nTerm);
  111397. pTree->nTerm = nTerm;
  111398. }else{
  111399. pTree->zTerm = (char *)zTerm;
  111400. pTree->nTerm = nTerm;
  111401. }
  111402. return SQLITE_OK;
  111403. }
  111404. }
  111405. /* If control flows to here, it was not possible to append zTerm to the
  111406. ** current node. Create a new node (a right-sibling of the current node).
  111407. ** If this is the first node in the tree, the term is added to it.
  111408. **
  111409. ** Otherwise, the term is not added to the new node, it is left empty for
  111410. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  111411. ** has no parent, one is created here.
  111412. */
  111413. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  111414. if( !pNew ){
  111415. return SQLITE_NOMEM;
  111416. }
  111417. memset(pNew, 0, sizeof(SegmentNode));
  111418. pNew->nData = 1 + FTS3_VARINT_MAX;
  111419. pNew->aData = (char *)&pNew[1];
  111420. if( pTree ){
  111421. SegmentNode *pParent = pTree->pParent;
  111422. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  111423. if( pTree->pParent==0 ){
  111424. pTree->pParent = pParent;
  111425. }
  111426. pTree->pRight = pNew;
  111427. pNew->pLeftmost = pTree->pLeftmost;
  111428. pNew->pParent = pParent;
  111429. pNew->zMalloc = pTree->zMalloc;
  111430. pNew->nMalloc = pTree->nMalloc;
  111431. pTree->zMalloc = 0;
  111432. }else{
  111433. pNew->pLeftmost = pNew;
  111434. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  111435. }
  111436. *ppTree = pNew;
  111437. return rc;
  111438. }
  111439. /*
  111440. ** Helper function for fts3NodeWrite().
  111441. */
  111442. static int fts3TreeFinishNode(
  111443. SegmentNode *pTree,
  111444. int iHeight,
  111445. sqlite3_int64 iLeftChild
  111446. ){
  111447. int nStart;
  111448. assert( iHeight>=1 && iHeight<128 );
  111449. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  111450. pTree->aData[nStart] = (char)iHeight;
  111451. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  111452. return nStart;
  111453. }
  111454. /*
  111455. ** Write the buffer for the segment node pTree and all of its peers to the
  111456. ** database. Then call this function recursively to write the parent of
  111457. ** pTree and its peers to the database.
  111458. **
  111459. ** Except, if pTree is a root node, do not write it to the database. Instead,
  111460. ** set output variables *paRoot and *pnRoot to contain the root node.
  111461. **
  111462. ** If successful, SQLITE_OK is returned and output variable *piLast is
  111463. ** set to the largest blockid written to the database (or zero if no
  111464. ** blocks were written to the db). Otherwise, an SQLite error code is
  111465. ** returned.
  111466. */
  111467. static int fts3NodeWrite(
  111468. Fts3Table *p, /* Virtual table handle */
  111469. SegmentNode *pTree, /* SegmentNode handle */
  111470. int iHeight, /* Height of this node in tree */
  111471. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  111472. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  111473. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  111474. char **paRoot, /* OUT: Data for root node */
  111475. int *pnRoot /* OUT: Size of root node in bytes */
  111476. ){
  111477. int rc = SQLITE_OK;
  111478. if( !pTree->pParent ){
  111479. /* Root node of the tree. */
  111480. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  111481. *piLast = iFree-1;
  111482. *pnRoot = pTree->nData - nStart;
  111483. *paRoot = &pTree->aData[nStart];
  111484. }else{
  111485. SegmentNode *pIter;
  111486. sqlite3_int64 iNextFree = iFree;
  111487. sqlite3_int64 iNextLeaf = iLeaf;
  111488. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  111489. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  111490. int nWrite = pIter->nData - nStart;
  111491. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  111492. iNextFree++;
  111493. iNextLeaf += (pIter->nEntry+1);
  111494. }
  111495. if( rc==SQLITE_OK ){
  111496. assert( iNextLeaf==iFree );
  111497. rc = fts3NodeWrite(
  111498. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  111499. );
  111500. }
  111501. }
  111502. return rc;
  111503. }
  111504. /*
  111505. ** Free all memory allocations associated with the tree pTree.
  111506. */
  111507. static void fts3NodeFree(SegmentNode *pTree){
  111508. if( pTree ){
  111509. SegmentNode *p = pTree->pLeftmost;
  111510. fts3NodeFree(p->pParent);
  111511. while( p ){
  111512. SegmentNode *pRight = p->pRight;
  111513. if( p->aData!=(char *)&p[1] ){
  111514. sqlite3_free(p->aData);
  111515. }
  111516. assert( pRight==0 || p->zMalloc==0 );
  111517. sqlite3_free(p->zMalloc);
  111518. sqlite3_free(p);
  111519. p = pRight;
  111520. }
  111521. }
  111522. }
  111523. /*
  111524. ** Add a term to the segment being constructed by the SegmentWriter object
  111525. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  111526. ** be passed NULL. This function will allocate a new SegmentWriter object
  111527. ** and return it via the input/output variable *ppWriter in this case.
  111528. **
  111529. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  111530. */
  111531. static int fts3SegWriterAdd(
  111532. Fts3Table *p, /* Virtual table handle */
  111533. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  111534. int isCopyTerm, /* True if buffer zTerm must be copied */
  111535. const char *zTerm, /* Pointer to buffer containing term */
  111536. int nTerm, /* Size of term in bytes */
  111537. const char *aDoclist, /* Pointer to buffer containing doclist */
  111538. int nDoclist /* Size of doclist in bytes */
  111539. ){
  111540. int nPrefix; /* Size of term prefix in bytes */
  111541. int nSuffix; /* Size of term suffix in bytes */
  111542. int nReq; /* Number of bytes required on leaf page */
  111543. int nData;
  111544. SegmentWriter *pWriter = *ppWriter;
  111545. if( !pWriter ){
  111546. int rc;
  111547. sqlite3_stmt *pStmt;
  111548. /* Allocate the SegmentWriter structure */
  111549. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  111550. if( !pWriter ) return SQLITE_NOMEM;
  111551. memset(pWriter, 0, sizeof(SegmentWriter));
  111552. *ppWriter = pWriter;
  111553. /* Allocate a buffer in which to accumulate data */
  111554. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  111555. if( !pWriter->aData ) return SQLITE_NOMEM;
  111556. pWriter->nSize = p->nNodeSize;
  111557. /* Find the next free blockid in the %_segments table */
  111558. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  111559. if( rc!=SQLITE_OK ) return rc;
  111560. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  111561. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  111562. pWriter->iFirst = pWriter->iFree;
  111563. }
  111564. rc = sqlite3_reset(pStmt);
  111565. if( rc!=SQLITE_OK ) return rc;
  111566. }
  111567. nData = pWriter->nData;
  111568. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  111569. nSuffix = nTerm-nPrefix;
  111570. /* Figure out how many bytes are required by this new entry */
  111571. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  111572. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  111573. nSuffix + /* Term suffix */
  111574. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  111575. nDoclist; /* Doclist data */
  111576. if( nData>0 && nData+nReq>p->nNodeSize ){
  111577. int rc;
  111578. /* The current leaf node is full. Write it out to the database. */
  111579. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  111580. if( rc!=SQLITE_OK ) return rc;
  111581. /* Add the current term to the interior node tree. The term added to
  111582. ** the interior tree must:
  111583. **
  111584. ** a) be greater than the largest term on the leaf node just written
  111585. ** to the database (still available in pWriter->zTerm), and
  111586. **
  111587. ** b) be less than or equal to the term about to be added to the new
  111588. ** leaf node (zTerm/nTerm).
  111589. **
  111590. ** In other words, it must be the prefix of zTerm 1 byte longer than
  111591. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  111592. */
  111593. assert( nPrefix<nTerm );
  111594. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  111595. if( rc!=SQLITE_OK ) return rc;
  111596. nData = 0;
  111597. pWriter->nTerm = 0;
  111598. nPrefix = 0;
  111599. nSuffix = nTerm;
  111600. nReq = 1 + /* varint containing prefix size */
  111601. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  111602. nTerm + /* Term suffix */
  111603. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  111604. nDoclist; /* Doclist data */
  111605. }
  111606. /* If the buffer currently allocated is too small for this entry, realloc
  111607. ** the buffer to make it large enough.
  111608. */
  111609. if( nReq>pWriter->nSize ){
  111610. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  111611. if( !aNew ) return SQLITE_NOMEM;
  111612. pWriter->aData = aNew;
  111613. pWriter->nSize = nReq;
  111614. }
  111615. assert( nData+nReq<=pWriter->nSize );
  111616. /* Append the prefix-compressed term and doclist to the buffer. */
  111617. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  111618. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  111619. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  111620. nData += nSuffix;
  111621. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  111622. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  111623. pWriter->nData = nData + nDoclist;
  111624. /* Save the current term so that it can be used to prefix-compress the next.
  111625. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  111626. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  111627. ** store a copy of the pointer.
  111628. */
  111629. if( isCopyTerm ){
  111630. if( nTerm>pWriter->nMalloc ){
  111631. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  111632. if( !zNew ){
  111633. return SQLITE_NOMEM;
  111634. }
  111635. pWriter->nMalloc = nTerm*2;
  111636. pWriter->zMalloc = zNew;
  111637. pWriter->zTerm = zNew;
  111638. }
  111639. assert( pWriter->zTerm==pWriter->zMalloc );
  111640. memcpy(pWriter->zTerm, zTerm, nTerm);
  111641. }else{
  111642. pWriter->zTerm = (char *)zTerm;
  111643. }
  111644. pWriter->nTerm = nTerm;
  111645. return SQLITE_OK;
  111646. }
  111647. /*
  111648. ** Flush all data associated with the SegmentWriter object pWriter to the
  111649. ** database. This function must be called after all terms have been added
  111650. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  111651. ** returned. Otherwise, an SQLite error code.
  111652. */
  111653. static int fts3SegWriterFlush(
  111654. Fts3Table *p, /* Virtual table handle */
  111655. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  111656. int iLevel, /* Value for 'level' column of %_segdir */
  111657. int iIdx /* Value for 'idx' column of %_segdir */
  111658. ){
  111659. int rc; /* Return code */
  111660. if( pWriter->pTree ){
  111661. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  111662. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  111663. char *zRoot = NULL; /* Pointer to buffer containing root node */
  111664. int nRoot = 0; /* Size of buffer zRoot */
  111665. iLastLeaf = pWriter->iFree;
  111666. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  111667. if( rc==SQLITE_OK ){
  111668. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  111669. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  111670. }
  111671. if( rc==SQLITE_OK ){
  111672. rc = fts3WriteSegdir(
  111673. p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
  111674. }
  111675. }else{
  111676. /* The entire tree fits on the root node. Write it to the segdir table. */
  111677. rc = fts3WriteSegdir(
  111678. p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
  111679. }
  111680. return rc;
  111681. }
  111682. /*
  111683. ** Release all memory held by the SegmentWriter object passed as the
  111684. ** first argument.
  111685. */
  111686. static void fts3SegWriterFree(SegmentWriter *pWriter){
  111687. if( pWriter ){
  111688. sqlite3_free(pWriter->aData);
  111689. sqlite3_free(pWriter->zMalloc);
  111690. fts3NodeFree(pWriter->pTree);
  111691. sqlite3_free(pWriter);
  111692. }
  111693. }
  111694. /*
  111695. ** The first value in the apVal[] array is assumed to contain an integer.
  111696. ** This function tests if there exist any documents with docid values that
  111697. ** are different from that integer. i.e. if deleting the document with docid
  111698. ** apVal[0] would mean the FTS3 table were empty.
  111699. **
  111700. ** If successful, *pisEmpty is set to true if the table is empty except for
  111701. ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
  111702. ** error occurs, an SQLite error code is returned.
  111703. */
  111704. static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
  111705. sqlite3_stmt *pStmt;
  111706. int rc;
  111707. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
  111708. if( rc==SQLITE_OK ){
  111709. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  111710. *pisEmpty = sqlite3_column_int(pStmt, 0);
  111711. }
  111712. rc = sqlite3_reset(pStmt);
  111713. }
  111714. return rc;
  111715. }
  111716. /*
  111717. ** Set *pnSegment to the total number of segments in the database. Set
  111718. ** *pnMax to the largest segment level in the database (segment levels
  111719. ** are stored in the 'level' column of the %_segdir table).
  111720. **
  111721. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  111722. */
  111723. static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
  111724. sqlite3_stmt *pStmt;
  111725. int rc;
  111726. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
  111727. if( rc!=SQLITE_OK ) return rc;
  111728. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  111729. *pnSegment = sqlite3_column_int(pStmt, 0);
  111730. *pnMax = sqlite3_column_int(pStmt, 1);
  111731. }
  111732. return sqlite3_reset(pStmt);
  111733. }
  111734. /*
  111735. ** This function is used after merging multiple segments into a single large
  111736. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  111737. ** it:
  111738. **
  111739. ** 1) Deletes all %_segments entries for the segments associated with
  111740. ** each of the SegReader objects in the array passed as the third
  111741. ** argument, and
  111742. **
  111743. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  111744. ** entries regardless of level if (iLevel<0).
  111745. **
  111746. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  111747. */
  111748. static int fts3DeleteSegdir(
  111749. Fts3Table *p, /* Virtual table handle */
  111750. int iLevel, /* Level of %_segdir entries to delete */
  111751. Fts3SegReader **apSegment, /* Array of SegReader objects */
  111752. int nReader /* Size of array apSegment */
  111753. ){
  111754. int rc; /* Return Code */
  111755. int i; /* Iterator variable */
  111756. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  111757. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  111758. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  111759. Fts3SegReader *pSegment = apSegment[i];
  111760. if( pSegment->iStartBlock ){
  111761. sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
  111762. sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
  111763. sqlite3_step(pDelete);
  111764. rc = sqlite3_reset(pDelete);
  111765. }
  111766. }
  111767. if( rc!=SQLITE_OK ){
  111768. return rc;
  111769. }
  111770. if( iLevel==FTS3_SEGCURSOR_ALL ){
  111771. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  111772. }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
  111773. sqlite3Fts3PendingTermsClear(p);
  111774. }else{
  111775. assert( iLevel>=0 );
  111776. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
  111777. if( rc==SQLITE_OK ){
  111778. sqlite3_bind_int(pDelete, 1, iLevel);
  111779. sqlite3_step(pDelete);
  111780. rc = sqlite3_reset(pDelete);
  111781. }
  111782. }
  111783. return rc;
  111784. }
  111785. /*
  111786. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  111787. ** a position list that may (or may not) feature multiple columns. This
  111788. ** function adjusts the pointer *ppList and the length *pnList so that they
  111789. ** identify the subset of the position list that corresponds to column iCol.
  111790. **
  111791. ** If there are no entries in the input position list for column iCol, then
  111792. ** *pnList is set to zero before returning.
  111793. */
  111794. static void fts3ColumnFilter(
  111795. int iCol, /* Column to filter on */
  111796. char **ppList, /* IN/OUT: Pointer to position list */
  111797. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  111798. ){
  111799. char *pList = *ppList;
  111800. int nList = *pnList;
  111801. char *pEnd = &pList[nList];
  111802. int iCurrent = 0;
  111803. char *p = pList;
  111804. assert( iCol>=0 );
  111805. while( 1 ){
  111806. char c = 0;
  111807. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  111808. if( iCol==iCurrent ){
  111809. nList = (int)(p - pList);
  111810. break;
  111811. }
  111812. nList -= (int)(p - pList);
  111813. pList = p;
  111814. if( nList==0 ){
  111815. break;
  111816. }
  111817. p = &pList[1];
  111818. p += sqlite3Fts3GetVarint32(p, &iCurrent);
  111819. }
  111820. *ppList = pList;
  111821. *pnList = nList;
  111822. }
  111823. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  111824. Fts3Table *p, /* Virtual table handle */
  111825. Fts3SegReaderCursor *pCsr, /* Cursor object */
  111826. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  111827. ){
  111828. int i;
  111829. /* Initialize the cursor object */
  111830. pCsr->pFilter = pFilter;
  111831. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  111832. ** for, then advance each segment iterator until it points to a term of
  111833. ** equal or greater value than the specified term. This prevents many
  111834. ** unnecessary merge/sort operations for the case where single segment
  111835. ** b-tree leaf nodes contain more than one term.
  111836. */
  111837. for(i=0; i<pCsr->nSegment; i++){
  111838. int nTerm = pFilter->nTerm;
  111839. const char *zTerm = pFilter->zTerm;
  111840. Fts3SegReader *pSeg = pCsr->apSegment[i];
  111841. do {
  111842. int rc = fts3SegReaderNext(p, pSeg);
  111843. if( rc!=SQLITE_OK ) return rc;
  111844. }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
  111845. }
  111846. fts3SegReaderSort(
  111847. pCsr->apSegment, pCsr->nSegment, pCsr->nSegment, fts3SegReaderCmp);
  111848. return SQLITE_OK;
  111849. }
  111850. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  111851. Fts3Table *p, /* Virtual table handle */
  111852. Fts3SegReaderCursor *pCsr /* Cursor object */
  111853. ){
  111854. int rc = SQLITE_OK;
  111855. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  111856. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  111857. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  111858. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  111859. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  111860. Fts3SegReader **apSegment = pCsr->apSegment;
  111861. int nSegment = pCsr->nSegment;
  111862. Fts3SegFilter *pFilter = pCsr->pFilter;
  111863. if( pCsr->nSegment==0 ) return SQLITE_OK;
  111864. do {
  111865. int nMerge;
  111866. int i;
  111867. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  111868. ** forward. Then sort the list in order of current term again.
  111869. */
  111870. for(i=0; i<pCsr->nAdvance; i++){
  111871. rc = fts3SegReaderNext(p, apSegment[i]);
  111872. if( rc!=SQLITE_OK ) return rc;
  111873. }
  111874. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  111875. pCsr->nAdvance = 0;
  111876. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  111877. assert( rc==SQLITE_OK );
  111878. if( apSegment[0]->aNode==0 ) break;
  111879. pCsr->nTerm = apSegment[0]->nTerm;
  111880. pCsr->zTerm = apSegment[0]->zTerm;
  111881. /* If this is a prefix-search, and if the term that apSegment[0] points
  111882. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  111883. ** required callbacks have been made. In this case exit early.
  111884. **
  111885. ** Similarly, if this is a search for an exact match, and the first term
  111886. ** of segment apSegment[0] is not a match, exit early.
  111887. */
  111888. if( pFilter->zTerm && !isScan ){
  111889. if( pCsr->nTerm<pFilter->nTerm
  111890. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  111891. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  111892. ){
  111893. break;
  111894. }
  111895. }
  111896. nMerge = 1;
  111897. while( nMerge<nSegment
  111898. && apSegment[nMerge]->aNode
  111899. && apSegment[nMerge]->nTerm==pCsr->nTerm
  111900. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  111901. ){
  111902. nMerge++;
  111903. }
  111904. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  111905. if( nMerge==1 && !isIgnoreEmpty ){
  111906. pCsr->aDoclist = apSegment[0]->aDoclist;
  111907. pCsr->nDoclist = apSegment[0]->nDoclist;
  111908. rc = SQLITE_ROW;
  111909. }else{
  111910. int nDoclist = 0; /* Size of doclist */
  111911. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  111912. /* The current term of the first nMerge entries in the array
  111913. ** of Fts3SegReader objects is the same. The doclists must be merged
  111914. ** and a single term returned with the merged doclist.
  111915. */
  111916. for(i=0; i<nMerge; i++){
  111917. fts3SegReaderFirstDocid(apSegment[i]);
  111918. }
  111919. fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
  111920. while( apSegment[0]->pOffsetList ){
  111921. int j; /* Number of segments that share a docid */
  111922. char *pList;
  111923. int nList;
  111924. int nByte;
  111925. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  111926. fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
  111927. j = 1;
  111928. while( j<nMerge
  111929. && apSegment[j]->pOffsetList
  111930. && apSegment[j]->iDocid==iDocid
  111931. ){
  111932. fts3SegReaderNextDocid(apSegment[j], 0, 0);
  111933. j++;
  111934. }
  111935. if( isColFilter ){
  111936. fts3ColumnFilter(pFilter->iCol, &pList, &nList);
  111937. }
  111938. if( !isIgnoreEmpty || nList>0 ){
  111939. nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
  111940. if( nDoclist+nByte>pCsr->nBuffer ){
  111941. char *aNew;
  111942. pCsr->nBuffer = (nDoclist+nByte)*2;
  111943. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  111944. if( !aNew ){
  111945. return SQLITE_NOMEM;
  111946. }
  111947. pCsr->aBuffer = aNew;
  111948. }
  111949. nDoclist += sqlite3Fts3PutVarint(
  111950. &pCsr->aBuffer[nDoclist], iDocid-iPrev
  111951. );
  111952. iPrev = iDocid;
  111953. if( isRequirePos ){
  111954. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  111955. nDoclist += nList;
  111956. pCsr->aBuffer[nDoclist++] = '\0';
  111957. }
  111958. }
  111959. fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
  111960. }
  111961. if( nDoclist>0 ){
  111962. pCsr->aDoclist = pCsr->aBuffer;
  111963. pCsr->nDoclist = nDoclist;
  111964. rc = SQLITE_ROW;
  111965. }
  111966. }
  111967. pCsr->nAdvance = nMerge;
  111968. }while( rc==SQLITE_OK );
  111969. return rc;
  111970. }
  111971. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  111972. Fts3SegReaderCursor *pCsr /* Cursor object */
  111973. ){
  111974. if( pCsr ){
  111975. int i;
  111976. for(i=0; i<pCsr->nSegment; i++){
  111977. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  111978. }
  111979. sqlite3_free(pCsr->apSegment);
  111980. sqlite3_free(pCsr->aBuffer);
  111981. pCsr->nSegment = 0;
  111982. pCsr->apSegment = 0;
  111983. pCsr->aBuffer = 0;
  111984. }
  111985. }
  111986. /*
  111987. ** Merge all level iLevel segments in the database into a single
  111988. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  111989. ** single segment with a level equal to the numerically largest level
  111990. ** currently present in the database.
  111991. **
  111992. ** If this function is called with iLevel<0, but there is only one
  111993. ** segment in the database, SQLITE_DONE is returned immediately.
  111994. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  111995. ** an SQLite error code is returned.
  111996. */
  111997. static int fts3SegmentMerge(Fts3Table *p, int iLevel){
  111998. int rc; /* Return code */
  111999. int iIdx = 0; /* Index of new segment */
  112000. int iNewLevel = 0; /* Level to create new segment at */
  112001. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  112002. Fts3SegFilter filter; /* Segment term filter condition */
  112003. Fts3SegReaderCursor csr; /* Cursor to iterate through level(s) */
  112004. rc = sqlite3Fts3SegReaderCursor(p, iLevel, 0, 0, 1, 0, &csr);
  112005. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  112006. if( iLevel==FTS3_SEGCURSOR_ALL ){
  112007. /* This call is to merge all segments in the database to a single
  112008. ** segment. The level of the new segment is equal to the the numerically
  112009. ** greatest segment level currently present in the database. The index
  112010. ** of the new segment is always 0. */
  112011. int nDummy; /* TODO: Remove this */
  112012. if( csr.nSegment==1 ){
  112013. rc = SQLITE_DONE;
  112014. goto finished;
  112015. }
  112016. rc = fts3SegmentCountMax(p, &nDummy, &iNewLevel);
  112017. }else{
  112018. /* This call is to merge all segments at level iLevel. Find the next
  112019. ** available segment index at level iLevel+1. The call to
  112020. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  112021. ** a single iLevel+2 segment if necessary. */
  112022. iNewLevel = iLevel+1;
  112023. rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
  112024. }
  112025. if( rc!=SQLITE_OK ) goto finished;
  112026. assert( csr.nSegment>0 );
  112027. assert( iNewLevel>=0 );
  112028. memset(&filter, 0, sizeof(Fts3SegFilter));
  112029. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  112030. filter.flags |= (iLevel==FTS3_SEGCURSOR_ALL ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  112031. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  112032. while( SQLITE_OK==rc ){
  112033. rc = sqlite3Fts3SegReaderStep(p, &csr);
  112034. if( rc!=SQLITE_ROW ) break;
  112035. rc = fts3SegWriterAdd(p, &pWriter, 1,
  112036. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  112037. }
  112038. if( rc!=SQLITE_OK ) goto finished;
  112039. assert( pWriter );
  112040. rc = fts3DeleteSegdir(p, iLevel, csr.apSegment, csr.nSegment);
  112041. if( rc!=SQLITE_OK ) goto finished;
  112042. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  112043. finished:
  112044. fts3SegWriterFree(pWriter);
  112045. sqlite3Fts3SegReaderFinish(&csr);
  112046. return rc;
  112047. }
  112048. /*
  112049. ** Flush the contents of pendingTerms to a level 0 segment.
  112050. */
  112051. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  112052. return fts3SegmentMerge(p, FTS3_SEGCURSOR_PENDING);
  112053. }
  112054. /*
  112055. ** Encode N integers as varints into a blob.
  112056. */
  112057. static void fts3EncodeIntArray(
  112058. int N, /* The number of integers to encode */
  112059. u32 *a, /* The integer values */
  112060. char *zBuf, /* Write the BLOB here */
  112061. int *pNBuf /* Write number of bytes if zBuf[] used here */
  112062. ){
  112063. int i, j;
  112064. for(i=j=0; i<N; i++){
  112065. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  112066. }
  112067. *pNBuf = j;
  112068. }
  112069. /*
  112070. ** Decode a blob of varints into N integers
  112071. */
  112072. static void fts3DecodeIntArray(
  112073. int N, /* The number of integers to decode */
  112074. u32 *a, /* Write the integer values */
  112075. const char *zBuf, /* The BLOB containing the varints */
  112076. int nBuf /* size of the BLOB */
  112077. ){
  112078. int i, j;
  112079. UNUSED_PARAMETER(nBuf);
  112080. for(i=j=0; i<N; i++){
  112081. sqlite3_int64 x;
  112082. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  112083. assert(j<=nBuf);
  112084. a[i] = (u32)(x & 0xffffffff);
  112085. }
  112086. }
  112087. /*
  112088. ** Insert the sizes (in tokens) for each column of the document
  112089. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  112090. ** a blob of varints.
  112091. */
  112092. static void fts3InsertDocsize(
  112093. int *pRC, /* Result code */
  112094. Fts3Table *p, /* Table into which to insert */
  112095. u32 *aSz /* Sizes of each column */
  112096. ){
  112097. char *pBlob; /* The BLOB encoding of the document size */
  112098. int nBlob; /* Number of bytes in the BLOB */
  112099. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  112100. int rc; /* Result code from subfunctions */
  112101. if( *pRC ) return;
  112102. pBlob = sqlite3_malloc( 10*p->nColumn );
  112103. if( pBlob==0 ){
  112104. *pRC = SQLITE_NOMEM;
  112105. return;
  112106. }
  112107. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  112108. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  112109. if( rc ){
  112110. sqlite3_free(pBlob);
  112111. *pRC = rc;
  112112. return;
  112113. }
  112114. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  112115. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  112116. sqlite3_step(pStmt);
  112117. *pRC = sqlite3_reset(pStmt);
  112118. }
  112119. /*
  112120. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  112121. ** where N is the number of user defined columns in the fts3 table plus
  112122. ** two. If nCol is the number of user defined columns, then values of the
  112123. ** varints are set as follows:
  112124. **
  112125. ** Varint 0: Total number of rows in the table.
  112126. **
  112127. ** Varint 1..nCol: For each column, the total number of tokens stored in
  112128. ** the column for all rows of the table.
  112129. **
  112130. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  112131. ** columns of all rows of the table.
  112132. **
  112133. */
  112134. static void fts3UpdateDocTotals(
  112135. int *pRC, /* The result code */
  112136. Fts3Table *p, /* Table being updated */
  112137. u32 *aSzIns, /* Size increases */
  112138. u32 *aSzDel, /* Size decreases */
  112139. int nChng /* Change in the number of documents */
  112140. ){
  112141. char *pBlob; /* Storage for BLOB written into %_stat */
  112142. int nBlob; /* Size of BLOB written into %_stat */
  112143. u32 *a; /* Array of integers that becomes the BLOB */
  112144. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  112145. int i; /* Loop counter */
  112146. int rc; /* Result code from subfunctions */
  112147. const int nStat = p->nColumn+2;
  112148. if( *pRC ) return;
  112149. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  112150. if( a==0 ){
  112151. *pRC = SQLITE_NOMEM;
  112152. return;
  112153. }
  112154. pBlob = (char*)&a[nStat];
  112155. rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
  112156. if( rc ){
  112157. sqlite3_free(a);
  112158. *pRC = rc;
  112159. return;
  112160. }
  112161. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  112162. fts3DecodeIntArray(nStat, a,
  112163. sqlite3_column_blob(pStmt, 0),
  112164. sqlite3_column_bytes(pStmt, 0));
  112165. }else{
  112166. memset(a, 0, sizeof(u32)*(nStat) );
  112167. }
  112168. sqlite3_reset(pStmt);
  112169. if( nChng<0 && a[0]<(u32)(-nChng) ){
  112170. a[0] = 0;
  112171. }else{
  112172. a[0] += nChng;
  112173. }
  112174. for(i=0; i<p->nColumn+1; i++){
  112175. u32 x = a[i+1];
  112176. if( x+aSzIns[i] < aSzDel[i] ){
  112177. x = 0;
  112178. }else{
  112179. x = x + aSzIns[i] - aSzDel[i];
  112180. }
  112181. a[i+1] = x;
  112182. }
  112183. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  112184. rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
  112185. if( rc ){
  112186. sqlite3_free(a);
  112187. *pRC = rc;
  112188. return;
  112189. }
  112190. sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
  112191. sqlite3_step(pStmt);
  112192. *pRC = sqlite3_reset(pStmt);
  112193. sqlite3_free(a);
  112194. }
  112195. /*
  112196. ** Handle a 'special' INSERT of the form:
  112197. **
  112198. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  112199. **
  112200. ** Argument pVal contains the result of <expr>. Currently the only
  112201. ** meaningful value to insert is the text 'optimize'.
  112202. */
  112203. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  112204. int rc; /* Return Code */
  112205. const char *zVal = (const char *)sqlite3_value_text(pVal);
  112206. int nVal = sqlite3_value_bytes(pVal);
  112207. if( !zVal ){
  112208. return SQLITE_NOMEM;
  112209. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  112210. rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
  112211. if( rc==SQLITE_DONE ){
  112212. rc = SQLITE_OK;
  112213. }else{
  112214. sqlite3Fts3PendingTermsClear(p);
  112215. }
  112216. #ifdef SQLITE_TEST
  112217. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  112218. p->nNodeSize = atoi(&zVal[9]);
  112219. rc = SQLITE_OK;
  112220. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  112221. p->nMaxPendingData = atoi(&zVal[11]);
  112222. rc = SQLITE_OK;
  112223. #endif
  112224. }else{
  112225. rc = SQLITE_ERROR;
  112226. }
  112227. sqlite3Fts3SegmentsClose(p);
  112228. return rc;
  112229. }
  112230. /*
  112231. ** Return the deferred doclist associated with deferred token pDeferred.
  112232. ** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
  112233. ** been called to allocate and populate the doclist.
  112234. */
  112235. SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
  112236. if( pDeferred->pList ){
  112237. *pnByte = pDeferred->pList->nData;
  112238. return pDeferred->pList->aData;
  112239. }
  112240. *pnByte = 0;
  112241. return 0;
  112242. }
  112243. /*
  112244. ** Helper fucntion for FreeDeferredDoclists(). This function removes all
  112245. ** references to deferred doclists from within the tree of Fts3Expr
  112246. ** structures headed by
  112247. */
  112248. static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
  112249. if( pExpr ){
  112250. fts3DeferredDoclistClear(pExpr->pLeft);
  112251. fts3DeferredDoclistClear(pExpr->pRight);
  112252. if( pExpr->isLoaded ){
  112253. sqlite3_free(pExpr->aDoclist);
  112254. pExpr->isLoaded = 0;
  112255. pExpr->aDoclist = 0;
  112256. pExpr->nDoclist = 0;
  112257. pExpr->pCurrent = 0;
  112258. pExpr->iCurrent = 0;
  112259. }
  112260. }
  112261. }
  112262. /*
  112263. ** Delete all cached deferred doclists. Deferred doclists are cached
  112264. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  112265. */
  112266. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  112267. Fts3DeferredToken *pDef;
  112268. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  112269. sqlite3_free(pDef->pList);
  112270. pDef->pList = 0;
  112271. }
  112272. if( pCsr->pDeferred ){
  112273. fts3DeferredDoclistClear(pCsr->pExpr);
  112274. }
  112275. }
  112276. /*
  112277. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  112278. ** this list using sqlite3Fts3DeferToken().
  112279. */
  112280. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  112281. Fts3DeferredToken *pDef;
  112282. Fts3DeferredToken *pNext;
  112283. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  112284. pNext = pDef->pNext;
  112285. sqlite3_free(pDef->pList);
  112286. sqlite3_free(pDef);
  112287. }
  112288. pCsr->pDeferred = 0;
  112289. }
  112290. /*
  112291. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  112292. ** based on the row that pCsr currently points to.
  112293. **
  112294. ** A deferred-doclist is like any other doclist with position information
  112295. ** included, except that it only contains entries for a single row of the
  112296. ** table, not for all rows.
  112297. */
  112298. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  112299. int rc = SQLITE_OK; /* Return code */
  112300. if( pCsr->pDeferred ){
  112301. int i; /* Used to iterate through table columns */
  112302. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  112303. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  112304. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  112305. sqlite3_tokenizer *pT = p->pTokenizer;
  112306. sqlite3_tokenizer_module const *pModule = pT->pModule;
  112307. assert( pCsr->isRequireSeek==0 );
  112308. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  112309. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  112310. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  112311. sqlite3_tokenizer_cursor *pTC = 0;
  112312. rc = pModule->xOpen(pT, zText, -1, &pTC);
  112313. while( rc==SQLITE_OK ){
  112314. char const *zToken; /* Buffer containing token */
  112315. int nToken; /* Number of bytes in token */
  112316. int iDum1, iDum2; /* Dummy variables */
  112317. int iPos; /* Position of token in zText */
  112318. pTC->pTokenizer = pT;
  112319. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  112320. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  112321. Fts3PhraseToken *pPT = pDef->pToken;
  112322. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  112323. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  112324. && (0==memcmp(zToken, pPT->z, pPT->n))
  112325. ){
  112326. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  112327. }
  112328. }
  112329. }
  112330. if( pTC ) pModule->xClose(pTC);
  112331. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  112332. }
  112333. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  112334. if( pDef->pList ){
  112335. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  112336. }
  112337. }
  112338. }
  112339. return rc;
  112340. }
  112341. /*
  112342. ** Add an entry for token pToken to the pCsr->pDeferred list.
  112343. */
  112344. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  112345. Fts3Cursor *pCsr, /* Fts3 table cursor */
  112346. Fts3PhraseToken *pToken, /* Token to defer */
  112347. int iCol /* Column that token must appear in (or -1) */
  112348. ){
  112349. Fts3DeferredToken *pDeferred;
  112350. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  112351. if( !pDeferred ){
  112352. return SQLITE_NOMEM;
  112353. }
  112354. memset(pDeferred, 0, sizeof(*pDeferred));
  112355. pDeferred->pToken = pToken;
  112356. pDeferred->pNext = pCsr->pDeferred;
  112357. pDeferred->iCol = iCol;
  112358. pCsr->pDeferred = pDeferred;
  112359. assert( pToken->pDeferred==0 );
  112360. pToken->pDeferred = pDeferred;
  112361. return SQLITE_OK;
  112362. }
  112363. /*
  112364. ** This function does the work for the xUpdate method of FTS3 virtual
  112365. ** tables.
  112366. */
  112367. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  112368. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  112369. int nArg, /* Size of argument array */
  112370. sqlite3_value **apVal, /* Array of arguments */
  112371. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  112372. ){
  112373. Fts3Table *p = (Fts3Table *)pVtab;
  112374. int rc = SQLITE_OK; /* Return Code */
  112375. int isRemove = 0; /* True for an UPDATE or DELETE */
  112376. sqlite3_int64 iRemove = 0; /* Rowid removed by UPDATE or DELETE */
  112377. u32 *aSzIns; /* Sizes of inserted documents */
  112378. u32 *aSzDel; /* Sizes of deleted documents */
  112379. int nChng = 0; /* Net change in number of documents */
  112380. assert( p->pSegments==0 );
  112381. /* Allocate space to hold the change in document sizes */
  112382. aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
  112383. if( aSzIns==0 ) return SQLITE_NOMEM;
  112384. aSzDel = &aSzIns[p->nColumn+1];
  112385. memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
  112386. /* If this is a DELETE or UPDATE operation, remove the old record. */
  112387. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  112388. int isEmpty = 0;
  112389. rc = fts3IsEmpty(p, apVal, &isEmpty);
  112390. if( rc==SQLITE_OK ){
  112391. if( isEmpty ){
  112392. /* Deleting this row means the whole table is empty. In this case
  112393. ** delete the contents of all three tables and throw away any
  112394. ** data in the pendingTerms hash table.
  112395. */
  112396. rc = fts3DeleteAll(p);
  112397. }else{
  112398. isRemove = 1;
  112399. iRemove = sqlite3_value_int64(apVal[0]);
  112400. rc = fts3PendingTermsDocid(p, iRemove);
  112401. fts3DeleteTerms(&rc, p, apVal, aSzDel);
  112402. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
  112403. if( p->bHasDocsize ){
  112404. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
  112405. }
  112406. nChng--;
  112407. }
  112408. }
  112409. }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
  112410. sqlite3_free(aSzIns);
  112411. return fts3SpecialInsert(p, apVal[p->nColumn+2]);
  112412. }
  112413. /* If this is an INSERT or UPDATE operation, insert the new record. */
  112414. if( nArg>1 && rc==SQLITE_OK ){
  112415. rc = fts3InsertData(p, apVal, pRowid);
  112416. if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
  112417. rc = fts3PendingTermsDocid(p, *pRowid);
  112418. }
  112419. if( rc==SQLITE_OK ){
  112420. rc = fts3InsertTerms(p, apVal, aSzIns);
  112421. }
  112422. if( p->bHasDocsize ){
  112423. fts3InsertDocsize(&rc, p, aSzIns);
  112424. }
  112425. nChng++;
  112426. }
  112427. if( p->bHasStat ){
  112428. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  112429. }
  112430. sqlite3_free(aSzIns);
  112431. sqlite3Fts3SegmentsClose(p);
  112432. return rc;
  112433. }
  112434. /*
  112435. ** Flush any data in the pending-terms hash table to disk. If successful,
  112436. ** merge all segments in the database (including the new segment, if
  112437. ** there was any data to flush) into a single segment.
  112438. */
  112439. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  112440. int rc;
  112441. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  112442. if( rc==SQLITE_OK ){
  112443. rc = fts3SegmentMerge(p, FTS3_SEGCURSOR_ALL);
  112444. if( rc==SQLITE_OK ){
  112445. rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  112446. if( rc==SQLITE_OK ){
  112447. sqlite3Fts3PendingTermsClear(p);
  112448. }
  112449. }else{
  112450. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  112451. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  112452. }
  112453. }
  112454. sqlite3Fts3SegmentsClose(p);
  112455. return rc;
  112456. }
  112457. #endif
  112458. /************** End of fts3_write.c ******************************************/
  112459. /************** Begin file fts3_snippet.c ************************************/
  112460. /*
  112461. ** 2009 Oct 23
  112462. **
  112463. ** The author disclaims copyright to this source code. In place of
  112464. ** a legal notice, here is a blessing:
  112465. **
  112466. ** May you do good and not evil.
  112467. ** May you find forgiveness for yourself and forgive others.
  112468. ** May you share freely, never taking more than you give.
  112469. **
  112470. ******************************************************************************
  112471. */
  112472. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  112473. /*
  112474. ** Characters that may appear in the second argument to matchinfo().
  112475. */
  112476. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  112477. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  112478. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  112479. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  112480. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  112481. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  112482. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  112483. /*
  112484. ** The default value for the second argument to matchinfo().
  112485. */
  112486. #define FTS3_MATCHINFO_DEFAULT "pcx"
  112487. /*
  112488. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  112489. ** Fts3Expr.aDoclist[]/nDoclist.
  112490. */
  112491. typedef struct LoadDoclistCtx LoadDoclistCtx;
  112492. struct LoadDoclistCtx {
  112493. Fts3Cursor *pCsr; /* FTS3 Cursor */
  112494. int nPhrase; /* Number of phrases seen so far */
  112495. int nToken; /* Number of tokens seen so far */
  112496. };
  112497. /*
  112498. ** The following types are used as part of the implementation of the
  112499. ** fts3BestSnippet() routine.
  112500. */
  112501. typedef struct SnippetIter SnippetIter;
  112502. typedef struct SnippetPhrase SnippetPhrase;
  112503. typedef struct SnippetFragment SnippetFragment;
  112504. struct SnippetIter {
  112505. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  112506. int iCol; /* Extract snippet from this column */
  112507. int nSnippet; /* Requested snippet length (in tokens) */
  112508. int nPhrase; /* Number of phrases in query */
  112509. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  112510. int iCurrent; /* First token of current snippet */
  112511. };
  112512. struct SnippetPhrase {
  112513. int nToken; /* Number of tokens in phrase */
  112514. char *pList; /* Pointer to start of phrase position list */
  112515. int iHead; /* Next value in position list */
  112516. char *pHead; /* Position list data following iHead */
  112517. int iTail; /* Next value in trailing position list */
  112518. char *pTail; /* Position list data following iTail */
  112519. };
  112520. struct SnippetFragment {
  112521. int iCol; /* Column snippet is extracted from */
  112522. int iPos; /* Index of first token in snippet */
  112523. u64 covered; /* Mask of query phrases covered */
  112524. u64 hlmask; /* Mask of snippet terms to highlight */
  112525. };
  112526. /*
  112527. ** This type is used as an fts3ExprIterate() context object while
  112528. ** accumulating the data returned by the matchinfo() function.
  112529. */
  112530. typedef struct MatchInfo MatchInfo;
  112531. struct MatchInfo {
  112532. Fts3Cursor *pCursor; /* FTS3 Cursor */
  112533. int nCol; /* Number of columns in table */
  112534. int nPhrase; /* Number of matchable phrases in query */
  112535. sqlite3_int64 nDoc; /* Number of docs in database */
  112536. u32 *aMatchinfo; /* Pre-allocated buffer */
  112537. };
  112538. /*
  112539. ** The snippet() and offsets() functions both return text values. An instance
  112540. ** of the following structure is used to accumulate those values while the
  112541. ** functions are running. See fts3StringAppend() for details.
  112542. */
  112543. typedef struct StrBuffer StrBuffer;
  112544. struct StrBuffer {
  112545. char *z; /* Pointer to buffer containing string */
  112546. int n; /* Length of z in bytes (excl. nul-term) */
  112547. int nAlloc; /* Allocated size of buffer z in bytes */
  112548. };
  112549. /*
  112550. ** This function is used to help iterate through a position-list. A position
  112551. ** list is a list of unique integers, sorted from smallest to largest. Each
  112552. ** element of the list is represented by an FTS3 varint that takes the value
  112553. ** of the difference between the current element and the previous one plus
  112554. ** two. For example, to store the position-list:
  112555. **
  112556. ** 4 9 113
  112557. **
  112558. ** the three varints:
  112559. **
  112560. ** 6 7 106
  112561. **
  112562. ** are encoded.
  112563. **
  112564. ** When this function is called, *pp points to the start of an element of
  112565. ** the list. *piPos contains the value of the previous entry in the list.
  112566. ** After it returns, *piPos contains the value of the next element of the
  112567. ** list and *pp is advanced to the following varint.
  112568. */
  112569. static void fts3GetDeltaPosition(char **pp, int *piPos){
  112570. int iVal;
  112571. *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
  112572. *piPos += (iVal-2);
  112573. }
  112574. /*
  112575. ** Helper function for fts3ExprIterate() (see below).
  112576. */
  112577. static int fts3ExprIterate2(
  112578. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  112579. int *piPhrase, /* Pointer to phrase counter */
  112580. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  112581. void *pCtx /* Second argument to pass to callback */
  112582. ){
  112583. int rc; /* Return code */
  112584. int eType = pExpr->eType; /* Type of expression node pExpr */
  112585. if( eType!=FTSQUERY_PHRASE ){
  112586. assert( pExpr->pLeft && pExpr->pRight );
  112587. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  112588. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  112589. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  112590. }
  112591. }else{
  112592. rc = x(pExpr, *piPhrase, pCtx);
  112593. (*piPhrase)++;
  112594. }
  112595. return rc;
  112596. }
  112597. /*
  112598. ** Iterate through all phrase nodes in an FTS3 query, except those that
  112599. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  112600. ** For each phrase node found, the supplied callback function is invoked.
  112601. **
  112602. ** If the callback function returns anything other than SQLITE_OK,
  112603. ** the iteration is abandoned and the error code returned immediately.
  112604. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  112605. ** all eligible phrase nodes.
  112606. */
  112607. static int fts3ExprIterate(
  112608. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  112609. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  112610. void *pCtx /* Second argument to pass to callback */
  112611. ){
  112612. int iPhrase = 0; /* Variable used as the phrase counter */
  112613. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  112614. }
  112615. /*
  112616. ** The argument to this function is always a phrase node. Its doclist
  112617. ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
  112618. ** to the left of this one in the query tree have already been loaded.
  112619. **
  112620. ** If this phrase node is part of a series of phrase nodes joined by
  112621. ** NEAR operators (and is not the left-most of said series), then elements are
  112622. ** removed from the phrases doclist consistent with the NEAR restriction. If
  112623. ** required, elements may be removed from the doclists of phrases to the
  112624. ** left of this one that are part of the same series of NEAR operator
  112625. ** connected phrases.
  112626. **
  112627. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  112628. */
  112629. static int fts3ExprNearTrim(Fts3Expr *pExpr){
  112630. int rc = SQLITE_OK;
  112631. Fts3Expr *pParent = pExpr->pParent;
  112632. assert( pExpr->eType==FTSQUERY_PHRASE );
  112633. while( rc==SQLITE_OK
  112634. && pParent
  112635. && pParent->eType==FTSQUERY_NEAR
  112636. && pParent->pRight==pExpr
  112637. ){
  112638. /* This expression (pExpr) is the right-hand-side of a NEAR operator.
  112639. ** Find the expression to the left of the same operator.
  112640. */
  112641. int nNear = pParent->nNear;
  112642. Fts3Expr *pLeft = pParent->pLeft;
  112643. if( pLeft->eType!=FTSQUERY_PHRASE ){
  112644. assert( pLeft->eType==FTSQUERY_NEAR );
  112645. assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
  112646. pLeft = pLeft->pRight;
  112647. }
  112648. rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
  112649. pExpr = pLeft;
  112650. pParent = pExpr->pParent;
  112651. }
  112652. return rc;
  112653. }
  112654. /*
  112655. ** This is an fts3ExprIterate() callback used while loading the doclists
  112656. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  112657. ** fts3ExprLoadDoclists().
  112658. */
  112659. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  112660. int rc = SQLITE_OK;
  112661. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  112662. UNUSED_PARAMETER(iPhrase);
  112663. p->nPhrase++;
  112664. p->nToken += pExpr->pPhrase->nToken;
  112665. if( pExpr->isLoaded==0 ){
  112666. rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
  112667. pExpr->isLoaded = 1;
  112668. if( rc==SQLITE_OK ){
  112669. rc = fts3ExprNearTrim(pExpr);
  112670. }
  112671. }
  112672. return rc;
  112673. }
  112674. /*
  112675. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  112676. ** pCsr.
  112677. **
  112678. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  112679. ** phrases in the expression (all phrases except those directly or
  112680. ** indirectly descended from the right-hand-side of a NOT operator). If
  112681. ** pnToken is not NULL, then it is set to the number of tokens in all
  112682. ** matchable phrases of the expression.
  112683. */
  112684. static int fts3ExprLoadDoclists(
  112685. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  112686. int *pnPhrase, /* OUT: Number of phrases in query */
  112687. int *pnToken /* OUT: Number of tokens in query */
  112688. ){
  112689. int rc; /* Return Code */
  112690. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  112691. sCtx.pCsr = pCsr;
  112692. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  112693. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  112694. if( pnToken ) *pnToken = sCtx.nToken;
  112695. return rc;
  112696. }
  112697. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  112698. (*(int *)ctx)++;
  112699. UNUSED_PARAMETER(pExpr);
  112700. UNUSED_PARAMETER(iPhrase);
  112701. return SQLITE_OK;
  112702. }
  112703. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  112704. int nPhrase = 0;
  112705. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  112706. return nPhrase;
  112707. }
  112708. /*
  112709. ** Advance the position list iterator specified by the first two
  112710. ** arguments so that it points to the first element with a value greater
  112711. ** than or equal to parameter iNext.
  112712. */
  112713. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  112714. char *pIter = *ppIter;
  112715. if( pIter ){
  112716. int iIter = *piIter;
  112717. while( iIter<iNext ){
  112718. if( 0==(*pIter & 0xFE) ){
  112719. iIter = -1;
  112720. pIter = 0;
  112721. break;
  112722. }
  112723. fts3GetDeltaPosition(&pIter, &iIter);
  112724. }
  112725. *piIter = iIter;
  112726. *ppIter = pIter;
  112727. }
  112728. }
  112729. /*
  112730. ** Advance the snippet iterator to the next candidate snippet.
  112731. */
  112732. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  112733. int i; /* Loop counter */
  112734. if( pIter->iCurrent<0 ){
  112735. /* The SnippetIter object has just been initialized. The first snippet
  112736. ** candidate always starts at offset 0 (even if this candidate has a
  112737. ** score of 0.0).
  112738. */
  112739. pIter->iCurrent = 0;
  112740. /* Advance the 'head' iterator of each phrase to the first offset that
  112741. ** is greater than or equal to (iNext+nSnippet).
  112742. */
  112743. for(i=0; i<pIter->nPhrase; i++){
  112744. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  112745. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  112746. }
  112747. }else{
  112748. int iStart;
  112749. int iEnd = 0x7FFFFFFF;
  112750. for(i=0; i<pIter->nPhrase; i++){
  112751. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  112752. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  112753. iEnd = pPhrase->iHead;
  112754. }
  112755. }
  112756. if( iEnd==0x7FFFFFFF ){
  112757. return 1;
  112758. }
  112759. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  112760. for(i=0; i<pIter->nPhrase; i++){
  112761. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  112762. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  112763. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  112764. }
  112765. }
  112766. return 0;
  112767. }
  112768. /*
  112769. ** Retrieve information about the current candidate snippet of snippet
  112770. ** iterator pIter.
  112771. */
  112772. static void fts3SnippetDetails(
  112773. SnippetIter *pIter, /* Snippet iterator */
  112774. u64 mCovered, /* Bitmask of phrases already covered */
  112775. int *piToken, /* OUT: First token of proposed snippet */
  112776. int *piScore, /* OUT: "Score" for this snippet */
  112777. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  112778. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  112779. ){
  112780. int iStart = pIter->iCurrent; /* First token of snippet */
  112781. int iScore = 0; /* Score of this snippet */
  112782. int i; /* Loop counter */
  112783. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  112784. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  112785. for(i=0; i<pIter->nPhrase; i++){
  112786. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  112787. if( pPhrase->pTail ){
  112788. char *pCsr = pPhrase->pTail;
  112789. int iCsr = pPhrase->iTail;
  112790. while( iCsr<(iStart+pIter->nSnippet) ){
  112791. int j;
  112792. u64 mPhrase = (u64)1 << i;
  112793. u64 mPos = (u64)1 << (iCsr - iStart);
  112794. assert( iCsr>=iStart );
  112795. if( (mCover|mCovered)&mPhrase ){
  112796. iScore++;
  112797. }else{
  112798. iScore += 1000;
  112799. }
  112800. mCover |= mPhrase;
  112801. for(j=0; j<pPhrase->nToken; j++){
  112802. mHighlight |= (mPos>>j);
  112803. }
  112804. if( 0==(*pCsr & 0x0FE) ) break;
  112805. fts3GetDeltaPosition(&pCsr, &iCsr);
  112806. }
  112807. }
  112808. }
  112809. /* Set the output variables before returning. */
  112810. *piToken = iStart;
  112811. *piScore = iScore;
  112812. *pmCover = mCover;
  112813. *pmHighlight = mHighlight;
  112814. }
  112815. /*
  112816. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  112817. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  112818. */
  112819. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  112820. SnippetIter *p = (SnippetIter *)ctx;
  112821. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  112822. char *pCsr;
  112823. pPhrase->nToken = pExpr->pPhrase->nToken;
  112824. pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
  112825. if( pCsr ){
  112826. int iFirst = 0;
  112827. pPhrase->pList = pCsr;
  112828. fts3GetDeltaPosition(&pCsr, &iFirst);
  112829. pPhrase->pHead = pCsr;
  112830. pPhrase->pTail = pCsr;
  112831. pPhrase->iHead = iFirst;
  112832. pPhrase->iTail = iFirst;
  112833. }else{
  112834. assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
  112835. }
  112836. return SQLITE_OK;
  112837. }
  112838. /*
  112839. ** Select the fragment of text consisting of nFragment contiguous tokens
  112840. ** from column iCol that represent the "best" snippet. The best snippet
  112841. ** is the snippet with the highest score, where scores are calculated
  112842. ** by adding:
  112843. **
  112844. ** (a) +1 point for each occurence of a matchable phrase in the snippet.
  112845. **
  112846. ** (b) +1000 points for the first occurence of each matchable phrase in
  112847. ** the snippet for which the corresponding mCovered bit is not set.
  112848. **
  112849. ** The selected snippet parameters are stored in structure *pFragment before
  112850. ** returning. The score of the selected snippet is stored in *piScore
  112851. ** before returning.
  112852. */
  112853. static int fts3BestSnippet(
  112854. int nSnippet, /* Desired snippet length */
  112855. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  112856. int iCol, /* Index of column to create snippet from */
  112857. u64 mCovered, /* Mask of phrases already covered */
  112858. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  112859. SnippetFragment *pFragment, /* OUT: Best snippet found */
  112860. int *piScore /* OUT: Score of snippet pFragment */
  112861. ){
  112862. int rc; /* Return Code */
  112863. int nList; /* Number of phrases in expression */
  112864. SnippetIter sIter; /* Iterates through snippet candidates */
  112865. int nByte; /* Number of bytes of space to allocate */
  112866. int iBestScore = -1; /* Best snippet score found so far */
  112867. int i; /* Loop counter */
  112868. memset(&sIter, 0, sizeof(sIter));
  112869. /* Iterate through the phrases in the expression to count them. The same
  112870. ** callback makes sure the doclists are loaded for each phrase.
  112871. */
  112872. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  112873. if( rc!=SQLITE_OK ){
  112874. return rc;
  112875. }
  112876. /* Now that it is known how many phrases there are, allocate and zero
  112877. ** the required space using malloc().
  112878. */
  112879. nByte = sizeof(SnippetPhrase) * nList;
  112880. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  112881. if( !sIter.aPhrase ){
  112882. return SQLITE_NOMEM;
  112883. }
  112884. memset(sIter.aPhrase, 0, nByte);
  112885. /* Initialize the contents of the SnippetIter object. Then iterate through
  112886. ** the set of phrases in the expression to populate the aPhrase[] array.
  112887. */
  112888. sIter.pCsr = pCsr;
  112889. sIter.iCol = iCol;
  112890. sIter.nSnippet = nSnippet;
  112891. sIter.nPhrase = nList;
  112892. sIter.iCurrent = -1;
  112893. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  112894. /* Set the *pmSeen output variable. */
  112895. for(i=0; i<nList; i++){
  112896. if( sIter.aPhrase[i].pHead ){
  112897. *pmSeen |= (u64)1 << i;
  112898. }
  112899. }
  112900. /* Loop through all candidate snippets. Store the best snippet in
  112901. ** *pFragment. Store its associated 'score' in iBestScore.
  112902. */
  112903. pFragment->iCol = iCol;
  112904. while( !fts3SnippetNextCandidate(&sIter) ){
  112905. int iPos;
  112906. int iScore;
  112907. u64 mCover;
  112908. u64 mHighlight;
  112909. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  112910. assert( iScore>=0 );
  112911. if( iScore>iBestScore ){
  112912. pFragment->iPos = iPos;
  112913. pFragment->hlmask = mHighlight;
  112914. pFragment->covered = mCover;
  112915. iBestScore = iScore;
  112916. }
  112917. }
  112918. sqlite3_free(sIter.aPhrase);
  112919. *piScore = iBestScore;
  112920. return SQLITE_OK;
  112921. }
  112922. /*
  112923. ** Append a string to the string-buffer passed as the first argument.
  112924. **
  112925. ** If nAppend is negative, then the length of the string zAppend is
  112926. ** determined using strlen().
  112927. */
  112928. static int fts3StringAppend(
  112929. StrBuffer *pStr, /* Buffer to append to */
  112930. const char *zAppend, /* Pointer to data to append to buffer */
  112931. int nAppend /* Size of zAppend in bytes (or -1) */
  112932. ){
  112933. if( nAppend<0 ){
  112934. nAppend = (int)strlen(zAppend);
  112935. }
  112936. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  112937. ** to grow the buffer until so that it is big enough to accomadate the
  112938. ** appended data.
  112939. */
  112940. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  112941. int nAlloc = pStr->nAlloc+nAppend+100;
  112942. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  112943. if( !zNew ){
  112944. return SQLITE_NOMEM;
  112945. }
  112946. pStr->z = zNew;
  112947. pStr->nAlloc = nAlloc;
  112948. }
  112949. /* Append the data to the string buffer. */
  112950. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  112951. pStr->n += nAppend;
  112952. pStr->z[pStr->n] = '\0';
  112953. return SQLITE_OK;
  112954. }
  112955. /*
  112956. ** The fts3BestSnippet() function often selects snippets that end with a
  112957. ** query term. That is, the final term of the snippet is always a term
  112958. ** that requires highlighting. For example, if 'X' is a highlighted term
  112959. ** and '.' is a non-highlighted term, BestSnippet() may select:
  112960. **
  112961. ** ........X.....X
  112962. **
  112963. ** This function "shifts" the beginning of the snippet forward in the
  112964. ** document so that there are approximately the same number of
  112965. ** non-highlighted terms to the right of the final highlighted term as there
  112966. ** are to the left of the first highlighted term. For example, to this:
  112967. **
  112968. ** ....X.....X....
  112969. **
  112970. ** This is done as part of extracting the snippet text, not when selecting
  112971. ** the snippet. Snippet selection is done based on doclists only, so there
  112972. ** is no way for fts3BestSnippet() to know whether or not the document
  112973. ** actually contains terms that follow the final highlighted term.
  112974. */
  112975. static int fts3SnippetShift(
  112976. Fts3Table *pTab, /* FTS3 table snippet comes from */
  112977. int nSnippet, /* Number of tokens desired for snippet */
  112978. const char *zDoc, /* Document text to extract snippet from */
  112979. int nDoc, /* Size of buffer zDoc in bytes */
  112980. int *piPos, /* IN/OUT: First token of snippet */
  112981. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  112982. ){
  112983. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  112984. if( hlmask ){
  112985. int nLeft; /* Tokens to the left of first highlight */
  112986. int nRight; /* Tokens to the right of last highlight */
  112987. int nDesired; /* Ideal number of tokens to shift forward */
  112988. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  112989. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  112990. nDesired = (nLeft-nRight)/2;
  112991. /* Ideally, the start of the snippet should be pushed forward in the
  112992. ** document nDesired tokens. This block checks if there are actually
  112993. ** nDesired tokens to the right of the snippet. If so, *piPos and
  112994. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  112995. ** right. Otherwise, the snippet is shifted by the number of tokens
  112996. ** available.
  112997. */
  112998. if( nDesired>0 ){
  112999. int nShift; /* Number of tokens to shift snippet by */
  113000. int iCurrent = 0; /* Token counter */
  113001. int rc; /* Return Code */
  113002. sqlite3_tokenizer_module *pMod;
  113003. sqlite3_tokenizer_cursor *pC;
  113004. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  113005. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  113006. ** or more tokens in zDoc/nDoc.
  113007. */
  113008. rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
  113009. if( rc!=SQLITE_OK ){
  113010. return rc;
  113011. }
  113012. pC->pTokenizer = pTab->pTokenizer;
  113013. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  113014. const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
  113015. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  113016. }
  113017. pMod->xClose(pC);
  113018. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  113019. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  113020. assert( nShift<=nDesired );
  113021. if( nShift>0 ){
  113022. *piPos += nShift;
  113023. *pHlmask = hlmask >> nShift;
  113024. }
  113025. }
  113026. }
  113027. return SQLITE_OK;
  113028. }
  113029. /*
  113030. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  113031. ** append it to string buffer pOut.
  113032. */
  113033. static int fts3SnippetText(
  113034. Fts3Cursor *pCsr, /* FTS3 Cursor */
  113035. SnippetFragment *pFragment, /* Snippet to extract */
  113036. int iFragment, /* Fragment number */
  113037. int isLast, /* True for final fragment in snippet */
  113038. int nSnippet, /* Number of tokens in extracted snippet */
  113039. const char *zOpen, /* String inserted before highlighted term */
  113040. const char *zClose, /* String inserted after highlighted term */
  113041. const char *zEllipsis, /* String inserted between snippets */
  113042. StrBuffer *pOut /* Write output here */
  113043. ){
  113044. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113045. int rc; /* Return code */
  113046. const char *zDoc; /* Document text to extract snippet from */
  113047. int nDoc; /* Size of zDoc in bytes */
  113048. int iCurrent = 0; /* Current token number of document */
  113049. int iEnd = 0; /* Byte offset of end of current token */
  113050. int isShiftDone = 0; /* True after snippet is shifted */
  113051. int iPos = pFragment->iPos; /* First token of snippet */
  113052. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  113053. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  113054. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  113055. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  113056. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  113057. int DUMMY1; /* Dummy argument used with tokenizer */
  113058. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  113059. if( zDoc==0 ){
  113060. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  113061. return SQLITE_NOMEM;
  113062. }
  113063. return SQLITE_OK;
  113064. }
  113065. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  113066. /* Open a token cursor on the document. */
  113067. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  113068. rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
  113069. if( rc!=SQLITE_OK ){
  113070. return rc;
  113071. }
  113072. pC->pTokenizer = pTab->pTokenizer;
  113073. while( rc==SQLITE_OK ){
  113074. int iBegin; /* Offset in zDoc of start of token */
  113075. int iFin; /* Offset in zDoc of end of token */
  113076. int isHighlight; /* True for highlighted terms */
  113077. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  113078. if( rc!=SQLITE_OK ){
  113079. if( rc==SQLITE_DONE ){
  113080. /* Special case - the last token of the snippet is also the last token
  113081. ** of the column. Append any punctuation that occurred between the end
  113082. ** of the previous token and the end of the document to the output.
  113083. ** Then break out of the loop. */
  113084. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  113085. }
  113086. break;
  113087. }
  113088. if( iCurrent<iPos ){ continue; }
  113089. if( !isShiftDone ){
  113090. int n = nDoc - iBegin;
  113091. rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
  113092. isShiftDone = 1;
  113093. /* Now that the shift has been done, check if the initial "..." are
  113094. ** required. They are required if (a) this is not the first fragment,
  113095. ** or (b) this fragment does not begin at position 0 of its column.
  113096. */
  113097. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  113098. rc = fts3StringAppend(pOut, zEllipsis, -1);
  113099. }
  113100. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  113101. }
  113102. if( iCurrent>=(iPos+nSnippet) ){
  113103. if( isLast ){
  113104. rc = fts3StringAppend(pOut, zEllipsis, -1);
  113105. }
  113106. break;
  113107. }
  113108. /* Set isHighlight to true if this term should be highlighted. */
  113109. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  113110. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  113111. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  113112. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  113113. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  113114. iEnd = iFin;
  113115. }
  113116. pMod->xClose(pC);
  113117. return rc;
  113118. }
  113119. /*
  113120. ** This function is used to count the entries in a column-list (a
  113121. ** delta-encoded list of term offsets within a single column of a single
  113122. ** row). When this function is called, *ppCollist should point to the
  113123. ** beginning of the first varint in the column-list (the varint that
  113124. ** contains the position of the first matching term in the column data).
  113125. ** Before returning, *ppCollist is set to point to the first byte after
  113126. ** the last varint in the column-list (either the 0x00 signifying the end
  113127. ** of the position-list, or the 0x01 that precedes the column number of
  113128. ** the next column in the position-list).
  113129. **
  113130. ** The number of elements in the column-list is returned.
  113131. */
  113132. static int fts3ColumnlistCount(char **ppCollist){
  113133. char *pEnd = *ppCollist;
  113134. char c = 0;
  113135. int nEntry = 0;
  113136. /* A column-list is terminated by either a 0x01 or 0x00. */
  113137. while( 0xFE & (*pEnd | c) ){
  113138. c = *pEnd++ & 0x80;
  113139. if( !c ) nEntry++;
  113140. }
  113141. *ppCollist = pEnd;
  113142. return nEntry;
  113143. }
  113144. static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
  113145. char *pCsr = *pp;
  113146. while( *pCsr ){
  113147. int nHit;
  113148. sqlite3_int64 iCol = 0;
  113149. if( *pCsr==0x01 ){
  113150. pCsr++;
  113151. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  113152. }
  113153. nHit = fts3ColumnlistCount(&pCsr);
  113154. assert( nHit>0 );
  113155. if( isGlobal ){
  113156. aOut[iCol*3+1]++;
  113157. }
  113158. aOut[iCol*3] += nHit;
  113159. }
  113160. pCsr++;
  113161. *pp = pCsr;
  113162. }
  113163. /*
  113164. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  113165. ** for a single query.
  113166. **
  113167. ** fts3ExprIterate() callback to load the 'global' elements of a
  113168. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  113169. ** of the matchinfo array that are constant for all rows returned by the
  113170. ** current query.
  113171. **
  113172. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  113173. ** function populates Matchinfo.aMatchinfo[] as follows:
  113174. **
  113175. ** for(iCol=0; iCol<nCol; iCol++){
  113176. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  113177. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  113178. ** }
  113179. **
  113180. ** where X is the number of matches for phrase iPhrase is column iCol of all
  113181. ** rows of the table. Y is the number of rows for which column iCol contains
  113182. ** at least one instance of phrase iPhrase.
  113183. **
  113184. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  113185. ** Y values are set to nDoc, where nDoc is the number of documents in the
  113186. ** file system. This is done because the full-text index doclist is required
  113187. ** to calculate these values properly, and the full-text index doclist is
  113188. ** not available for deferred tokens.
  113189. */
  113190. static int fts3ExprGlobalHitsCb(
  113191. Fts3Expr *pExpr, /* Phrase expression node */
  113192. int iPhrase, /* Phrase number (numbered from zero) */
  113193. void *pCtx /* Pointer to MatchInfo structure */
  113194. ){
  113195. MatchInfo *p = (MatchInfo *)pCtx;
  113196. Fts3Cursor *pCsr = p->pCursor;
  113197. char *pIter;
  113198. char *pEnd;
  113199. char *pFree = 0;
  113200. u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
  113201. assert( pExpr->isLoaded );
  113202. assert( pExpr->eType==FTSQUERY_PHRASE );
  113203. if( pCsr->pDeferred ){
  113204. Fts3Phrase *pPhrase = pExpr->pPhrase;
  113205. int ii;
  113206. for(ii=0; ii<pPhrase->nToken; ii++){
  113207. if( pPhrase->aToken[ii].bFulltext ) break;
  113208. }
  113209. if( ii<pPhrase->nToken ){
  113210. int nFree = 0;
  113211. int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
  113212. if( rc!=SQLITE_OK ) return rc;
  113213. pIter = pFree;
  113214. pEnd = &pFree[nFree];
  113215. }else{
  113216. int iCol; /* Column index */
  113217. for(iCol=0; iCol<p->nCol; iCol++){
  113218. aOut[iCol*3 + 1] = (u32)p->nDoc;
  113219. aOut[iCol*3 + 2] = (u32)p->nDoc;
  113220. }
  113221. return SQLITE_OK;
  113222. }
  113223. }else{
  113224. pIter = pExpr->aDoclist;
  113225. pEnd = &pExpr->aDoclist[pExpr->nDoclist];
  113226. }
  113227. /* Fill in the global hit count matrix row for this phrase. */
  113228. while( pIter<pEnd ){
  113229. while( *pIter++ & 0x80 ); /* Skip past docid. */
  113230. fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
  113231. }
  113232. sqlite3_free(pFree);
  113233. return SQLITE_OK;
  113234. }
  113235. /*
  113236. ** fts3ExprIterate() callback used to collect the "local" part of the
  113237. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  113238. ** array that are different for each row returned by the query.
  113239. */
  113240. static int fts3ExprLocalHitsCb(
  113241. Fts3Expr *pExpr, /* Phrase expression node */
  113242. int iPhrase, /* Phrase number */
  113243. void *pCtx /* Pointer to MatchInfo structure */
  113244. ){
  113245. MatchInfo *p = (MatchInfo *)pCtx;
  113246. int iStart = iPhrase * p->nCol * 3;
  113247. int i;
  113248. for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
  113249. if( pExpr->aDoclist ){
  113250. char *pCsr;
  113251. pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
  113252. if( pCsr ){
  113253. fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
  113254. }
  113255. }
  113256. return SQLITE_OK;
  113257. }
  113258. static int fts3MatchinfoCheck(
  113259. Fts3Table *pTab,
  113260. char cArg,
  113261. char **pzErr
  113262. ){
  113263. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  113264. || (cArg==FTS3_MATCHINFO_NCOL)
  113265. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
  113266. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
  113267. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  113268. || (cArg==FTS3_MATCHINFO_LCS)
  113269. || (cArg==FTS3_MATCHINFO_HITS)
  113270. ){
  113271. return SQLITE_OK;
  113272. }
  113273. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  113274. return SQLITE_ERROR;
  113275. }
  113276. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  113277. int nVal; /* Number of integers output by cArg */
  113278. switch( cArg ){
  113279. case FTS3_MATCHINFO_NDOC:
  113280. case FTS3_MATCHINFO_NPHRASE:
  113281. case FTS3_MATCHINFO_NCOL:
  113282. nVal = 1;
  113283. break;
  113284. case FTS3_MATCHINFO_AVGLENGTH:
  113285. case FTS3_MATCHINFO_LENGTH:
  113286. case FTS3_MATCHINFO_LCS:
  113287. nVal = pInfo->nCol;
  113288. break;
  113289. default:
  113290. assert( cArg==FTS3_MATCHINFO_HITS );
  113291. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  113292. break;
  113293. }
  113294. return nVal;
  113295. }
  113296. static int fts3MatchinfoSelectDoctotal(
  113297. Fts3Table *pTab,
  113298. sqlite3_stmt **ppStmt,
  113299. sqlite3_int64 *pnDoc,
  113300. const char **paLen
  113301. ){
  113302. sqlite3_stmt *pStmt;
  113303. const char *a;
  113304. sqlite3_int64 nDoc;
  113305. if( !*ppStmt ){
  113306. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  113307. if( rc!=SQLITE_OK ) return rc;
  113308. }
  113309. pStmt = *ppStmt;
  113310. assert( sqlite3_data_count(pStmt)==1 );
  113311. a = sqlite3_column_blob(pStmt, 0);
  113312. a += sqlite3Fts3GetVarint(a, &nDoc);
  113313. if( nDoc==0 ) return SQLITE_CORRUPT;
  113314. *pnDoc = (u32)nDoc;
  113315. if( paLen ) *paLen = a;
  113316. return SQLITE_OK;
  113317. }
  113318. /*
  113319. ** An instance of the following structure is used to store state while
  113320. ** iterating through a multi-column position-list corresponding to the
  113321. ** hits for a single phrase on a single row in order to calculate the
  113322. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  113323. */
  113324. typedef struct LcsIterator LcsIterator;
  113325. struct LcsIterator {
  113326. Fts3Expr *pExpr; /* Pointer to phrase expression */
  113327. char *pRead; /* Cursor used to iterate through aDoclist */
  113328. int iPosOffset; /* Tokens count up to end of this phrase */
  113329. int iCol; /* Current column number */
  113330. int iPos; /* Current position */
  113331. };
  113332. /*
  113333. ** If LcsIterator.iCol is set to the following value, the iterator has
  113334. ** finished iterating through all offsets for all columns.
  113335. */
  113336. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  113337. static int fts3MatchinfoLcsCb(
  113338. Fts3Expr *pExpr, /* Phrase expression node */
  113339. int iPhrase, /* Phrase number (numbered from zero) */
  113340. void *pCtx /* Pointer to MatchInfo structure */
  113341. ){
  113342. LcsIterator *aIter = (LcsIterator *)pCtx;
  113343. aIter[iPhrase].pExpr = pExpr;
  113344. return SQLITE_OK;
  113345. }
  113346. /*
  113347. ** Advance the iterator passed as an argument to the next position. Return
  113348. ** 1 if the iterator is at EOF or if it now points to the start of the
  113349. ** position list for the next column.
  113350. */
  113351. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  113352. char *pRead = pIter->pRead;
  113353. sqlite3_int64 iRead;
  113354. int rc = 0;
  113355. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  113356. if( iRead==0 ){
  113357. pIter->iCol = LCS_ITERATOR_FINISHED;
  113358. rc = 1;
  113359. }else{
  113360. if( iRead==1 ){
  113361. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  113362. pIter->iCol = (int)iRead;
  113363. pIter->iPos = pIter->iPosOffset;
  113364. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  113365. rc = 1;
  113366. }
  113367. pIter->iPos += (int)(iRead-2);
  113368. }
  113369. pIter->pRead = pRead;
  113370. return rc;
  113371. }
  113372. /*
  113373. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  113374. **
  113375. ** If the call is successful, the longest-common-substring lengths for each
  113376. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  113377. ** array before returning. SQLITE_OK is returned in this case.
  113378. **
  113379. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  113380. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  113381. ** undefined.
  113382. */
  113383. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  113384. LcsIterator *aIter;
  113385. int i;
  113386. int iCol;
  113387. int nToken = 0;
  113388. /* Allocate and populate the array of LcsIterator objects. The array
  113389. ** contains one element for each matchable phrase in the query.
  113390. **/
  113391. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  113392. if( !aIter ) return SQLITE_NOMEM;
  113393. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  113394. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  113395. for(i=0; i<pInfo->nPhrase; i++){
  113396. LcsIterator *pIter = &aIter[i];
  113397. nToken -= pIter->pExpr->pPhrase->nToken;
  113398. pIter->iPosOffset = nToken;
  113399. pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
  113400. if( pIter->pRead ){
  113401. pIter->iPos = pIter->iPosOffset;
  113402. fts3LcsIteratorAdvance(&aIter[i]);
  113403. }else{
  113404. pIter->iCol = LCS_ITERATOR_FINISHED;
  113405. }
  113406. }
  113407. for(iCol=0; iCol<pInfo->nCol; iCol++){
  113408. int nLcs = 0; /* LCS value for this column */
  113409. int nLive = 0; /* Number of iterators in aIter not at EOF */
  113410. /* Loop through the iterators in aIter[]. Set nLive to the number of
  113411. ** iterators that point to a position-list corresponding to column iCol.
  113412. */
  113413. for(i=0; i<pInfo->nPhrase; i++){
  113414. assert( aIter[i].iCol>=iCol );
  113415. if( aIter[i].iCol==iCol ) nLive++;
  113416. }
  113417. /* The following loop runs until all iterators in aIter[] have finished
  113418. ** iterating through positions in column iCol. Exactly one of the
  113419. ** iterators is advanced each time the body of the loop is run.
  113420. */
  113421. while( nLive>0 ){
  113422. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  113423. int nThisLcs = 0; /* LCS for the current iterator positions */
  113424. for(i=0; i<pInfo->nPhrase; i++){
  113425. LcsIterator *pIter = &aIter[i];
  113426. if( iCol!=pIter->iCol ){
  113427. /* This iterator is already at EOF for this column. */
  113428. nThisLcs = 0;
  113429. }else{
  113430. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  113431. pAdv = pIter;
  113432. }
  113433. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  113434. nThisLcs++;
  113435. }else{
  113436. nThisLcs = 1;
  113437. }
  113438. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  113439. }
  113440. }
  113441. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  113442. }
  113443. pInfo->aMatchinfo[iCol] = nLcs;
  113444. }
  113445. sqlite3_free(aIter);
  113446. return SQLITE_OK;
  113447. }
  113448. /*
  113449. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  113450. ** be returned by the matchinfo() function. Argument zArg contains the
  113451. ** format string passed as the second argument to matchinfo (or the
  113452. ** default value "pcx" if no second argument was specified). The format
  113453. ** string has already been validated and the pInfo->aMatchinfo[] array
  113454. ** is guaranteed to be large enough for the output.
  113455. **
  113456. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  113457. ** If it is false, then assume that those fields that do not change between
  113458. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  113459. ** have already been populated.
  113460. **
  113461. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  113462. ** occurs. If a value other than SQLITE_OK is returned, the state the
  113463. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  113464. */
  113465. static int fts3MatchinfoValues(
  113466. Fts3Cursor *pCsr, /* FTS3 cursor object */
  113467. int bGlobal, /* True to grab the global stats */
  113468. MatchInfo *pInfo, /* Matchinfo context object */
  113469. const char *zArg /* Matchinfo format string */
  113470. ){
  113471. int rc = SQLITE_OK;
  113472. int i;
  113473. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113474. sqlite3_stmt *pSelect = 0;
  113475. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  113476. switch( zArg[i] ){
  113477. case FTS3_MATCHINFO_NPHRASE:
  113478. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  113479. break;
  113480. case FTS3_MATCHINFO_NCOL:
  113481. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  113482. break;
  113483. case FTS3_MATCHINFO_NDOC:
  113484. if( bGlobal ){
  113485. sqlite3_int64 nDoc;
  113486. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  113487. pInfo->aMatchinfo[0] = (u32)nDoc;
  113488. }
  113489. break;
  113490. case FTS3_MATCHINFO_AVGLENGTH:
  113491. if( bGlobal ){
  113492. sqlite3_int64 nDoc; /* Number of rows in table */
  113493. const char *a; /* Aggregate column length array */
  113494. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  113495. if( rc==SQLITE_OK ){
  113496. int iCol;
  113497. for(iCol=0; iCol<pInfo->nCol; iCol++){
  113498. u32 iVal;
  113499. sqlite3_int64 nToken;
  113500. a += sqlite3Fts3GetVarint(a, &nToken);
  113501. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  113502. pInfo->aMatchinfo[iCol] = iVal;
  113503. }
  113504. }
  113505. }
  113506. break;
  113507. case FTS3_MATCHINFO_LENGTH: {
  113508. sqlite3_stmt *pSelectDocsize = 0;
  113509. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  113510. if( rc==SQLITE_OK ){
  113511. int iCol;
  113512. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  113513. for(iCol=0; iCol<pInfo->nCol; iCol++){
  113514. sqlite3_int64 nToken;
  113515. a += sqlite3Fts3GetVarint(a, &nToken);
  113516. pInfo->aMatchinfo[iCol] = (u32)nToken;
  113517. }
  113518. }
  113519. sqlite3_reset(pSelectDocsize);
  113520. break;
  113521. }
  113522. case FTS3_MATCHINFO_LCS:
  113523. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  113524. if( rc==SQLITE_OK ){
  113525. rc = fts3MatchinfoLcs(pCsr, pInfo);
  113526. }
  113527. break;
  113528. default: {
  113529. Fts3Expr *pExpr;
  113530. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  113531. pExpr = pCsr->pExpr;
  113532. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  113533. if( rc!=SQLITE_OK ) break;
  113534. if( bGlobal ){
  113535. if( pCsr->pDeferred ){
  113536. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  113537. if( rc!=SQLITE_OK ) break;
  113538. }
  113539. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  113540. if( rc!=SQLITE_OK ) break;
  113541. }
  113542. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  113543. break;
  113544. }
  113545. }
  113546. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  113547. }
  113548. sqlite3_reset(pSelect);
  113549. return rc;
  113550. }
  113551. /*
  113552. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  113553. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  113554. */
  113555. static int fts3GetMatchinfo(
  113556. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  113557. const char *zArg /* Second argument to matchinfo() function */
  113558. ){
  113559. MatchInfo sInfo;
  113560. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113561. int rc = SQLITE_OK;
  113562. int bGlobal = 0; /* Collect 'global' stats as well as local */
  113563. memset(&sInfo, 0, sizeof(MatchInfo));
  113564. sInfo.pCursor = pCsr;
  113565. sInfo.nCol = pTab->nColumn;
  113566. /* If there is cached matchinfo() data, but the format string for the
  113567. ** cache does not match the format string for this request, discard
  113568. ** the cached data. */
  113569. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  113570. assert( pCsr->aMatchinfo );
  113571. sqlite3_free(pCsr->aMatchinfo);
  113572. pCsr->zMatchinfo = 0;
  113573. pCsr->aMatchinfo = 0;
  113574. }
  113575. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  113576. ** matchinfo function has been called for this query. In this case
  113577. ** allocate the array used to accumulate the matchinfo data and
  113578. ** initialize those elements that are constant for every row.
  113579. */
  113580. if( pCsr->aMatchinfo==0 ){
  113581. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  113582. int nArg; /* Bytes in zArg */
  113583. int i; /* Used to iterate through zArg */
  113584. /* Determine the number of phrases in the query */
  113585. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  113586. sInfo.nPhrase = pCsr->nPhrase;
  113587. /* Determine the number of integers in the buffer returned by this call. */
  113588. for(i=0; zArg[i]; i++){
  113589. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  113590. }
  113591. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  113592. nArg = (int)strlen(zArg);
  113593. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  113594. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  113595. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  113596. pCsr->nMatchinfo = nMatchinfo;
  113597. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  113598. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  113599. pCsr->isMatchinfoNeeded = 1;
  113600. bGlobal = 1;
  113601. }
  113602. sInfo.aMatchinfo = pCsr->aMatchinfo;
  113603. sInfo.nPhrase = pCsr->nPhrase;
  113604. if( pCsr->isMatchinfoNeeded ){
  113605. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  113606. pCsr->isMatchinfoNeeded = 0;
  113607. }
  113608. return rc;
  113609. }
  113610. /*
  113611. ** Implementation of snippet() function.
  113612. */
  113613. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  113614. sqlite3_context *pCtx, /* SQLite function call context */
  113615. Fts3Cursor *pCsr, /* Cursor object */
  113616. const char *zStart, /* Snippet start text - "<b>" */
  113617. const char *zEnd, /* Snippet end text - "</b>" */
  113618. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  113619. int iCol, /* Extract snippet from this column */
  113620. int nToken /* Approximate number of tokens in snippet */
  113621. ){
  113622. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113623. int rc = SQLITE_OK;
  113624. int i;
  113625. StrBuffer res = {0, 0, 0};
  113626. /* The returned text includes up to four fragments of text extracted from
  113627. ** the data in the current row. The first iteration of the for(...) loop
  113628. ** below attempts to locate a single fragment of text nToken tokens in
  113629. ** size that contains at least one instance of all phrases in the query
  113630. ** expression that appear in the current row. If such a fragment of text
  113631. ** cannot be found, the second iteration of the loop attempts to locate
  113632. ** a pair of fragments, and so on.
  113633. */
  113634. int nSnippet = 0; /* Number of fragments in this snippet */
  113635. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  113636. int nFToken = -1; /* Number of tokens in each fragment */
  113637. if( !pCsr->pExpr ){
  113638. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  113639. return;
  113640. }
  113641. for(nSnippet=1; 1; nSnippet++){
  113642. int iSnip; /* Loop counter 0..nSnippet-1 */
  113643. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  113644. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  113645. if( nToken>=0 ){
  113646. nFToken = (nToken+nSnippet-1) / nSnippet;
  113647. }else{
  113648. nFToken = -1 * nToken;
  113649. }
  113650. for(iSnip=0; iSnip<nSnippet; iSnip++){
  113651. int iBestScore = -1; /* Best score of columns checked so far */
  113652. int iRead; /* Used to iterate through columns */
  113653. SnippetFragment *pFragment = &aSnippet[iSnip];
  113654. memset(pFragment, 0, sizeof(*pFragment));
  113655. /* Loop through all columns of the table being considered for snippets.
  113656. ** If the iCol argument to this function was negative, this means all
  113657. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  113658. */
  113659. for(iRead=0; iRead<pTab->nColumn; iRead++){
  113660. SnippetFragment sF = {0, 0, 0, 0};
  113661. int iS;
  113662. if( iCol>=0 && iRead!=iCol ) continue;
  113663. /* Find the best snippet of nFToken tokens in column iRead. */
  113664. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  113665. if( rc!=SQLITE_OK ){
  113666. goto snippet_out;
  113667. }
  113668. if( iS>iBestScore ){
  113669. *pFragment = sF;
  113670. iBestScore = iS;
  113671. }
  113672. }
  113673. mCovered |= pFragment->covered;
  113674. }
  113675. /* If all query phrases seen by fts3BestSnippet() are present in at least
  113676. ** one of the nSnippet snippet fragments, break out of the loop.
  113677. */
  113678. assert( (mCovered&mSeen)==mCovered );
  113679. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  113680. }
  113681. assert( nFToken>0 );
  113682. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  113683. rc = fts3SnippetText(pCsr, &aSnippet[i],
  113684. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  113685. );
  113686. }
  113687. snippet_out:
  113688. sqlite3Fts3SegmentsClose(pTab);
  113689. if( rc!=SQLITE_OK ){
  113690. sqlite3_result_error_code(pCtx, rc);
  113691. sqlite3_free(res.z);
  113692. }else{
  113693. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  113694. }
  113695. }
  113696. typedef struct TermOffset TermOffset;
  113697. typedef struct TermOffsetCtx TermOffsetCtx;
  113698. struct TermOffset {
  113699. char *pList; /* Position-list */
  113700. int iPos; /* Position just read from pList */
  113701. int iOff; /* Offset of this term from read positions */
  113702. };
  113703. struct TermOffsetCtx {
  113704. int iCol; /* Column of table to populate aTerm for */
  113705. int iTerm;
  113706. sqlite3_int64 iDocid;
  113707. TermOffset *aTerm;
  113708. };
  113709. /*
  113710. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  113711. */
  113712. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  113713. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  113714. int nTerm; /* Number of tokens in phrase */
  113715. int iTerm; /* For looping through nTerm phrase terms */
  113716. char *pList; /* Pointer to position list for phrase */
  113717. int iPos = 0; /* First position in position-list */
  113718. UNUSED_PARAMETER(iPhrase);
  113719. pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
  113720. nTerm = pExpr->pPhrase->nToken;
  113721. if( pList ){
  113722. fts3GetDeltaPosition(&pList, &iPos);
  113723. assert( iPos>=0 );
  113724. }
  113725. for(iTerm=0; iTerm<nTerm; iTerm++){
  113726. TermOffset *pT = &p->aTerm[p->iTerm++];
  113727. pT->iOff = nTerm-iTerm-1;
  113728. pT->pList = pList;
  113729. pT->iPos = iPos;
  113730. }
  113731. return SQLITE_OK;
  113732. }
  113733. /*
  113734. ** Implementation of offsets() function.
  113735. */
  113736. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  113737. sqlite3_context *pCtx, /* SQLite function call context */
  113738. Fts3Cursor *pCsr /* Cursor object */
  113739. ){
  113740. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113741. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  113742. const char *ZDUMMY; /* Dummy argument used with xNext() */
  113743. int NDUMMY; /* Dummy argument used with xNext() */
  113744. int rc; /* Return Code */
  113745. int nToken; /* Number of tokens in query */
  113746. int iCol; /* Column currently being processed */
  113747. StrBuffer res = {0, 0, 0}; /* Result string */
  113748. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  113749. if( !pCsr->pExpr ){
  113750. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  113751. return;
  113752. }
  113753. memset(&sCtx, 0, sizeof(sCtx));
  113754. assert( pCsr->isRequireSeek==0 );
  113755. /* Count the number of terms in the query */
  113756. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  113757. if( rc!=SQLITE_OK ) goto offsets_out;
  113758. /* Allocate the array of TermOffset iterators. */
  113759. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  113760. if( 0==sCtx.aTerm ){
  113761. rc = SQLITE_NOMEM;
  113762. goto offsets_out;
  113763. }
  113764. sCtx.iDocid = pCsr->iPrevId;
  113765. /* Loop through the table columns, appending offset information to
  113766. ** string-buffer res for each column.
  113767. */
  113768. for(iCol=0; iCol<pTab->nColumn; iCol++){
  113769. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  113770. int iStart;
  113771. int iEnd;
  113772. int iCurrent;
  113773. const char *zDoc;
  113774. int nDoc;
  113775. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  113776. ** no way that this operation can fail, so the return code from
  113777. ** fts3ExprIterate() can be discarded.
  113778. */
  113779. sCtx.iCol = iCol;
  113780. sCtx.iTerm = 0;
  113781. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  113782. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  113783. ** in column iCol, jump immediately to the next iteration of the loop.
  113784. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  113785. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  113786. ** to the caller.
  113787. */
  113788. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  113789. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  113790. if( zDoc==0 ){
  113791. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  113792. continue;
  113793. }
  113794. rc = SQLITE_NOMEM;
  113795. goto offsets_out;
  113796. }
  113797. /* Initialize a tokenizer iterator to iterate through column iCol. */
  113798. rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
  113799. if( rc!=SQLITE_OK ) goto offsets_out;
  113800. pC->pTokenizer = pTab->pTokenizer;
  113801. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  113802. while( rc==SQLITE_OK ){
  113803. int i; /* Used to loop through terms */
  113804. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  113805. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  113806. for(i=0; i<nToken; i++){
  113807. TermOffset *pT = &sCtx.aTerm[i];
  113808. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  113809. iMinPos = pT->iPos-pT->iOff;
  113810. pTerm = pT;
  113811. }
  113812. }
  113813. if( !pTerm ){
  113814. /* All offsets for this column have been gathered. */
  113815. break;
  113816. }else{
  113817. assert( iCurrent<=iMinPos );
  113818. if( 0==(0xFE&*pTerm->pList) ){
  113819. pTerm->pList = 0;
  113820. }else{
  113821. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  113822. }
  113823. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  113824. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  113825. }
  113826. if( rc==SQLITE_OK ){
  113827. char aBuffer[64];
  113828. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  113829. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  113830. );
  113831. rc = fts3StringAppend(&res, aBuffer, -1);
  113832. }else if( rc==SQLITE_DONE ){
  113833. rc = SQLITE_CORRUPT;
  113834. }
  113835. }
  113836. }
  113837. if( rc==SQLITE_DONE ){
  113838. rc = SQLITE_OK;
  113839. }
  113840. pMod->xClose(pC);
  113841. if( rc!=SQLITE_OK ) goto offsets_out;
  113842. }
  113843. offsets_out:
  113844. sqlite3_free(sCtx.aTerm);
  113845. assert( rc!=SQLITE_DONE );
  113846. sqlite3Fts3SegmentsClose(pTab);
  113847. if( rc!=SQLITE_OK ){
  113848. sqlite3_result_error_code(pCtx, rc);
  113849. sqlite3_free(res.z);
  113850. }else{
  113851. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  113852. }
  113853. return;
  113854. }
  113855. /*
  113856. ** Implementation of matchinfo() function.
  113857. */
  113858. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  113859. sqlite3_context *pContext, /* Function call context */
  113860. Fts3Cursor *pCsr, /* FTS3 table cursor */
  113861. const char *zArg /* Second arg to matchinfo() function */
  113862. ){
  113863. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  113864. int rc;
  113865. int i;
  113866. const char *zFormat;
  113867. if( zArg ){
  113868. for(i=0; zArg[i]; i++){
  113869. char *zErr = 0;
  113870. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  113871. sqlite3_result_error(pContext, zErr, -1);
  113872. sqlite3_free(zErr);
  113873. return;
  113874. }
  113875. }
  113876. zFormat = zArg;
  113877. }else{
  113878. zFormat = FTS3_MATCHINFO_DEFAULT;
  113879. }
  113880. if( !pCsr->pExpr ){
  113881. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  113882. return;
  113883. }
  113884. /* Retrieve matchinfo() data. */
  113885. rc = fts3GetMatchinfo(pCsr, zFormat);
  113886. sqlite3Fts3SegmentsClose(pTab);
  113887. if( rc!=SQLITE_OK ){
  113888. sqlite3_result_error_code(pContext, rc);
  113889. }else{
  113890. int n = pCsr->nMatchinfo * sizeof(u32);
  113891. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  113892. }
  113893. }
  113894. #endif
  113895. /************** End of fts3_snippet.c ****************************************/
  113896. /************** Begin file rtree.c *******************************************/
  113897. /*
  113898. ** 2001 September 15
  113899. **
  113900. ** The author disclaims copyright to this source code. In place of
  113901. ** a legal notice, here is a blessing:
  113902. **
  113903. ** May you do good and not evil.
  113904. ** May you find forgiveness for yourself and forgive others.
  113905. ** May you share freely, never taking more than you give.
  113906. **
  113907. *************************************************************************
  113908. ** This file contains code for implementations of the r-tree and r*-tree
  113909. ** algorithms packaged as an SQLite virtual table module.
  113910. */
  113911. /*
  113912. ** Database Format of R-Tree Tables
  113913. ** --------------------------------
  113914. **
  113915. ** The data structure for a single virtual r-tree table is stored in three
  113916. ** native SQLite tables declared as follows. In each case, the '%' character
  113917. ** in the table name is replaced with the user-supplied name of the r-tree
  113918. ** table.
  113919. **
  113920. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  113921. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  113922. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  113923. **
  113924. ** The data for each node of the r-tree structure is stored in the %_node
  113925. ** table. For each node that is not the root node of the r-tree, there is
  113926. ** an entry in the %_parent table associating the node with its parent.
  113927. ** And for each row of data in the table, there is an entry in the %_rowid
  113928. ** table that maps from the entries rowid to the id of the node that it
  113929. ** is stored on.
  113930. **
  113931. ** The root node of an r-tree always exists, even if the r-tree table is
  113932. ** empty. The nodeno of the root node is always 1. All other nodes in the
  113933. ** table must be the same size as the root node. The content of each node
  113934. ** is formatted as follows:
  113935. **
  113936. ** 1. If the node is the root node (node 1), then the first 2 bytes
  113937. ** of the node contain the tree depth as a big-endian integer.
  113938. ** For non-root nodes, the first 2 bytes are left unused.
  113939. **
  113940. ** 2. The next 2 bytes contain the number of entries currently
  113941. ** stored in the node.
  113942. **
  113943. ** 3. The remainder of the node contains the node entries. Each entry
  113944. ** consists of a single 8-byte integer followed by an even number
  113945. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  113946. ** of a record. For internal nodes it is the node number of a
  113947. ** child page.
  113948. */
  113949. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  113950. /*
  113951. ** This file contains an implementation of a couple of different variants
  113952. ** of the r-tree algorithm. See the README file for further details. The
  113953. ** same data-structure is used for all, but the algorithms for insert and
  113954. ** delete operations vary. The variants used are selected at compile time
  113955. ** by defining the following symbols:
  113956. */
  113957. /* Either, both or none of the following may be set to activate
  113958. ** r*tree variant algorithms.
  113959. */
  113960. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  113961. #define VARIANT_RSTARTREE_REINSERT 1
  113962. /*
  113963. ** Exactly one of the following must be set to 1.
  113964. */
  113965. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  113966. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  113967. #define VARIANT_RSTARTREE_SPLIT 1
  113968. #define VARIANT_GUTTMAN_SPLIT \
  113969. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  113970. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  113971. #define PickNext QuadraticPickNext
  113972. #define PickSeeds QuadraticPickSeeds
  113973. #define AssignCells splitNodeGuttman
  113974. #endif
  113975. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  113976. #define PickNext LinearPickNext
  113977. #define PickSeeds LinearPickSeeds
  113978. #define AssignCells splitNodeGuttman
  113979. #endif
  113980. #if VARIANT_RSTARTREE_SPLIT
  113981. #define AssignCells splitNodeStartree
  113982. #endif
  113983. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  113984. # define NDEBUG 1
  113985. #endif
  113986. #ifndef SQLITE_CORE
  113987. SQLITE_EXTENSION_INIT1
  113988. #else
  113989. #endif
  113990. #ifndef SQLITE_AMALGAMATION
  113991. #include "sqlite3rtree.h"
  113992. typedef sqlite3_int64 i64;
  113993. typedef unsigned char u8;
  113994. typedef unsigned int u32;
  113995. #endif
  113996. /* The following macro is used to suppress compiler warnings.
  113997. */
  113998. #ifndef UNUSED_PARAMETER
  113999. # define UNUSED_PARAMETER(x) (void)(x)
  114000. #endif
  114001. typedef struct Rtree Rtree;
  114002. typedef struct RtreeCursor RtreeCursor;
  114003. typedef struct RtreeNode RtreeNode;
  114004. typedef struct RtreeCell RtreeCell;
  114005. typedef struct RtreeConstraint RtreeConstraint;
  114006. typedef struct RtreeMatchArg RtreeMatchArg;
  114007. typedef struct RtreeGeomCallback RtreeGeomCallback;
  114008. typedef union RtreeCoord RtreeCoord;
  114009. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  114010. #define RTREE_MAX_DIMENSIONS 5
  114011. /* Size of hash table Rtree.aHash. This hash table is not expected to
  114012. ** ever contain very many entries, so a fixed number of buckets is
  114013. ** used.
  114014. */
  114015. #define HASHSIZE 128
  114016. /*
  114017. ** An rtree virtual-table object.
  114018. */
  114019. struct Rtree {
  114020. sqlite3_vtab base;
  114021. sqlite3 *db; /* Host database connection */
  114022. int iNodeSize; /* Size in bytes of each node in the node table */
  114023. int nDim; /* Number of dimensions */
  114024. int nBytesPerCell; /* Bytes consumed per cell */
  114025. int iDepth; /* Current depth of the r-tree structure */
  114026. char *zDb; /* Name of database containing r-tree table */
  114027. char *zName; /* Name of r-tree table */
  114028. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  114029. int nBusy; /* Current number of users of this structure */
  114030. /* List of nodes removed during a CondenseTree operation. List is
  114031. ** linked together via the pointer normally used for hash chains -
  114032. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  114033. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  114034. */
  114035. RtreeNode *pDeleted;
  114036. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  114037. /* Statements to read/write/delete a record from xxx_node */
  114038. sqlite3_stmt *pReadNode;
  114039. sqlite3_stmt *pWriteNode;
  114040. sqlite3_stmt *pDeleteNode;
  114041. /* Statements to read/write/delete a record from xxx_rowid */
  114042. sqlite3_stmt *pReadRowid;
  114043. sqlite3_stmt *pWriteRowid;
  114044. sqlite3_stmt *pDeleteRowid;
  114045. /* Statements to read/write/delete a record from xxx_parent */
  114046. sqlite3_stmt *pReadParent;
  114047. sqlite3_stmt *pWriteParent;
  114048. sqlite3_stmt *pDeleteParent;
  114049. int eCoordType;
  114050. };
  114051. /* Possible values for eCoordType: */
  114052. #define RTREE_COORD_REAL32 0
  114053. #define RTREE_COORD_INT32 1
  114054. /*
  114055. ** The minimum number of cells allowed for a node is a third of the
  114056. ** maximum. In Gutman's notation:
  114057. **
  114058. ** m = M/3
  114059. **
  114060. ** If an R*-tree "Reinsert" operation is required, the same number of
  114061. ** cells are removed from the overfull node and reinserted into the tree.
  114062. */
  114063. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  114064. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  114065. #define RTREE_MAXCELLS 51
  114066. /*
  114067. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  114068. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  114069. ** Therefore all non-root nodes must contain at least 3 entries. Since
  114070. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  114071. ** 40 or less.
  114072. */
  114073. #define RTREE_MAX_DEPTH 40
  114074. /*
  114075. ** An rtree cursor object.
  114076. */
  114077. struct RtreeCursor {
  114078. sqlite3_vtab_cursor base;
  114079. RtreeNode *pNode; /* Node cursor is currently pointing at */
  114080. int iCell; /* Index of current cell in pNode */
  114081. int iStrategy; /* Copy of idxNum search parameter */
  114082. int nConstraint; /* Number of entries in aConstraint */
  114083. RtreeConstraint *aConstraint; /* Search constraints. */
  114084. };
  114085. union RtreeCoord {
  114086. float f;
  114087. int i;
  114088. };
  114089. /*
  114090. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  114091. ** formatted as a double. This macro assumes that local variable pRtree points
  114092. ** to the Rtree structure associated with the RtreeCoord.
  114093. */
  114094. #define DCOORD(coord) ( \
  114095. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  114096. ((double)coord.f) : \
  114097. ((double)coord.i) \
  114098. )
  114099. /*
  114100. ** A search constraint.
  114101. */
  114102. struct RtreeConstraint {
  114103. int iCoord; /* Index of constrained coordinate */
  114104. int op; /* Constraining operation */
  114105. double rValue; /* Constraint value. */
  114106. int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
  114107. sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
  114108. };
  114109. /* Possible values for RtreeConstraint.op */
  114110. #define RTREE_EQ 0x41
  114111. #define RTREE_LE 0x42
  114112. #define RTREE_LT 0x43
  114113. #define RTREE_GE 0x44
  114114. #define RTREE_GT 0x45
  114115. #define RTREE_MATCH 0x46
  114116. /*
  114117. ** An rtree structure node.
  114118. */
  114119. struct RtreeNode {
  114120. RtreeNode *pParent; /* Parent node */
  114121. i64 iNode;
  114122. int nRef;
  114123. int isDirty;
  114124. u8 *zData;
  114125. RtreeNode *pNext; /* Next node in this hash chain */
  114126. };
  114127. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  114128. /*
  114129. ** Structure to store a deserialized rtree record.
  114130. */
  114131. struct RtreeCell {
  114132. i64 iRowid;
  114133. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  114134. };
  114135. /*
  114136. ** Value for the first field of every RtreeMatchArg object. The MATCH
  114137. ** operator tests that the first field of a blob operand matches this
  114138. ** value to avoid operating on invalid blobs (which could cause a segfault).
  114139. */
  114140. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  114141. /*
  114142. ** An instance of this structure must be supplied as a blob argument to
  114143. ** the right-hand-side of an SQL MATCH operator used to constrain an
  114144. ** r-tree query.
  114145. */
  114146. struct RtreeMatchArg {
  114147. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  114148. int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
  114149. void *pContext;
  114150. int nParam;
  114151. double aParam[1];
  114152. };
  114153. /*
  114154. ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
  114155. ** a single instance of the following structure is allocated. It is used
  114156. ** as the context for the user-function created by by s_r_g_c(). The object
  114157. ** is eventually deleted by the destructor mechanism provided by
  114158. ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
  114159. ** the geometry callback function).
  114160. */
  114161. struct RtreeGeomCallback {
  114162. int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
  114163. void *pContext;
  114164. };
  114165. #ifndef MAX
  114166. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  114167. #endif
  114168. #ifndef MIN
  114169. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  114170. #endif
  114171. /*
  114172. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  114173. ** 64 bit integer. The deserialized value is returned.
  114174. */
  114175. static int readInt16(u8 *p){
  114176. return (p[0]<<8) + p[1];
  114177. }
  114178. static void readCoord(u8 *p, RtreeCoord *pCoord){
  114179. u32 i = (
  114180. (((u32)p[0]) << 24) +
  114181. (((u32)p[1]) << 16) +
  114182. (((u32)p[2]) << 8) +
  114183. (((u32)p[3]) << 0)
  114184. );
  114185. *(u32 *)pCoord = i;
  114186. }
  114187. static i64 readInt64(u8 *p){
  114188. return (
  114189. (((i64)p[0]) << 56) +
  114190. (((i64)p[1]) << 48) +
  114191. (((i64)p[2]) << 40) +
  114192. (((i64)p[3]) << 32) +
  114193. (((i64)p[4]) << 24) +
  114194. (((i64)p[5]) << 16) +
  114195. (((i64)p[6]) << 8) +
  114196. (((i64)p[7]) << 0)
  114197. );
  114198. }
  114199. /*
  114200. ** Functions to serialize a 16 bit integer, 32 bit real number and
  114201. ** 64 bit integer. The value returned is the number of bytes written
  114202. ** to the argument buffer (always 2, 4 and 8 respectively).
  114203. */
  114204. static int writeInt16(u8 *p, int i){
  114205. p[0] = (i>> 8)&0xFF;
  114206. p[1] = (i>> 0)&0xFF;
  114207. return 2;
  114208. }
  114209. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  114210. u32 i;
  114211. assert( sizeof(RtreeCoord)==4 );
  114212. assert( sizeof(u32)==4 );
  114213. i = *(u32 *)pCoord;
  114214. p[0] = (i>>24)&0xFF;
  114215. p[1] = (i>>16)&0xFF;
  114216. p[2] = (i>> 8)&0xFF;
  114217. p[3] = (i>> 0)&0xFF;
  114218. return 4;
  114219. }
  114220. static int writeInt64(u8 *p, i64 i){
  114221. p[0] = (i>>56)&0xFF;
  114222. p[1] = (i>>48)&0xFF;
  114223. p[2] = (i>>40)&0xFF;
  114224. p[3] = (i>>32)&0xFF;
  114225. p[4] = (i>>24)&0xFF;
  114226. p[5] = (i>>16)&0xFF;
  114227. p[6] = (i>> 8)&0xFF;
  114228. p[7] = (i>> 0)&0xFF;
  114229. return 8;
  114230. }
  114231. /*
  114232. ** Increment the reference count of node p.
  114233. */
  114234. static void nodeReference(RtreeNode *p){
  114235. if( p ){
  114236. p->nRef++;
  114237. }
  114238. }
  114239. /*
  114240. ** Clear the content of node p (set all bytes to 0x00).
  114241. */
  114242. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  114243. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  114244. p->isDirty = 1;
  114245. }
  114246. /*
  114247. ** Given a node number iNode, return the corresponding key to use
  114248. ** in the Rtree.aHash table.
  114249. */
  114250. static int nodeHash(i64 iNode){
  114251. return (
  114252. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  114253. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  114254. ) % HASHSIZE;
  114255. }
  114256. /*
  114257. ** Search the node hash table for node iNode. If found, return a pointer
  114258. ** to it. Otherwise, return 0.
  114259. */
  114260. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  114261. RtreeNode *p;
  114262. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  114263. return p;
  114264. }
  114265. /*
  114266. ** Add node pNode to the node hash table.
  114267. */
  114268. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  114269. int iHash;
  114270. assert( pNode->pNext==0 );
  114271. iHash = nodeHash(pNode->iNode);
  114272. pNode->pNext = pRtree->aHash[iHash];
  114273. pRtree->aHash[iHash] = pNode;
  114274. }
  114275. /*
  114276. ** Remove node pNode from the node hash table.
  114277. */
  114278. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  114279. RtreeNode **pp;
  114280. if( pNode->iNode!=0 ){
  114281. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  114282. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  114283. *pp = pNode->pNext;
  114284. pNode->pNext = 0;
  114285. }
  114286. }
  114287. /*
  114288. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  114289. ** indicating that node has not yet been assigned a node number. It is
  114290. ** assigned a node number when nodeWrite() is called to write the
  114291. ** node contents out to the database.
  114292. */
  114293. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  114294. RtreeNode *pNode;
  114295. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  114296. if( pNode ){
  114297. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  114298. pNode->zData = (u8 *)&pNode[1];
  114299. pNode->nRef = 1;
  114300. pNode->pParent = pParent;
  114301. pNode->isDirty = 1;
  114302. nodeReference(pParent);
  114303. }
  114304. return pNode;
  114305. }
  114306. /*
  114307. ** Obtain a reference to an r-tree node.
  114308. */
  114309. static int
  114310. nodeAcquire(
  114311. Rtree *pRtree, /* R-tree structure */
  114312. i64 iNode, /* Node number to load */
  114313. RtreeNode *pParent, /* Either the parent node or NULL */
  114314. RtreeNode **ppNode /* OUT: Acquired node */
  114315. ){
  114316. int rc;
  114317. int rc2 = SQLITE_OK;
  114318. RtreeNode *pNode;
  114319. /* Check if the requested node is already in the hash table. If so,
  114320. ** increase its reference count and return it.
  114321. */
  114322. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  114323. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  114324. if( pParent && !pNode->pParent ){
  114325. nodeReference(pParent);
  114326. pNode->pParent = pParent;
  114327. }
  114328. pNode->nRef++;
  114329. *ppNode = pNode;
  114330. return SQLITE_OK;
  114331. }
  114332. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  114333. rc = sqlite3_step(pRtree->pReadNode);
  114334. if( rc==SQLITE_ROW ){
  114335. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  114336. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  114337. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  114338. if( !pNode ){
  114339. rc2 = SQLITE_NOMEM;
  114340. }else{
  114341. pNode->pParent = pParent;
  114342. pNode->zData = (u8 *)&pNode[1];
  114343. pNode->nRef = 1;
  114344. pNode->iNode = iNode;
  114345. pNode->isDirty = 0;
  114346. pNode->pNext = 0;
  114347. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  114348. nodeReference(pParent);
  114349. }
  114350. }
  114351. }
  114352. rc = sqlite3_reset(pRtree->pReadNode);
  114353. if( rc==SQLITE_OK ) rc = rc2;
  114354. /* If the root node was just loaded, set pRtree->iDepth to the height
  114355. ** of the r-tree structure. A height of zero means all data is stored on
  114356. ** the root node. A height of one means the children of the root node
  114357. ** are the leaves, and so on. If the depth as specified on the root node
  114358. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  114359. */
  114360. if( pNode && iNode==1 ){
  114361. pRtree->iDepth = readInt16(pNode->zData);
  114362. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  114363. rc = SQLITE_CORRUPT;
  114364. }
  114365. }
  114366. /* If no error has occurred so far, check if the "number of entries"
  114367. ** field on the node is too large. If so, set the return code to
  114368. ** SQLITE_CORRUPT.
  114369. */
  114370. if( pNode && rc==SQLITE_OK ){
  114371. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  114372. rc = SQLITE_CORRUPT;
  114373. }
  114374. }
  114375. if( rc==SQLITE_OK ){
  114376. if( pNode!=0 ){
  114377. nodeHashInsert(pRtree, pNode);
  114378. }else{
  114379. rc = SQLITE_CORRUPT;
  114380. }
  114381. *ppNode = pNode;
  114382. }else{
  114383. sqlite3_free(pNode);
  114384. *ppNode = 0;
  114385. }
  114386. return rc;
  114387. }
  114388. /*
  114389. ** Overwrite cell iCell of node pNode with the contents of pCell.
  114390. */
  114391. static void nodeOverwriteCell(
  114392. Rtree *pRtree,
  114393. RtreeNode *pNode,
  114394. RtreeCell *pCell,
  114395. int iCell
  114396. ){
  114397. int ii;
  114398. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  114399. p += writeInt64(p, pCell->iRowid);
  114400. for(ii=0; ii<(pRtree->nDim*2); ii++){
  114401. p += writeCoord(p, &pCell->aCoord[ii]);
  114402. }
  114403. pNode->isDirty = 1;
  114404. }
  114405. /*
  114406. ** Remove cell the cell with index iCell from node pNode.
  114407. */
  114408. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  114409. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  114410. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  114411. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  114412. memmove(pDst, pSrc, nByte);
  114413. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  114414. pNode->isDirty = 1;
  114415. }
  114416. /*
  114417. ** Insert the contents of cell pCell into node pNode. If the insert
  114418. ** is successful, return SQLITE_OK.
  114419. **
  114420. ** If there is not enough free space in pNode, return SQLITE_FULL.
  114421. */
  114422. static int
  114423. nodeInsertCell(
  114424. Rtree *pRtree,
  114425. RtreeNode *pNode,
  114426. RtreeCell *pCell
  114427. ){
  114428. int nCell; /* Current number of cells in pNode */
  114429. int nMaxCell; /* Maximum number of cells for pNode */
  114430. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  114431. nCell = NCELL(pNode);
  114432. assert( nCell<=nMaxCell );
  114433. if( nCell<nMaxCell ){
  114434. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  114435. writeInt16(&pNode->zData[2], nCell+1);
  114436. pNode->isDirty = 1;
  114437. }
  114438. return (nCell==nMaxCell);
  114439. }
  114440. /*
  114441. ** If the node is dirty, write it out to the database.
  114442. */
  114443. static int
  114444. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  114445. int rc = SQLITE_OK;
  114446. if( pNode->isDirty ){
  114447. sqlite3_stmt *p = pRtree->pWriteNode;
  114448. if( pNode->iNode ){
  114449. sqlite3_bind_int64(p, 1, pNode->iNode);
  114450. }else{
  114451. sqlite3_bind_null(p, 1);
  114452. }
  114453. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  114454. sqlite3_step(p);
  114455. pNode->isDirty = 0;
  114456. rc = sqlite3_reset(p);
  114457. if( pNode->iNode==0 && rc==SQLITE_OK ){
  114458. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  114459. nodeHashInsert(pRtree, pNode);
  114460. }
  114461. }
  114462. return rc;
  114463. }
  114464. /*
  114465. ** Release a reference to a node. If the node is dirty and the reference
  114466. ** count drops to zero, the node data is written to the database.
  114467. */
  114468. static int
  114469. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  114470. int rc = SQLITE_OK;
  114471. if( pNode ){
  114472. assert( pNode->nRef>0 );
  114473. pNode->nRef--;
  114474. if( pNode->nRef==0 ){
  114475. if( pNode->iNode==1 ){
  114476. pRtree->iDepth = -1;
  114477. }
  114478. if( pNode->pParent ){
  114479. rc = nodeRelease(pRtree, pNode->pParent);
  114480. }
  114481. if( rc==SQLITE_OK ){
  114482. rc = nodeWrite(pRtree, pNode);
  114483. }
  114484. nodeHashDelete(pRtree, pNode);
  114485. sqlite3_free(pNode);
  114486. }
  114487. }
  114488. return rc;
  114489. }
  114490. /*
  114491. ** Return the 64-bit integer value associated with cell iCell of
  114492. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  114493. ** an internal node, then the 64-bit integer is a child page number.
  114494. */
  114495. static i64 nodeGetRowid(
  114496. Rtree *pRtree,
  114497. RtreeNode *pNode,
  114498. int iCell
  114499. ){
  114500. assert( iCell<NCELL(pNode) );
  114501. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  114502. }
  114503. /*
  114504. ** Return coordinate iCoord from cell iCell in node pNode.
  114505. */
  114506. static void nodeGetCoord(
  114507. Rtree *pRtree,
  114508. RtreeNode *pNode,
  114509. int iCell,
  114510. int iCoord,
  114511. RtreeCoord *pCoord /* Space to write result to */
  114512. ){
  114513. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  114514. }
  114515. /*
  114516. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  114517. ** to by pCell with the results.
  114518. */
  114519. static void nodeGetCell(
  114520. Rtree *pRtree,
  114521. RtreeNode *pNode,
  114522. int iCell,
  114523. RtreeCell *pCell
  114524. ){
  114525. int ii;
  114526. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  114527. for(ii=0; ii<pRtree->nDim*2; ii++){
  114528. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  114529. }
  114530. }
  114531. /* Forward declaration for the function that does the work of
  114532. ** the virtual table module xCreate() and xConnect() methods.
  114533. */
  114534. static int rtreeInit(
  114535. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  114536. );
  114537. /*
  114538. ** Rtree virtual table module xCreate method.
  114539. */
  114540. static int rtreeCreate(
  114541. sqlite3 *db,
  114542. void *pAux,
  114543. int argc, const char *const*argv,
  114544. sqlite3_vtab **ppVtab,
  114545. char **pzErr
  114546. ){
  114547. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  114548. }
  114549. /*
  114550. ** Rtree virtual table module xConnect method.
  114551. */
  114552. static int rtreeConnect(
  114553. sqlite3 *db,
  114554. void *pAux,
  114555. int argc, const char *const*argv,
  114556. sqlite3_vtab **ppVtab,
  114557. char **pzErr
  114558. ){
  114559. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  114560. }
  114561. /*
  114562. ** Increment the r-tree reference count.
  114563. */
  114564. static void rtreeReference(Rtree *pRtree){
  114565. pRtree->nBusy++;
  114566. }
  114567. /*
  114568. ** Decrement the r-tree reference count. When the reference count reaches
  114569. ** zero the structure is deleted.
  114570. */
  114571. static void rtreeRelease(Rtree *pRtree){
  114572. pRtree->nBusy--;
  114573. if( pRtree->nBusy==0 ){
  114574. sqlite3_finalize(pRtree->pReadNode);
  114575. sqlite3_finalize(pRtree->pWriteNode);
  114576. sqlite3_finalize(pRtree->pDeleteNode);
  114577. sqlite3_finalize(pRtree->pReadRowid);
  114578. sqlite3_finalize(pRtree->pWriteRowid);
  114579. sqlite3_finalize(pRtree->pDeleteRowid);
  114580. sqlite3_finalize(pRtree->pReadParent);
  114581. sqlite3_finalize(pRtree->pWriteParent);
  114582. sqlite3_finalize(pRtree->pDeleteParent);
  114583. sqlite3_free(pRtree);
  114584. }
  114585. }
  114586. /*
  114587. ** Rtree virtual table module xDisconnect method.
  114588. */
  114589. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  114590. rtreeRelease((Rtree *)pVtab);
  114591. return SQLITE_OK;
  114592. }
  114593. /*
  114594. ** Rtree virtual table module xDestroy method.
  114595. */
  114596. static int rtreeDestroy(sqlite3_vtab *pVtab){
  114597. Rtree *pRtree = (Rtree *)pVtab;
  114598. int rc;
  114599. char *zCreate = sqlite3_mprintf(
  114600. "DROP TABLE '%q'.'%q_node';"
  114601. "DROP TABLE '%q'.'%q_rowid';"
  114602. "DROP TABLE '%q'.'%q_parent';",
  114603. pRtree->zDb, pRtree->zName,
  114604. pRtree->zDb, pRtree->zName,
  114605. pRtree->zDb, pRtree->zName
  114606. );
  114607. if( !zCreate ){
  114608. rc = SQLITE_NOMEM;
  114609. }else{
  114610. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  114611. sqlite3_free(zCreate);
  114612. }
  114613. if( rc==SQLITE_OK ){
  114614. rtreeRelease(pRtree);
  114615. }
  114616. return rc;
  114617. }
  114618. /*
  114619. ** Rtree virtual table module xOpen method.
  114620. */
  114621. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  114622. int rc = SQLITE_NOMEM;
  114623. RtreeCursor *pCsr;
  114624. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  114625. if( pCsr ){
  114626. memset(pCsr, 0, sizeof(RtreeCursor));
  114627. pCsr->base.pVtab = pVTab;
  114628. rc = SQLITE_OK;
  114629. }
  114630. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  114631. return rc;
  114632. }
  114633. /*
  114634. ** Free the RtreeCursor.aConstraint[] array and its contents.
  114635. */
  114636. static void freeCursorConstraints(RtreeCursor *pCsr){
  114637. if( pCsr->aConstraint ){
  114638. int i; /* Used to iterate through constraint array */
  114639. for(i=0; i<pCsr->nConstraint; i++){
  114640. sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
  114641. if( pGeom ){
  114642. if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
  114643. sqlite3_free(pGeom);
  114644. }
  114645. }
  114646. sqlite3_free(pCsr->aConstraint);
  114647. pCsr->aConstraint = 0;
  114648. }
  114649. }
  114650. /*
  114651. ** Rtree virtual table module xClose method.
  114652. */
  114653. static int rtreeClose(sqlite3_vtab_cursor *cur){
  114654. Rtree *pRtree = (Rtree *)(cur->pVtab);
  114655. int rc;
  114656. RtreeCursor *pCsr = (RtreeCursor *)cur;
  114657. freeCursorConstraints(pCsr);
  114658. rc = nodeRelease(pRtree, pCsr->pNode);
  114659. sqlite3_free(pCsr);
  114660. return rc;
  114661. }
  114662. /*
  114663. ** Rtree virtual table module xEof method.
  114664. **
  114665. ** Return non-zero if the cursor does not currently point to a valid
  114666. ** record (i.e if the scan has finished), or zero otherwise.
  114667. */
  114668. static int rtreeEof(sqlite3_vtab_cursor *cur){
  114669. RtreeCursor *pCsr = (RtreeCursor *)cur;
  114670. return (pCsr->pNode==0);
  114671. }
  114672. /*
  114673. ** The r-tree constraint passed as the second argument to this function is
  114674. ** guaranteed to be a MATCH constraint.
  114675. */
  114676. static int testRtreeGeom(
  114677. Rtree *pRtree, /* R-Tree object */
  114678. RtreeConstraint *pConstraint, /* MATCH constraint to test */
  114679. RtreeCell *pCell, /* Cell to test */
  114680. int *pbRes /* OUT: Test result */
  114681. ){
  114682. int i;
  114683. double aCoord[RTREE_MAX_DIMENSIONS*2];
  114684. int nCoord = pRtree->nDim*2;
  114685. assert( pConstraint->op==RTREE_MATCH );
  114686. assert( pConstraint->pGeom );
  114687. for(i=0; i<nCoord; i++){
  114688. aCoord[i] = DCOORD(pCell->aCoord[i]);
  114689. }
  114690. return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
  114691. }
  114692. /*
  114693. ** Cursor pCursor currently points to a cell in a non-leaf page.
  114694. ** Set *pbEof to true if the sub-tree headed by the cell is filtered
  114695. ** (excluded) by the constraints in the pCursor->aConstraint[]
  114696. ** array, or false otherwise.
  114697. **
  114698. ** Return SQLITE_OK if successful or an SQLite error code if an error
  114699. ** occurs within a geometry callback.
  114700. */
  114701. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  114702. RtreeCell cell;
  114703. int ii;
  114704. int bRes = 0;
  114705. int rc = SQLITE_OK;
  114706. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  114707. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  114708. RtreeConstraint *p = &pCursor->aConstraint[ii];
  114709. double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  114710. double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  114711. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  114712. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  114713. );
  114714. switch( p->op ){
  114715. case RTREE_LE: case RTREE_LT:
  114716. bRes = p->rValue<cell_min;
  114717. break;
  114718. case RTREE_GE: case RTREE_GT:
  114719. bRes = p->rValue>cell_max;
  114720. break;
  114721. case RTREE_EQ:
  114722. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  114723. break;
  114724. default: {
  114725. assert( p->op==RTREE_MATCH );
  114726. rc = testRtreeGeom(pRtree, p, &cell, &bRes);
  114727. bRes = !bRes;
  114728. break;
  114729. }
  114730. }
  114731. }
  114732. *pbEof = bRes;
  114733. return rc;
  114734. }
  114735. /*
  114736. ** Test if the cell that cursor pCursor currently points to
  114737. ** would be filtered (excluded) by the constraints in the
  114738. ** pCursor->aConstraint[] array. If so, set *pbEof to true before
  114739. ** returning. If the cell is not filtered (excluded) by the constraints,
  114740. ** set pbEof to zero.
  114741. **
  114742. ** Return SQLITE_OK if successful or an SQLite error code if an error
  114743. ** occurs within a geometry callback.
  114744. **
  114745. ** This function assumes that the cell is part of a leaf node.
  114746. */
  114747. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  114748. RtreeCell cell;
  114749. int ii;
  114750. *pbEof = 0;
  114751. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  114752. for(ii=0; ii<pCursor->nConstraint; ii++){
  114753. RtreeConstraint *p = &pCursor->aConstraint[ii];
  114754. double coord = DCOORD(cell.aCoord[p->iCoord]);
  114755. int res;
  114756. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  114757. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  114758. );
  114759. switch( p->op ){
  114760. case RTREE_LE: res = (coord<=p->rValue); break;
  114761. case RTREE_LT: res = (coord<p->rValue); break;
  114762. case RTREE_GE: res = (coord>=p->rValue); break;
  114763. case RTREE_GT: res = (coord>p->rValue); break;
  114764. case RTREE_EQ: res = (coord==p->rValue); break;
  114765. default: {
  114766. int rc;
  114767. assert( p->op==RTREE_MATCH );
  114768. rc = testRtreeGeom(pRtree, p, &cell, &res);
  114769. if( rc!=SQLITE_OK ){
  114770. return rc;
  114771. }
  114772. break;
  114773. }
  114774. }
  114775. if( !res ){
  114776. *pbEof = 1;
  114777. return SQLITE_OK;
  114778. }
  114779. }
  114780. return SQLITE_OK;
  114781. }
  114782. /*
  114783. ** Cursor pCursor currently points at a node that heads a sub-tree of
  114784. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  114785. ** to point to the left-most cell of the sub-tree that matches the
  114786. ** configured constraints.
  114787. */
  114788. static int descendToCell(
  114789. Rtree *pRtree,
  114790. RtreeCursor *pCursor,
  114791. int iHeight,
  114792. int *pEof /* OUT: Set to true if cannot descend */
  114793. ){
  114794. int isEof;
  114795. int rc;
  114796. int ii;
  114797. RtreeNode *pChild;
  114798. sqlite3_int64 iRowid;
  114799. RtreeNode *pSavedNode = pCursor->pNode;
  114800. int iSavedCell = pCursor->iCell;
  114801. assert( iHeight>=0 );
  114802. if( iHeight==0 ){
  114803. rc = testRtreeEntry(pRtree, pCursor, &isEof);
  114804. }else{
  114805. rc = testRtreeCell(pRtree, pCursor, &isEof);
  114806. }
  114807. if( rc!=SQLITE_OK || isEof || iHeight==0 ){
  114808. goto descend_to_cell_out;
  114809. }
  114810. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  114811. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  114812. if( rc!=SQLITE_OK ){
  114813. goto descend_to_cell_out;
  114814. }
  114815. nodeRelease(pRtree, pCursor->pNode);
  114816. pCursor->pNode = pChild;
  114817. isEof = 1;
  114818. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  114819. pCursor->iCell = ii;
  114820. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  114821. if( rc!=SQLITE_OK ){
  114822. goto descend_to_cell_out;
  114823. }
  114824. }
  114825. if( isEof ){
  114826. assert( pCursor->pNode==pChild );
  114827. nodeReference(pSavedNode);
  114828. nodeRelease(pRtree, pChild);
  114829. pCursor->pNode = pSavedNode;
  114830. pCursor->iCell = iSavedCell;
  114831. }
  114832. descend_to_cell_out:
  114833. *pEof = isEof;
  114834. return rc;
  114835. }
  114836. /*
  114837. ** One of the cells in node pNode is guaranteed to have a 64-bit
  114838. ** integer value equal to iRowid. Return the index of this cell.
  114839. */
  114840. static int nodeRowidIndex(
  114841. Rtree *pRtree,
  114842. RtreeNode *pNode,
  114843. i64 iRowid,
  114844. int *piIndex
  114845. ){
  114846. int ii;
  114847. int nCell = NCELL(pNode);
  114848. for(ii=0; ii<nCell; ii++){
  114849. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  114850. *piIndex = ii;
  114851. return SQLITE_OK;
  114852. }
  114853. }
  114854. return SQLITE_CORRUPT;
  114855. }
  114856. /*
  114857. ** Return the index of the cell containing a pointer to node pNode
  114858. ** in its parent. If pNode is the root node, return -1.
  114859. */
  114860. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  114861. RtreeNode *pParent = pNode->pParent;
  114862. if( pParent ){
  114863. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  114864. }
  114865. *piIndex = -1;
  114866. return SQLITE_OK;
  114867. }
  114868. /*
  114869. ** Rtree virtual table module xNext method.
  114870. */
  114871. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  114872. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  114873. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  114874. int rc = SQLITE_OK;
  114875. /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
  114876. ** already at EOF. It is against the rules to call the xNext() method of
  114877. ** a cursor that has already reached EOF.
  114878. */
  114879. assert( pCsr->pNode );
  114880. if( pCsr->iStrategy==1 ){
  114881. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  114882. nodeRelease(pRtree, pCsr->pNode);
  114883. pCsr->pNode = 0;
  114884. }else{
  114885. /* Move to the next entry that matches the configured constraints. */
  114886. int iHeight = 0;
  114887. while( pCsr->pNode ){
  114888. RtreeNode *pNode = pCsr->pNode;
  114889. int nCell = NCELL(pNode);
  114890. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  114891. int isEof;
  114892. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  114893. if( rc!=SQLITE_OK || !isEof ){
  114894. return rc;
  114895. }
  114896. }
  114897. pCsr->pNode = pNode->pParent;
  114898. rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
  114899. if( rc!=SQLITE_OK ){
  114900. return rc;
  114901. }
  114902. nodeReference(pCsr->pNode);
  114903. nodeRelease(pRtree, pNode);
  114904. iHeight++;
  114905. }
  114906. }
  114907. return rc;
  114908. }
  114909. /*
  114910. ** Rtree virtual table module xRowid method.
  114911. */
  114912. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  114913. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  114914. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  114915. assert(pCsr->pNode);
  114916. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  114917. return SQLITE_OK;
  114918. }
  114919. /*
  114920. ** Rtree virtual table module xColumn method.
  114921. */
  114922. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  114923. Rtree *pRtree = (Rtree *)cur->pVtab;
  114924. RtreeCursor *pCsr = (RtreeCursor *)cur;
  114925. if( i==0 ){
  114926. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  114927. sqlite3_result_int64(ctx, iRowid);
  114928. }else{
  114929. RtreeCoord c;
  114930. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  114931. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  114932. sqlite3_result_double(ctx, c.f);
  114933. }else{
  114934. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  114935. sqlite3_result_int(ctx, c.i);
  114936. }
  114937. }
  114938. return SQLITE_OK;
  114939. }
  114940. /*
  114941. ** Use nodeAcquire() to obtain the leaf node containing the record with
  114942. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  114943. ** return SQLITE_OK. If there is no such record in the table, set
  114944. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  114945. ** to zero and return an SQLite error code.
  114946. */
  114947. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  114948. int rc;
  114949. *ppLeaf = 0;
  114950. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  114951. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  114952. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  114953. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  114954. sqlite3_reset(pRtree->pReadRowid);
  114955. }else{
  114956. rc = sqlite3_reset(pRtree->pReadRowid);
  114957. }
  114958. return rc;
  114959. }
  114960. /*
  114961. ** This function is called to configure the RtreeConstraint object passed
  114962. ** as the second argument for a MATCH constraint. The value passed as the
  114963. ** first argument to this function is the right-hand operand to the MATCH
  114964. ** operator.
  114965. */
  114966. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  114967. RtreeMatchArg *p;
  114968. sqlite3_rtree_geometry *pGeom;
  114969. int nBlob;
  114970. /* Check that value is actually a blob. */
  114971. if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
  114972. /* Check that the blob is roughly the right size. */
  114973. nBlob = sqlite3_value_bytes(pValue);
  114974. if( nBlob<(int)sizeof(RtreeMatchArg)
  114975. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
  114976. ){
  114977. return SQLITE_ERROR;
  114978. }
  114979. pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
  114980. sizeof(sqlite3_rtree_geometry) + nBlob
  114981. );
  114982. if( !pGeom ) return SQLITE_NOMEM;
  114983. memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
  114984. p = (RtreeMatchArg *)&pGeom[1];
  114985. memcpy(p, sqlite3_value_blob(pValue), nBlob);
  114986. if( p->magic!=RTREE_GEOMETRY_MAGIC
  114987. || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
  114988. ){
  114989. sqlite3_free(pGeom);
  114990. return SQLITE_ERROR;
  114991. }
  114992. pGeom->pContext = p->pContext;
  114993. pGeom->nParam = p->nParam;
  114994. pGeom->aParam = p->aParam;
  114995. pCons->xGeom = p->xGeom;
  114996. pCons->pGeom = pGeom;
  114997. return SQLITE_OK;
  114998. }
  114999. /*
  115000. ** Rtree virtual table module xFilter method.
  115001. */
  115002. static int rtreeFilter(
  115003. sqlite3_vtab_cursor *pVtabCursor,
  115004. int idxNum, const char *idxStr,
  115005. int argc, sqlite3_value **argv
  115006. ){
  115007. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  115008. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  115009. RtreeNode *pRoot = 0;
  115010. int ii;
  115011. int rc = SQLITE_OK;
  115012. rtreeReference(pRtree);
  115013. freeCursorConstraints(pCsr);
  115014. pCsr->iStrategy = idxNum;
  115015. if( idxNum==1 ){
  115016. /* Special case - lookup by rowid. */
  115017. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  115018. i64 iRowid = sqlite3_value_int64(argv[0]);
  115019. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  115020. pCsr->pNode = pLeaf;
  115021. if( pLeaf ){
  115022. assert( rc==SQLITE_OK );
  115023. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
  115024. }
  115025. }else{
  115026. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  115027. ** with the configured constraints.
  115028. */
  115029. if( argc>0 ){
  115030. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  115031. pCsr->nConstraint = argc;
  115032. if( !pCsr->aConstraint ){
  115033. rc = SQLITE_NOMEM;
  115034. }else{
  115035. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  115036. assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
  115037. for(ii=0; ii<argc; ii++){
  115038. RtreeConstraint *p = &pCsr->aConstraint[ii];
  115039. p->op = idxStr[ii*2];
  115040. p->iCoord = idxStr[ii*2+1]-'a';
  115041. if( p->op==RTREE_MATCH ){
  115042. /* A MATCH operator. The right-hand-side must be a blob that
  115043. ** can be cast into an RtreeMatchArg object. One created using
  115044. ** an sqlite3_rtree_geometry_callback() SQL user function.
  115045. */
  115046. rc = deserializeGeometry(argv[ii], p);
  115047. if( rc!=SQLITE_OK ){
  115048. break;
  115049. }
  115050. }else{
  115051. p->rValue = sqlite3_value_double(argv[ii]);
  115052. }
  115053. }
  115054. }
  115055. }
  115056. if( rc==SQLITE_OK ){
  115057. pCsr->pNode = 0;
  115058. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  115059. }
  115060. if( rc==SQLITE_OK ){
  115061. int isEof = 1;
  115062. int nCell = NCELL(pRoot);
  115063. pCsr->pNode = pRoot;
  115064. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  115065. assert( pCsr->pNode==pRoot );
  115066. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  115067. if( !isEof ){
  115068. break;
  115069. }
  115070. }
  115071. if( rc==SQLITE_OK && isEof ){
  115072. assert( pCsr->pNode==pRoot );
  115073. nodeRelease(pRtree, pRoot);
  115074. pCsr->pNode = 0;
  115075. }
  115076. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  115077. }
  115078. }
  115079. rtreeRelease(pRtree);
  115080. return rc;
  115081. }
  115082. /*
  115083. ** Rtree virtual table module xBestIndex method. There are three
  115084. ** table scan strategies to choose from (in order from most to
  115085. ** least desirable):
  115086. **
  115087. ** idxNum idxStr Strategy
  115088. ** ------------------------------------------------
  115089. ** 1 Unused Direct lookup by rowid.
  115090. ** 2 See below R-tree query or full-table scan.
  115091. ** ------------------------------------------------
  115092. **
  115093. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  115094. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  115095. ** constraint used. The first two bytes of idxStr correspond to
  115096. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  115097. ** (argvIndex==1) etc.
  115098. **
  115099. ** The first of each pair of bytes in idxStr identifies the constraint
  115100. ** operator as follows:
  115101. **
  115102. ** Operator Byte Value
  115103. ** ----------------------
  115104. ** = 0x41 ('A')
  115105. ** <= 0x42 ('B')
  115106. ** < 0x43 ('C')
  115107. ** >= 0x44 ('D')
  115108. ** > 0x45 ('E')
  115109. ** MATCH 0x46 ('F')
  115110. ** ----------------------
  115111. **
  115112. ** The second of each pair of bytes identifies the coordinate column
  115113. ** to which the constraint applies. The leftmost coordinate column
  115114. ** is 'a', the second from the left 'b' etc.
  115115. */
  115116. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  115117. int rc = SQLITE_OK;
  115118. int ii;
  115119. int iIdx = 0;
  115120. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  115121. memset(zIdxStr, 0, sizeof(zIdxStr));
  115122. UNUSED_PARAMETER(tab);
  115123. assert( pIdxInfo->idxStr==0 );
  115124. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  115125. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  115126. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  115127. /* We have an equality constraint on the rowid. Use strategy 1. */
  115128. int jj;
  115129. for(jj=0; jj<ii; jj++){
  115130. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  115131. pIdxInfo->aConstraintUsage[jj].omit = 0;
  115132. }
  115133. pIdxInfo->idxNum = 1;
  115134. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  115135. pIdxInfo->aConstraintUsage[jj].omit = 1;
  115136. /* This strategy involves a two rowid lookups on an B-Tree structures
  115137. ** and then a linear search of an R-Tree node. This should be
  115138. ** considered almost as quick as a direct rowid lookup (for which
  115139. ** sqlite uses an internal cost of 0.0).
  115140. */
  115141. pIdxInfo->estimatedCost = 10.0;
  115142. return SQLITE_OK;
  115143. }
  115144. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  115145. u8 op;
  115146. switch( p->op ){
  115147. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  115148. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  115149. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  115150. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  115151. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  115152. default:
  115153. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  115154. op = RTREE_MATCH;
  115155. break;
  115156. }
  115157. zIdxStr[iIdx++] = op;
  115158. zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
  115159. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  115160. pIdxInfo->aConstraintUsage[ii].omit = 1;
  115161. }
  115162. }
  115163. pIdxInfo->idxNum = 2;
  115164. pIdxInfo->needToFreeIdxStr = 1;
  115165. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  115166. return SQLITE_NOMEM;
  115167. }
  115168. assert( iIdx>=0 );
  115169. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  115170. return rc;
  115171. }
  115172. /*
  115173. ** Return the N-dimensional volumn of the cell stored in *p.
  115174. */
  115175. static float cellArea(Rtree *pRtree, RtreeCell *p){
  115176. float area = 1.0;
  115177. int ii;
  115178. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  115179. area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  115180. }
  115181. return area;
  115182. }
  115183. /*
  115184. ** Return the margin length of cell p. The margin length is the sum
  115185. ** of the objects size in each dimension.
  115186. */
  115187. static float cellMargin(Rtree *pRtree, RtreeCell *p){
  115188. float margin = 0.0;
  115189. int ii;
  115190. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  115191. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  115192. }
  115193. return margin;
  115194. }
  115195. /*
  115196. ** Store the union of cells p1 and p2 in p1.
  115197. */
  115198. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  115199. int ii;
  115200. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  115201. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  115202. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  115203. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  115204. }
  115205. }else{
  115206. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  115207. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  115208. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  115209. }
  115210. }
  115211. }
  115212. /*
  115213. ** Return true if the area covered by p2 is a subset of the area covered
  115214. ** by p1. False otherwise.
  115215. */
  115216. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  115217. int ii;
  115218. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  115219. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  115220. RtreeCoord *a1 = &p1->aCoord[ii];
  115221. RtreeCoord *a2 = &p2->aCoord[ii];
  115222. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  115223. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  115224. ){
  115225. return 0;
  115226. }
  115227. }
  115228. return 1;
  115229. }
  115230. /*
  115231. ** Return the amount cell p would grow by if it were unioned with pCell.
  115232. */
  115233. static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  115234. float area;
  115235. RtreeCell cell;
  115236. memcpy(&cell, p, sizeof(RtreeCell));
  115237. area = cellArea(pRtree, &cell);
  115238. cellUnion(pRtree, &cell, pCell);
  115239. return (cellArea(pRtree, &cell)-area);
  115240. }
  115241. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  115242. static float cellOverlap(
  115243. Rtree *pRtree,
  115244. RtreeCell *p,
  115245. RtreeCell *aCell,
  115246. int nCell,
  115247. int iExclude
  115248. ){
  115249. int ii;
  115250. float overlap = 0.0;
  115251. for(ii=0; ii<nCell; ii++){
  115252. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  115253. if( ii!=iExclude )
  115254. #else
  115255. assert( iExclude==-1 );
  115256. UNUSED_PARAMETER(iExclude);
  115257. #endif
  115258. {
  115259. int jj;
  115260. float o = 1.0;
  115261. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  115262. double x1;
  115263. double x2;
  115264. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  115265. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  115266. if( x2<x1 ){
  115267. o = 0.0;
  115268. break;
  115269. }else{
  115270. o = o * (x2-x1);
  115271. }
  115272. }
  115273. overlap += o;
  115274. }
  115275. }
  115276. return overlap;
  115277. }
  115278. #endif
  115279. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  115280. static float cellOverlapEnlargement(
  115281. Rtree *pRtree,
  115282. RtreeCell *p,
  115283. RtreeCell *pInsert,
  115284. RtreeCell *aCell,
  115285. int nCell,
  115286. int iExclude
  115287. ){
  115288. float before;
  115289. float after;
  115290. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  115291. cellUnion(pRtree, p, pInsert);
  115292. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  115293. return after-before;
  115294. }
  115295. #endif
  115296. /*
  115297. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  115298. ** ChooseSubTree in r*tree terminology.
  115299. */
  115300. static int ChooseLeaf(
  115301. Rtree *pRtree, /* Rtree table */
  115302. RtreeCell *pCell, /* Cell to insert into rtree */
  115303. int iHeight, /* Height of sub-tree rooted at pCell */
  115304. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  115305. ){
  115306. int rc;
  115307. int ii;
  115308. RtreeNode *pNode;
  115309. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  115310. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  115311. int iCell;
  115312. sqlite3_int64 iBest;
  115313. float fMinGrowth;
  115314. float fMinArea;
  115315. float fMinOverlap;
  115316. int nCell = NCELL(pNode);
  115317. RtreeCell cell;
  115318. RtreeNode *pChild;
  115319. RtreeCell *aCell = 0;
  115320. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  115321. if( ii==(pRtree->iDepth-1) ){
  115322. int jj;
  115323. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  115324. if( !aCell ){
  115325. rc = SQLITE_NOMEM;
  115326. nodeRelease(pRtree, pNode);
  115327. pNode = 0;
  115328. continue;
  115329. }
  115330. for(jj=0; jj<nCell; jj++){
  115331. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  115332. }
  115333. }
  115334. #endif
  115335. /* Select the child node which will be enlarged the least if pCell
  115336. ** is inserted into it. Resolve ties by choosing the entry with
  115337. ** the smallest area.
  115338. */
  115339. for(iCell=0; iCell<nCell; iCell++){
  115340. int bBest = 0;
  115341. float growth;
  115342. float area;
  115343. float overlap = 0.0;
  115344. nodeGetCell(pRtree, pNode, iCell, &cell);
  115345. growth = cellGrowth(pRtree, &cell, pCell);
  115346. area = cellArea(pRtree, &cell);
  115347. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  115348. if( ii==(pRtree->iDepth-1) ){
  115349. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  115350. }
  115351. if( (iCell==0)
  115352. || (overlap<fMinOverlap)
  115353. || (overlap==fMinOverlap && growth<fMinGrowth)
  115354. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  115355. ){
  115356. bBest = 1;
  115357. }
  115358. #else
  115359. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  115360. bBest = 1;
  115361. }
  115362. #endif
  115363. if( bBest ){
  115364. fMinOverlap = overlap;
  115365. fMinGrowth = growth;
  115366. fMinArea = area;
  115367. iBest = cell.iRowid;
  115368. }
  115369. }
  115370. sqlite3_free(aCell);
  115371. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  115372. nodeRelease(pRtree, pNode);
  115373. pNode = pChild;
  115374. }
  115375. *ppLeaf = pNode;
  115376. return rc;
  115377. }
  115378. /*
  115379. ** A cell with the same content as pCell has just been inserted into
  115380. ** the node pNode. This function updates the bounding box cells in
  115381. ** all ancestor elements.
  115382. */
  115383. static int AdjustTree(
  115384. Rtree *pRtree, /* Rtree table */
  115385. RtreeNode *pNode, /* Adjust ancestry of this node. */
  115386. RtreeCell *pCell /* This cell was just inserted */
  115387. ){
  115388. RtreeNode *p = pNode;
  115389. while( p->pParent ){
  115390. RtreeNode *pParent = p->pParent;
  115391. RtreeCell cell;
  115392. int iCell;
  115393. if( nodeParentIndex(pRtree, p, &iCell) ){
  115394. return SQLITE_CORRUPT;
  115395. }
  115396. nodeGetCell(pRtree, pParent, iCell, &cell);
  115397. if( !cellContains(pRtree, &cell, pCell) ){
  115398. cellUnion(pRtree, &cell, pCell);
  115399. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  115400. }
  115401. p = pParent;
  115402. }
  115403. return SQLITE_OK;
  115404. }
  115405. /*
  115406. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  115407. */
  115408. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  115409. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  115410. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  115411. sqlite3_step(pRtree->pWriteRowid);
  115412. return sqlite3_reset(pRtree->pWriteRowid);
  115413. }
  115414. /*
  115415. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  115416. */
  115417. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  115418. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  115419. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  115420. sqlite3_step(pRtree->pWriteParent);
  115421. return sqlite3_reset(pRtree->pWriteParent);
  115422. }
  115423. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  115424. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  115425. /*
  115426. ** Implementation of the linear variant of the PickNext() function from
  115427. ** Guttman[84].
  115428. */
  115429. static RtreeCell *LinearPickNext(
  115430. Rtree *pRtree,
  115431. RtreeCell *aCell,
  115432. int nCell,
  115433. RtreeCell *pLeftBox,
  115434. RtreeCell *pRightBox,
  115435. int *aiUsed
  115436. ){
  115437. int ii;
  115438. for(ii=0; aiUsed[ii]; ii++);
  115439. aiUsed[ii] = 1;
  115440. return &aCell[ii];
  115441. }
  115442. /*
  115443. ** Implementation of the linear variant of the PickSeeds() function from
  115444. ** Guttman[84].
  115445. */
  115446. static void LinearPickSeeds(
  115447. Rtree *pRtree,
  115448. RtreeCell *aCell,
  115449. int nCell,
  115450. int *piLeftSeed,
  115451. int *piRightSeed
  115452. ){
  115453. int i;
  115454. int iLeftSeed = 0;
  115455. int iRightSeed = 1;
  115456. float maxNormalInnerWidth = 0.0;
  115457. /* Pick two "seed" cells from the array of cells. The algorithm used
  115458. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  115459. ** indices of the two seed cells in the array are stored in local
  115460. ** variables iLeftSeek and iRightSeed.
  115461. */
  115462. for(i=0; i<pRtree->nDim; i++){
  115463. float x1 = DCOORD(aCell[0].aCoord[i*2]);
  115464. float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
  115465. float x3 = x1;
  115466. float x4 = x2;
  115467. int jj;
  115468. int iCellLeft = 0;
  115469. int iCellRight = 0;
  115470. for(jj=1; jj<nCell; jj++){
  115471. float left = DCOORD(aCell[jj].aCoord[i*2]);
  115472. float right = DCOORD(aCell[jj].aCoord[i*2+1]);
  115473. if( left<x1 ) x1 = left;
  115474. if( right>x4 ) x4 = right;
  115475. if( left>x3 ){
  115476. x3 = left;
  115477. iCellRight = jj;
  115478. }
  115479. if( right<x2 ){
  115480. x2 = right;
  115481. iCellLeft = jj;
  115482. }
  115483. }
  115484. if( x4!=x1 ){
  115485. float normalwidth = (x3 - x2) / (x4 - x1);
  115486. if( normalwidth>maxNormalInnerWidth ){
  115487. iLeftSeed = iCellLeft;
  115488. iRightSeed = iCellRight;
  115489. }
  115490. }
  115491. }
  115492. *piLeftSeed = iLeftSeed;
  115493. *piRightSeed = iRightSeed;
  115494. }
  115495. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  115496. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  115497. /*
  115498. ** Implementation of the quadratic variant of the PickNext() function from
  115499. ** Guttman[84].
  115500. */
  115501. static RtreeCell *QuadraticPickNext(
  115502. Rtree *pRtree,
  115503. RtreeCell *aCell,
  115504. int nCell,
  115505. RtreeCell *pLeftBox,
  115506. RtreeCell *pRightBox,
  115507. int *aiUsed
  115508. ){
  115509. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  115510. int iSelect = -1;
  115511. float fDiff;
  115512. int ii;
  115513. for(ii=0; ii<nCell; ii++){
  115514. if( aiUsed[ii]==0 ){
  115515. float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  115516. float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  115517. float diff = FABS(right-left);
  115518. if( iSelect<0 || diff>fDiff ){
  115519. fDiff = diff;
  115520. iSelect = ii;
  115521. }
  115522. }
  115523. }
  115524. aiUsed[iSelect] = 1;
  115525. return &aCell[iSelect];
  115526. }
  115527. /*
  115528. ** Implementation of the quadratic variant of the PickSeeds() function from
  115529. ** Guttman[84].
  115530. */
  115531. static void QuadraticPickSeeds(
  115532. Rtree *pRtree,
  115533. RtreeCell *aCell,
  115534. int nCell,
  115535. int *piLeftSeed,
  115536. int *piRightSeed
  115537. ){
  115538. int ii;
  115539. int jj;
  115540. int iLeftSeed = 0;
  115541. int iRightSeed = 1;
  115542. float fWaste = 0.0;
  115543. for(ii=0; ii<nCell; ii++){
  115544. for(jj=ii+1; jj<nCell; jj++){
  115545. float right = cellArea(pRtree, &aCell[jj]);
  115546. float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  115547. float waste = growth - right;
  115548. if( waste>fWaste ){
  115549. iLeftSeed = ii;
  115550. iRightSeed = jj;
  115551. fWaste = waste;
  115552. }
  115553. }
  115554. }
  115555. *piLeftSeed = iLeftSeed;
  115556. *piRightSeed = iRightSeed;
  115557. }
  115558. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  115559. /*
  115560. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  115561. ** nIdx. The aIdx array contains the set of integers from 0 to
  115562. ** (nIdx-1) in no particular order. This function sorts the values
  115563. ** in aIdx according to the indexed values in aDistance. For
  115564. ** example, assuming the inputs:
  115565. **
  115566. ** aIdx = { 0, 1, 2, 3 }
  115567. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  115568. **
  115569. ** this function sets the aIdx array to contain:
  115570. **
  115571. ** aIdx = { 0, 1, 2, 3 }
  115572. **
  115573. ** The aSpare array is used as temporary working space by the
  115574. ** sorting algorithm.
  115575. */
  115576. static void SortByDistance(
  115577. int *aIdx,
  115578. int nIdx,
  115579. float *aDistance,
  115580. int *aSpare
  115581. ){
  115582. if( nIdx>1 ){
  115583. int iLeft = 0;
  115584. int iRight = 0;
  115585. int nLeft = nIdx/2;
  115586. int nRight = nIdx-nLeft;
  115587. int *aLeft = aIdx;
  115588. int *aRight = &aIdx[nLeft];
  115589. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  115590. SortByDistance(aRight, nRight, aDistance, aSpare);
  115591. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  115592. aLeft = aSpare;
  115593. while( iLeft<nLeft || iRight<nRight ){
  115594. if( iLeft==nLeft ){
  115595. aIdx[iLeft+iRight] = aRight[iRight];
  115596. iRight++;
  115597. }else if( iRight==nRight ){
  115598. aIdx[iLeft+iRight] = aLeft[iLeft];
  115599. iLeft++;
  115600. }else{
  115601. float fLeft = aDistance[aLeft[iLeft]];
  115602. float fRight = aDistance[aRight[iRight]];
  115603. if( fLeft<fRight ){
  115604. aIdx[iLeft+iRight] = aLeft[iLeft];
  115605. iLeft++;
  115606. }else{
  115607. aIdx[iLeft+iRight] = aRight[iRight];
  115608. iRight++;
  115609. }
  115610. }
  115611. }
  115612. #if 0
  115613. /* Check that the sort worked */
  115614. {
  115615. int jj;
  115616. for(jj=1; jj<nIdx; jj++){
  115617. float left = aDistance[aIdx[jj-1]];
  115618. float right = aDistance[aIdx[jj]];
  115619. assert( left<=right );
  115620. }
  115621. }
  115622. #endif
  115623. }
  115624. }
  115625. /*
  115626. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  115627. ** nIdx. The aIdx array contains the set of integers from 0 to
  115628. ** (nIdx-1) in no particular order. This function sorts the values
  115629. ** in aIdx according to dimension iDim of the cells in aCell. The
  115630. ** minimum value of dimension iDim is considered first, the
  115631. ** maximum used to break ties.
  115632. **
  115633. ** The aSpare array is used as temporary working space by the
  115634. ** sorting algorithm.
  115635. */
  115636. static void SortByDimension(
  115637. Rtree *pRtree,
  115638. int *aIdx,
  115639. int nIdx,
  115640. int iDim,
  115641. RtreeCell *aCell,
  115642. int *aSpare
  115643. ){
  115644. if( nIdx>1 ){
  115645. int iLeft = 0;
  115646. int iRight = 0;
  115647. int nLeft = nIdx/2;
  115648. int nRight = nIdx-nLeft;
  115649. int *aLeft = aIdx;
  115650. int *aRight = &aIdx[nLeft];
  115651. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  115652. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  115653. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  115654. aLeft = aSpare;
  115655. while( iLeft<nLeft || iRight<nRight ){
  115656. double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  115657. double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  115658. double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  115659. double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  115660. if( (iLeft!=nLeft) && ((iRight==nRight)
  115661. || (xleft1<xright1)
  115662. || (xleft1==xright1 && xleft2<xright2)
  115663. )){
  115664. aIdx[iLeft+iRight] = aLeft[iLeft];
  115665. iLeft++;
  115666. }else{
  115667. aIdx[iLeft+iRight] = aRight[iRight];
  115668. iRight++;
  115669. }
  115670. }
  115671. #if 0
  115672. /* Check that the sort worked */
  115673. {
  115674. int jj;
  115675. for(jj=1; jj<nIdx; jj++){
  115676. float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  115677. float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  115678. float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  115679. float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  115680. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  115681. }
  115682. }
  115683. #endif
  115684. }
  115685. }
  115686. #if VARIANT_RSTARTREE_SPLIT
  115687. /*
  115688. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  115689. */
  115690. static int splitNodeStartree(
  115691. Rtree *pRtree,
  115692. RtreeCell *aCell,
  115693. int nCell,
  115694. RtreeNode *pLeft,
  115695. RtreeNode *pRight,
  115696. RtreeCell *pBboxLeft,
  115697. RtreeCell *pBboxRight
  115698. ){
  115699. int **aaSorted;
  115700. int *aSpare;
  115701. int ii;
  115702. int iBestDim;
  115703. int iBestSplit;
  115704. float fBestMargin;
  115705. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  115706. aaSorted = (int **)sqlite3_malloc(nByte);
  115707. if( !aaSorted ){
  115708. return SQLITE_NOMEM;
  115709. }
  115710. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  115711. memset(aaSorted, 0, nByte);
  115712. for(ii=0; ii<pRtree->nDim; ii++){
  115713. int jj;
  115714. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  115715. for(jj=0; jj<nCell; jj++){
  115716. aaSorted[ii][jj] = jj;
  115717. }
  115718. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  115719. }
  115720. for(ii=0; ii<pRtree->nDim; ii++){
  115721. float margin = 0.0;
  115722. float fBestOverlap;
  115723. float fBestArea;
  115724. int iBestLeft;
  115725. int nLeft;
  115726. for(
  115727. nLeft=RTREE_MINCELLS(pRtree);
  115728. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  115729. nLeft++
  115730. ){
  115731. RtreeCell left;
  115732. RtreeCell right;
  115733. int kk;
  115734. float overlap;
  115735. float area;
  115736. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  115737. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  115738. for(kk=1; kk<(nCell-1); kk++){
  115739. if( kk<nLeft ){
  115740. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  115741. }else{
  115742. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  115743. }
  115744. }
  115745. margin += cellMargin(pRtree, &left);
  115746. margin += cellMargin(pRtree, &right);
  115747. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  115748. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  115749. if( (nLeft==RTREE_MINCELLS(pRtree))
  115750. || (overlap<fBestOverlap)
  115751. || (overlap==fBestOverlap && area<fBestArea)
  115752. ){
  115753. iBestLeft = nLeft;
  115754. fBestOverlap = overlap;
  115755. fBestArea = area;
  115756. }
  115757. }
  115758. if( ii==0 || margin<fBestMargin ){
  115759. iBestDim = ii;
  115760. fBestMargin = margin;
  115761. iBestSplit = iBestLeft;
  115762. }
  115763. }
  115764. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  115765. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  115766. for(ii=0; ii<nCell; ii++){
  115767. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  115768. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  115769. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  115770. nodeInsertCell(pRtree, pTarget, pCell);
  115771. cellUnion(pRtree, pBbox, pCell);
  115772. }
  115773. sqlite3_free(aaSorted);
  115774. return SQLITE_OK;
  115775. }
  115776. #endif
  115777. #if VARIANT_GUTTMAN_SPLIT
  115778. /*
  115779. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  115780. */
  115781. static int splitNodeGuttman(
  115782. Rtree *pRtree,
  115783. RtreeCell *aCell,
  115784. int nCell,
  115785. RtreeNode *pLeft,
  115786. RtreeNode *pRight,
  115787. RtreeCell *pBboxLeft,
  115788. RtreeCell *pBboxRight
  115789. ){
  115790. int iLeftSeed = 0;
  115791. int iRightSeed = 1;
  115792. int *aiUsed;
  115793. int i;
  115794. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  115795. if( !aiUsed ){
  115796. return SQLITE_NOMEM;
  115797. }
  115798. memset(aiUsed, 0, sizeof(int)*nCell);
  115799. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  115800. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  115801. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  115802. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  115803. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  115804. aiUsed[iLeftSeed] = 1;
  115805. aiUsed[iRightSeed] = 1;
  115806. for(i=nCell-2; i>0; i--){
  115807. RtreeCell *pNext;
  115808. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  115809. float diff =
  115810. cellGrowth(pRtree, pBboxLeft, pNext) -
  115811. cellGrowth(pRtree, pBboxRight, pNext)
  115812. ;
  115813. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  115814. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  115815. ){
  115816. nodeInsertCell(pRtree, pRight, pNext);
  115817. cellUnion(pRtree, pBboxRight, pNext);
  115818. }else{
  115819. nodeInsertCell(pRtree, pLeft, pNext);
  115820. cellUnion(pRtree, pBboxLeft, pNext);
  115821. }
  115822. }
  115823. sqlite3_free(aiUsed);
  115824. return SQLITE_OK;
  115825. }
  115826. #endif
  115827. static int updateMapping(
  115828. Rtree *pRtree,
  115829. i64 iRowid,
  115830. RtreeNode *pNode,
  115831. int iHeight
  115832. ){
  115833. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  115834. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  115835. if( iHeight>0 ){
  115836. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  115837. if( pChild ){
  115838. nodeRelease(pRtree, pChild->pParent);
  115839. nodeReference(pNode);
  115840. pChild->pParent = pNode;
  115841. }
  115842. }
  115843. return xSetMapping(pRtree, iRowid, pNode->iNode);
  115844. }
  115845. static int SplitNode(
  115846. Rtree *pRtree,
  115847. RtreeNode *pNode,
  115848. RtreeCell *pCell,
  115849. int iHeight
  115850. ){
  115851. int i;
  115852. int newCellIsRight = 0;
  115853. int rc = SQLITE_OK;
  115854. int nCell = NCELL(pNode);
  115855. RtreeCell *aCell;
  115856. int *aiUsed;
  115857. RtreeNode *pLeft = 0;
  115858. RtreeNode *pRight = 0;
  115859. RtreeCell leftbbox;
  115860. RtreeCell rightbbox;
  115861. /* Allocate an array and populate it with a copy of pCell and
  115862. ** all cells from node pLeft. Then zero the original node.
  115863. */
  115864. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  115865. if( !aCell ){
  115866. rc = SQLITE_NOMEM;
  115867. goto splitnode_out;
  115868. }
  115869. aiUsed = (int *)&aCell[nCell+1];
  115870. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  115871. for(i=0; i<nCell; i++){
  115872. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  115873. }
  115874. nodeZero(pRtree, pNode);
  115875. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  115876. nCell++;
  115877. if( pNode->iNode==1 ){
  115878. pRight = nodeNew(pRtree, pNode);
  115879. pLeft = nodeNew(pRtree, pNode);
  115880. pRtree->iDepth++;
  115881. pNode->isDirty = 1;
  115882. writeInt16(pNode->zData, pRtree->iDepth);
  115883. }else{
  115884. pLeft = pNode;
  115885. pRight = nodeNew(pRtree, pLeft->pParent);
  115886. nodeReference(pLeft);
  115887. }
  115888. if( !pLeft || !pRight ){
  115889. rc = SQLITE_NOMEM;
  115890. goto splitnode_out;
  115891. }
  115892. memset(pLeft->zData, 0, pRtree->iNodeSize);
  115893. memset(pRight->zData, 0, pRtree->iNodeSize);
  115894. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  115895. if( rc!=SQLITE_OK ){
  115896. goto splitnode_out;
  115897. }
  115898. /* Ensure both child nodes have node numbers assigned to them by calling
  115899. ** nodeWrite(). Node pRight always needs a node number, as it was created
  115900. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  115901. ** In this case avoid the all to nodeWrite().
  115902. */
  115903. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  115904. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  115905. ){
  115906. goto splitnode_out;
  115907. }
  115908. rightbbox.iRowid = pRight->iNode;
  115909. leftbbox.iRowid = pLeft->iNode;
  115910. if( pNode->iNode==1 ){
  115911. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  115912. if( rc!=SQLITE_OK ){
  115913. goto splitnode_out;
  115914. }
  115915. }else{
  115916. RtreeNode *pParent = pLeft->pParent;
  115917. int iCell;
  115918. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  115919. if( rc==SQLITE_OK ){
  115920. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  115921. rc = AdjustTree(pRtree, pParent, &leftbbox);
  115922. }
  115923. if( rc!=SQLITE_OK ){
  115924. goto splitnode_out;
  115925. }
  115926. }
  115927. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  115928. goto splitnode_out;
  115929. }
  115930. for(i=0; i<NCELL(pRight); i++){
  115931. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  115932. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  115933. if( iRowid==pCell->iRowid ){
  115934. newCellIsRight = 1;
  115935. }
  115936. if( rc!=SQLITE_OK ){
  115937. goto splitnode_out;
  115938. }
  115939. }
  115940. if( pNode->iNode==1 ){
  115941. for(i=0; i<NCELL(pLeft); i++){
  115942. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  115943. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  115944. if( rc!=SQLITE_OK ){
  115945. goto splitnode_out;
  115946. }
  115947. }
  115948. }else if( newCellIsRight==0 ){
  115949. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  115950. }
  115951. if( rc==SQLITE_OK ){
  115952. rc = nodeRelease(pRtree, pRight);
  115953. pRight = 0;
  115954. }
  115955. if( rc==SQLITE_OK ){
  115956. rc = nodeRelease(pRtree, pLeft);
  115957. pLeft = 0;
  115958. }
  115959. splitnode_out:
  115960. nodeRelease(pRtree, pRight);
  115961. nodeRelease(pRtree, pLeft);
  115962. sqlite3_free(aCell);
  115963. return rc;
  115964. }
  115965. /*
  115966. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  115967. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  115968. ** the pLeaf->pParent chain all the way up to the root node.
  115969. **
  115970. ** This operation is required when a row is deleted (or updated - an update
  115971. ** is implemented as a delete followed by an insert). SQLite provides the
  115972. ** rowid of the row to delete, which can be used to find the leaf on which
  115973. ** the entry resides (argument pLeaf). Once the leaf is located, this
  115974. ** function is called to determine its ancestry.
  115975. */
  115976. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  115977. int rc = SQLITE_OK;
  115978. RtreeNode *pChild = pLeaf;
  115979. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  115980. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  115981. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  115982. rc = sqlite3_step(pRtree->pReadParent);
  115983. if( rc==SQLITE_ROW ){
  115984. RtreeNode *pTest; /* Used to test for reference loops */
  115985. i64 iNode; /* Node number of parent node */
  115986. /* Before setting pChild->pParent, test that we are not creating a
  115987. ** loop of references (as we would if, say, pChild==pParent). We don't
  115988. ** want to do this as it leads to a memory leak when trying to delete
  115989. ** the referenced counted node structures.
  115990. */
  115991. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  115992. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  115993. if( !pTest ){
  115994. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  115995. }
  115996. }
  115997. rc = sqlite3_reset(pRtree->pReadParent);
  115998. if( rc==SQLITE_OK ) rc = rc2;
  115999. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
  116000. pChild = pChild->pParent;
  116001. }
  116002. return rc;
  116003. }
  116004. static int deleteCell(Rtree *, RtreeNode *, int, int);
  116005. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  116006. int rc;
  116007. int rc2;
  116008. RtreeNode *pParent;
  116009. int iCell;
  116010. assert( pNode->nRef==1 );
  116011. /* Remove the entry in the parent cell. */
  116012. rc = nodeParentIndex(pRtree, pNode, &iCell);
  116013. if( rc==SQLITE_OK ){
  116014. pParent = pNode->pParent;
  116015. pNode->pParent = 0;
  116016. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  116017. }
  116018. rc2 = nodeRelease(pRtree, pParent);
  116019. if( rc==SQLITE_OK ){
  116020. rc = rc2;
  116021. }
  116022. if( rc!=SQLITE_OK ){
  116023. return rc;
  116024. }
  116025. /* Remove the xxx_node entry. */
  116026. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  116027. sqlite3_step(pRtree->pDeleteNode);
  116028. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  116029. return rc;
  116030. }
  116031. /* Remove the xxx_parent entry. */
  116032. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  116033. sqlite3_step(pRtree->pDeleteParent);
  116034. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  116035. return rc;
  116036. }
  116037. /* Remove the node from the in-memory hash table and link it into
  116038. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  116039. */
  116040. nodeHashDelete(pRtree, pNode);
  116041. pNode->iNode = iHeight;
  116042. pNode->pNext = pRtree->pDeleted;
  116043. pNode->nRef++;
  116044. pRtree->pDeleted = pNode;
  116045. return SQLITE_OK;
  116046. }
  116047. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  116048. RtreeNode *pParent = pNode->pParent;
  116049. int rc = SQLITE_OK;
  116050. if( pParent ){
  116051. int ii;
  116052. int nCell = NCELL(pNode);
  116053. RtreeCell box; /* Bounding box for pNode */
  116054. nodeGetCell(pRtree, pNode, 0, &box);
  116055. for(ii=1; ii<nCell; ii++){
  116056. RtreeCell cell;
  116057. nodeGetCell(pRtree, pNode, ii, &cell);
  116058. cellUnion(pRtree, &box, &cell);
  116059. }
  116060. box.iRowid = pNode->iNode;
  116061. rc = nodeParentIndex(pRtree, pNode, &ii);
  116062. if( rc==SQLITE_OK ){
  116063. nodeOverwriteCell(pRtree, pParent, &box, ii);
  116064. rc = fixBoundingBox(pRtree, pParent);
  116065. }
  116066. }
  116067. return rc;
  116068. }
  116069. /*
  116070. ** Delete the cell at index iCell of node pNode. After removing the
  116071. ** cell, adjust the r-tree data structure if required.
  116072. */
  116073. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  116074. RtreeNode *pParent;
  116075. int rc;
  116076. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  116077. return rc;
  116078. }
  116079. /* Remove the cell from the node. This call just moves bytes around
  116080. ** the in-memory node image, so it cannot fail.
  116081. */
  116082. nodeDeleteCell(pRtree, pNode, iCell);
  116083. /* If the node is not the tree root and now has less than the minimum
  116084. ** number of cells, remove it from the tree. Otherwise, update the
  116085. ** cell in the parent node so that it tightly contains the updated
  116086. ** node.
  116087. */
  116088. pParent = pNode->pParent;
  116089. assert( pParent || pNode->iNode==1 );
  116090. if( pParent ){
  116091. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  116092. rc = removeNode(pRtree, pNode, iHeight);
  116093. }else{
  116094. rc = fixBoundingBox(pRtree, pNode);
  116095. }
  116096. }
  116097. return rc;
  116098. }
  116099. static int Reinsert(
  116100. Rtree *pRtree,
  116101. RtreeNode *pNode,
  116102. RtreeCell *pCell,
  116103. int iHeight
  116104. ){
  116105. int *aOrder;
  116106. int *aSpare;
  116107. RtreeCell *aCell;
  116108. float *aDistance;
  116109. int nCell;
  116110. float aCenterCoord[RTREE_MAX_DIMENSIONS];
  116111. int iDim;
  116112. int ii;
  116113. int rc = SQLITE_OK;
  116114. memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
  116115. nCell = NCELL(pNode)+1;
  116116. /* Allocate the buffers used by this operation. The allocation is
  116117. ** relinquished before this function returns.
  116118. */
  116119. aCell = (RtreeCell *)sqlite3_malloc(nCell * (
  116120. sizeof(RtreeCell) + /* aCell array */
  116121. sizeof(int) + /* aOrder array */
  116122. sizeof(int) + /* aSpare array */
  116123. sizeof(float) /* aDistance array */
  116124. ));
  116125. if( !aCell ){
  116126. return SQLITE_NOMEM;
  116127. }
  116128. aOrder = (int *)&aCell[nCell];
  116129. aSpare = (int *)&aOrder[nCell];
  116130. aDistance = (float *)&aSpare[nCell];
  116131. for(ii=0; ii<nCell; ii++){
  116132. if( ii==(nCell-1) ){
  116133. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  116134. }else{
  116135. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  116136. }
  116137. aOrder[ii] = ii;
  116138. for(iDim=0; iDim<pRtree->nDim; iDim++){
  116139. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  116140. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  116141. }
  116142. }
  116143. for(iDim=0; iDim<pRtree->nDim; iDim++){
  116144. aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
  116145. }
  116146. for(ii=0; ii<nCell; ii++){
  116147. aDistance[ii] = 0.0;
  116148. for(iDim=0; iDim<pRtree->nDim; iDim++){
  116149. float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  116150. DCOORD(aCell[ii].aCoord[iDim*2]);
  116151. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  116152. }
  116153. }
  116154. SortByDistance(aOrder, nCell, aDistance, aSpare);
  116155. nodeZero(pRtree, pNode);
  116156. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  116157. RtreeCell *p = &aCell[aOrder[ii]];
  116158. nodeInsertCell(pRtree, pNode, p);
  116159. if( p->iRowid==pCell->iRowid ){
  116160. if( iHeight==0 ){
  116161. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  116162. }else{
  116163. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  116164. }
  116165. }
  116166. }
  116167. if( rc==SQLITE_OK ){
  116168. rc = fixBoundingBox(pRtree, pNode);
  116169. }
  116170. for(; rc==SQLITE_OK && ii<nCell; ii++){
  116171. /* Find a node to store this cell in. pNode->iNode currently contains
  116172. ** the height of the sub-tree headed by the cell.
  116173. */
  116174. RtreeNode *pInsert;
  116175. RtreeCell *p = &aCell[aOrder[ii]];
  116176. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  116177. if( rc==SQLITE_OK ){
  116178. int rc2;
  116179. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  116180. rc2 = nodeRelease(pRtree, pInsert);
  116181. if( rc==SQLITE_OK ){
  116182. rc = rc2;
  116183. }
  116184. }
  116185. }
  116186. sqlite3_free(aCell);
  116187. return rc;
  116188. }
  116189. /*
  116190. ** Insert cell pCell into node pNode. Node pNode is the head of a
  116191. ** subtree iHeight high (leaf nodes have iHeight==0).
  116192. */
  116193. static int rtreeInsertCell(
  116194. Rtree *pRtree,
  116195. RtreeNode *pNode,
  116196. RtreeCell *pCell,
  116197. int iHeight
  116198. ){
  116199. int rc = SQLITE_OK;
  116200. if( iHeight>0 ){
  116201. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  116202. if( pChild ){
  116203. nodeRelease(pRtree, pChild->pParent);
  116204. nodeReference(pNode);
  116205. pChild->pParent = pNode;
  116206. }
  116207. }
  116208. if( nodeInsertCell(pRtree, pNode, pCell) ){
  116209. #if VARIANT_RSTARTREE_REINSERT
  116210. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  116211. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  116212. }else{
  116213. pRtree->iReinsertHeight = iHeight;
  116214. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  116215. }
  116216. #else
  116217. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  116218. #endif
  116219. }else{
  116220. rc = AdjustTree(pRtree, pNode, pCell);
  116221. if( rc==SQLITE_OK ){
  116222. if( iHeight==0 ){
  116223. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  116224. }else{
  116225. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  116226. }
  116227. }
  116228. }
  116229. return rc;
  116230. }
  116231. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  116232. int ii;
  116233. int rc = SQLITE_OK;
  116234. int nCell = NCELL(pNode);
  116235. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  116236. RtreeNode *pInsert;
  116237. RtreeCell cell;
  116238. nodeGetCell(pRtree, pNode, ii, &cell);
  116239. /* Find a node to store this cell in. pNode->iNode currently contains
  116240. ** the height of the sub-tree headed by the cell.
  116241. */
  116242. rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
  116243. if( rc==SQLITE_OK ){
  116244. int rc2;
  116245. rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
  116246. rc2 = nodeRelease(pRtree, pInsert);
  116247. if( rc==SQLITE_OK ){
  116248. rc = rc2;
  116249. }
  116250. }
  116251. }
  116252. return rc;
  116253. }
  116254. /*
  116255. ** Select a currently unused rowid for a new r-tree record.
  116256. */
  116257. static int newRowid(Rtree *pRtree, i64 *piRowid){
  116258. int rc;
  116259. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  116260. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  116261. sqlite3_step(pRtree->pWriteRowid);
  116262. rc = sqlite3_reset(pRtree->pWriteRowid);
  116263. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  116264. return rc;
  116265. }
  116266. /*
  116267. ** The xUpdate method for rtree module virtual tables.
  116268. */
  116269. static int rtreeUpdate(
  116270. sqlite3_vtab *pVtab,
  116271. int nData,
  116272. sqlite3_value **azData,
  116273. sqlite_int64 *pRowid
  116274. ){
  116275. Rtree *pRtree = (Rtree *)pVtab;
  116276. int rc = SQLITE_OK;
  116277. rtreeReference(pRtree);
  116278. assert(nData>=1);
  116279. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  116280. ** record to delete from the r-tree table. The following block does
  116281. ** just that.
  116282. */
  116283. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  116284. i64 iDelete; /* The rowid to delete */
  116285. RtreeNode *pLeaf; /* Leaf node containing record iDelete */
  116286. int iCell; /* Index of iDelete cell in pLeaf */
  116287. RtreeNode *pRoot;
  116288. /* Obtain a reference to the root node to initialise Rtree.iDepth */
  116289. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  116290. /* Obtain a reference to the leaf node that contains the entry
  116291. ** about to be deleted.
  116292. */
  116293. if( rc==SQLITE_OK ){
  116294. iDelete = sqlite3_value_int64(azData[0]);
  116295. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  116296. }
  116297. /* Delete the cell in question from the leaf node. */
  116298. if( rc==SQLITE_OK ){
  116299. int rc2;
  116300. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  116301. if( rc==SQLITE_OK ){
  116302. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  116303. }
  116304. rc2 = nodeRelease(pRtree, pLeaf);
  116305. if( rc==SQLITE_OK ){
  116306. rc = rc2;
  116307. }
  116308. }
  116309. /* Delete the corresponding entry in the <rtree>_rowid table. */
  116310. if( rc==SQLITE_OK ){
  116311. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  116312. sqlite3_step(pRtree->pDeleteRowid);
  116313. rc = sqlite3_reset(pRtree->pDeleteRowid);
  116314. }
  116315. /* Check if the root node now has exactly one child. If so, remove
  116316. ** it, schedule the contents of the child for reinsertion and
  116317. ** reduce the tree height by one.
  116318. **
  116319. ** This is equivalent to copying the contents of the child into
  116320. ** the root node (the operation that Gutman's paper says to perform
  116321. ** in this scenario).
  116322. */
  116323. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  116324. int rc2;
  116325. RtreeNode *pChild;
  116326. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  116327. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  116328. if( rc==SQLITE_OK ){
  116329. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  116330. }
  116331. rc2 = nodeRelease(pRtree, pChild);
  116332. if( rc==SQLITE_OK ) rc = rc2;
  116333. if( rc==SQLITE_OK ){
  116334. pRtree->iDepth--;
  116335. writeInt16(pRoot->zData, pRtree->iDepth);
  116336. pRoot->isDirty = 1;
  116337. }
  116338. }
  116339. /* Re-insert the contents of any underfull nodes removed from the tree. */
  116340. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  116341. if( rc==SQLITE_OK ){
  116342. rc = reinsertNodeContent(pRtree, pLeaf);
  116343. }
  116344. pRtree->pDeleted = pLeaf->pNext;
  116345. sqlite3_free(pLeaf);
  116346. }
  116347. /* Release the reference to the root node. */
  116348. if( rc==SQLITE_OK ){
  116349. rc = nodeRelease(pRtree, pRoot);
  116350. }else{
  116351. nodeRelease(pRtree, pRoot);
  116352. }
  116353. }
  116354. /* If the azData[] array contains more than one element, elements
  116355. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  116356. ** the r-tree structure.
  116357. */
  116358. if( rc==SQLITE_OK && nData>1 ){
  116359. /* Insert a new record into the r-tree */
  116360. RtreeCell cell;
  116361. int ii;
  116362. RtreeNode *pLeaf;
  116363. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  116364. assert( nData==(pRtree->nDim*2 + 3) );
  116365. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  116366. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  116367. cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
  116368. cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
  116369. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  116370. rc = SQLITE_CONSTRAINT;
  116371. goto constraint;
  116372. }
  116373. }
  116374. }else{
  116375. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  116376. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  116377. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  116378. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  116379. rc = SQLITE_CONSTRAINT;
  116380. goto constraint;
  116381. }
  116382. }
  116383. }
  116384. /* Figure out the rowid of the new row. */
  116385. if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
  116386. rc = newRowid(pRtree, &cell.iRowid);
  116387. }else{
  116388. cell.iRowid = sqlite3_value_int64(azData[2]);
  116389. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  116390. if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
  116391. sqlite3_reset(pRtree->pReadRowid);
  116392. rc = SQLITE_CONSTRAINT;
  116393. goto constraint;
  116394. }
  116395. rc = sqlite3_reset(pRtree->pReadRowid);
  116396. }
  116397. *pRowid = cell.iRowid;
  116398. if( rc==SQLITE_OK ){
  116399. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  116400. }
  116401. if( rc==SQLITE_OK ){
  116402. int rc2;
  116403. pRtree->iReinsertHeight = -1;
  116404. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  116405. rc2 = nodeRelease(pRtree, pLeaf);
  116406. if( rc==SQLITE_OK ){
  116407. rc = rc2;
  116408. }
  116409. }
  116410. }
  116411. constraint:
  116412. rtreeRelease(pRtree);
  116413. return rc;
  116414. }
  116415. /*
  116416. ** The xRename method for rtree module virtual tables.
  116417. */
  116418. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  116419. Rtree *pRtree = (Rtree *)pVtab;
  116420. int rc = SQLITE_NOMEM;
  116421. char *zSql = sqlite3_mprintf(
  116422. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  116423. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  116424. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  116425. , pRtree->zDb, pRtree->zName, zNewName
  116426. , pRtree->zDb, pRtree->zName, zNewName
  116427. , pRtree->zDb, pRtree->zName, zNewName
  116428. );
  116429. if( zSql ){
  116430. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  116431. sqlite3_free(zSql);
  116432. }
  116433. return rc;
  116434. }
  116435. static sqlite3_module rtreeModule = {
  116436. 0, /* iVersion */
  116437. rtreeCreate, /* xCreate - create a table */
  116438. rtreeConnect, /* xConnect - connect to an existing table */
  116439. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  116440. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  116441. rtreeDestroy, /* xDestroy - Drop a table */
  116442. rtreeOpen, /* xOpen - open a cursor */
  116443. rtreeClose, /* xClose - close a cursor */
  116444. rtreeFilter, /* xFilter - configure scan constraints */
  116445. rtreeNext, /* xNext - advance a cursor */
  116446. rtreeEof, /* xEof */
  116447. rtreeColumn, /* xColumn - read data */
  116448. rtreeRowid, /* xRowid - read data */
  116449. rtreeUpdate, /* xUpdate - write data */
  116450. 0, /* xBegin - begin transaction */
  116451. 0, /* xSync - sync transaction */
  116452. 0, /* xCommit - commit transaction */
  116453. 0, /* xRollback - rollback transaction */
  116454. 0, /* xFindFunction - function overloading */
  116455. rtreeRename /* xRename - rename the table */
  116456. };
  116457. static int rtreeSqlInit(
  116458. Rtree *pRtree,
  116459. sqlite3 *db,
  116460. const char *zDb,
  116461. const char *zPrefix,
  116462. int isCreate
  116463. ){
  116464. int rc = SQLITE_OK;
  116465. #define N_STATEMENT 9
  116466. static const char *azSql[N_STATEMENT] = {
  116467. /* Read and write the xxx_node table */
  116468. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  116469. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  116470. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  116471. /* Read and write the xxx_rowid table */
  116472. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  116473. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  116474. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  116475. /* Read and write the xxx_parent table */
  116476. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  116477. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  116478. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  116479. };
  116480. sqlite3_stmt **appStmt[N_STATEMENT];
  116481. int i;
  116482. pRtree->db = db;
  116483. if( isCreate ){
  116484. char *zCreate = sqlite3_mprintf(
  116485. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  116486. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  116487. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  116488. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  116489. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  116490. );
  116491. if( !zCreate ){
  116492. return SQLITE_NOMEM;
  116493. }
  116494. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  116495. sqlite3_free(zCreate);
  116496. if( rc!=SQLITE_OK ){
  116497. return rc;
  116498. }
  116499. }
  116500. appStmt[0] = &pRtree->pReadNode;
  116501. appStmt[1] = &pRtree->pWriteNode;
  116502. appStmt[2] = &pRtree->pDeleteNode;
  116503. appStmt[3] = &pRtree->pReadRowid;
  116504. appStmt[4] = &pRtree->pWriteRowid;
  116505. appStmt[5] = &pRtree->pDeleteRowid;
  116506. appStmt[6] = &pRtree->pReadParent;
  116507. appStmt[7] = &pRtree->pWriteParent;
  116508. appStmt[8] = &pRtree->pDeleteParent;
  116509. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  116510. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  116511. if( zSql ){
  116512. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  116513. }else{
  116514. rc = SQLITE_NOMEM;
  116515. }
  116516. sqlite3_free(zSql);
  116517. }
  116518. return rc;
  116519. }
  116520. /*
  116521. ** The second argument to this function contains the text of an SQL statement
  116522. ** that returns a single integer value. The statement is compiled and executed
  116523. ** using database connection db. If successful, the integer value returned
  116524. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  116525. ** code is returned and the value of *piVal after returning is not defined.
  116526. */
  116527. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  116528. int rc = SQLITE_NOMEM;
  116529. if( zSql ){
  116530. sqlite3_stmt *pStmt = 0;
  116531. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  116532. if( rc==SQLITE_OK ){
  116533. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  116534. *piVal = sqlite3_column_int(pStmt, 0);
  116535. }
  116536. rc = sqlite3_finalize(pStmt);
  116537. }
  116538. }
  116539. return rc;
  116540. }
  116541. /*
  116542. ** This function is called from within the xConnect() or xCreate() method to
  116543. ** determine the node-size used by the rtree table being created or connected
  116544. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  116545. ** Otherwise, an SQLite error code is returned.
  116546. **
  116547. ** If this function is being called as part of an xConnect(), then the rtree
  116548. ** table already exists. In this case the node-size is determined by inspecting
  116549. ** the root node of the tree.
  116550. **
  116551. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  116552. ** This ensures that each node is stored on a single database page. If the
  116553. ** database page-size is so large that more than RTREE_MAXCELLS entries
  116554. ** would fit in a single node, use a smaller node-size.
  116555. */
  116556. static int getNodeSize(
  116557. sqlite3 *db, /* Database handle */
  116558. Rtree *pRtree, /* Rtree handle */
  116559. int isCreate /* True for xCreate, false for xConnect */
  116560. ){
  116561. int rc;
  116562. char *zSql;
  116563. if( isCreate ){
  116564. int iPageSize;
  116565. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  116566. rc = getIntFromStmt(db, zSql, &iPageSize);
  116567. if( rc==SQLITE_OK ){
  116568. pRtree->iNodeSize = iPageSize-64;
  116569. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  116570. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  116571. }
  116572. }
  116573. }else{
  116574. zSql = sqlite3_mprintf(
  116575. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  116576. pRtree->zDb, pRtree->zName
  116577. );
  116578. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  116579. }
  116580. sqlite3_free(zSql);
  116581. return rc;
  116582. }
  116583. /*
  116584. ** This function is the implementation of both the xConnect and xCreate
  116585. ** methods of the r-tree virtual table.
  116586. **
  116587. ** argv[0] -> module name
  116588. ** argv[1] -> database name
  116589. ** argv[2] -> table name
  116590. ** argv[...] -> column names...
  116591. */
  116592. static int rtreeInit(
  116593. sqlite3 *db, /* Database connection */
  116594. void *pAux, /* One of the RTREE_COORD_* constants */
  116595. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  116596. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  116597. char **pzErr, /* OUT: Error message, if any */
  116598. int isCreate /* True for xCreate, false for xConnect */
  116599. ){
  116600. int rc = SQLITE_OK;
  116601. Rtree *pRtree;
  116602. int nDb; /* Length of string argv[1] */
  116603. int nName; /* Length of string argv[2] */
  116604. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  116605. const char *aErrMsg[] = {
  116606. 0, /* 0 */
  116607. "Wrong number of columns for an rtree table", /* 1 */
  116608. "Too few columns for an rtree table", /* 2 */
  116609. "Too many columns for an rtree table" /* 3 */
  116610. };
  116611. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  116612. if( aErrMsg[iErr] ){
  116613. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  116614. return SQLITE_ERROR;
  116615. }
  116616. /* Allocate the sqlite3_vtab structure */
  116617. nDb = strlen(argv[1]);
  116618. nName = strlen(argv[2]);
  116619. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  116620. if( !pRtree ){
  116621. return SQLITE_NOMEM;
  116622. }
  116623. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  116624. pRtree->nBusy = 1;
  116625. pRtree->base.pModule = &rtreeModule;
  116626. pRtree->zDb = (char *)&pRtree[1];
  116627. pRtree->zName = &pRtree->zDb[nDb+1];
  116628. pRtree->nDim = (argc-4)/2;
  116629. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  116630. pRtree->eCoordType = eCoordType;
  116631. memcpy(pRtree->zDb, argv[1], nDb);
  116632. memcpy(pRtree->zName, argv[2], nName);
  116633. /* Figure out the node size to use. */
  116634. rc = getNodeSize(db, pRtree, isCreate);
  116635. /* Create/Connect to the underlying relational database schema. If
  116636. ** that is successful, call sqlite3_declare_vtab() to configure
  116637. ** the r-tree table schema.
  116638. */
  116639. if( rc==SQLITE_OK ){
  116640. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  116641. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  116642. }else{
  116643. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  116644. char *zTmp;
  116645. int ii;
  116646. for(ii=4; zSql && ii<argc; ii++){
  116647. zTmp = zSql;
  116648. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  116649. sqlite3_free(zTmp);
  116650. }
  116651. if( zSql ){
  116652. zTmp = zSql;
  116653. zSql = sqlite3_mprintf("%s);", zTmp);
  116654. sqlite3_free(zTmp);
  116655. }
  116656. if( !zSql ){
  116657. rc = SQLITE_NOMEM;
  116658. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  116659. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  116660. }
  116661. sqlite3_free(zSql);
  116662. }
  116663. }
  116664. if( rc==SQLITE_OK ){
  116665. *ppVtab = (sqlite3_vtab *)pRtree;
  116666. }else{
  116667. rtreeRelease(pRtree);
  116668. }
  116669. return rc;
  116670. }
  116671. /*
  116672. ** Implementation of a scalar function that decodes r-tree nodes to
  116673. ** human readable strings. This can be used for debugging and analysis.
  116674. **
  116675. ** The scalar function takes two arguments, a blob of data containing
  116676. ** an r-tree node, and the number of dimensions the r-tree indexes.
  116677. ** For a two-dimensional r-tree structure called "rt", to deserialize
  116678. ** all nodes, a statement like:
  116679. **
  116680. ** SELECT rtreenode(2, data) FROM rt_node;
  116681. **
  116682. ** The human readable string takes the form of a Tcl list with one
  116683. ** entry for each cell in the r-tree node. Each entry is itself a
  116684. ** list, containing the 8-byte rowid/pageno followed by the
  116685. ** <num-dimension>*2 coordinates.
  116686. */
  116687. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  116688. char *zText = 0;
  116689. RtreeNode node;
  116690. Rtree tree;
  116691. int ii;
  116692. UNUSED_PARAMETER(nArg);
  116693. memset(&node, 0, sizeof(RtreeNode));
  116694. memset(&tree, 0, sizeof(Rtree));
  116695. tree.nDim = sqlite3_value_int(apArg[0]);
  116696. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  116697. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  116698. for(ii=0; ii<NCELL(&node); ii++){
  116699. char zCell[512];
  116700. int nCell = 0;
  116701. RtreeCell cell;
  116702. int jj;
  116703. nodeGetCell(&tree, &node, ii, &cell);
  116704. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  116705. nCell = strlen(zCell);
  116706. for(jj=0; jj<tree.nDim*2; jj++){
  116707. sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
  116708. nCell = strlen(zCell);
  116709. }
  116710. if( zText ){
  116711. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  116712. sqlite3_free(zText);
  116713. zText = zTextNew;
  116714. }else{
  116715. zText = sqlite3_mprintf("{%s}", zCell);
  116716. }
  116717. }
  116718. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  116719. }
  116720. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  116721. UNUSED_PARAMETER(nArg);
  116722. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  116723. || sqlite3_value_bytes(apArg[0])<2
  116724. ){
  116725. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  116726. }else{
  116727. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  116728. sqlite3_result_int(ctx, readInt16(zBlob));
  116729. }
  116730. }
  116731. /*
  116732. ** Register the r-tree module with database handle db. This creates the
  116733. ** virtual table module "rtree" and the debugging/analysis scalar
  116734. ** function "rtreenode".
  116735. */
  116736. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  116737. const int utf8 = SQLITE_UTF8;
  116738. int rc;
  116739. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  116740. if( rc==SQLITE_OK ){
  116741. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  116742. }
  116743. if( rc==SQLITE_OK ){
  116744. void *c = (void *)RTREE_COORD_REAL32;
  116745. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  116746. }
  116747. if( rc==SQLITE_OK ){
  116748. void *c = (void *)RTREE_COORD_INT32;
  116749. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  116750. }
  116751. return rc;
  116752. }
  116753. /*
  116754. ** A version of sqlite3_free() that can be used as a callback. This is used
  116755. ** in two places - as the destructor for the blob value returned by the
  116756. ** invocation of a geometry function, and as the destructor for the geometry
  116757. ** functions themselves.
  116758. */
  116759. static void doSqlite3Free(void *p){
  116760. sqlite3_free(p);
  116761. }
  116762. /*
  116763. ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
  116764. ** scalar user function. This C function is the callback used for all such
  116765. ** registered SQL functions.
  116766. **
  116767. ** The scalar user functions return a blob that is interpreted by r-tree
  116768. ** table MATCH operators.
  116769. */
  116770. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  116771. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  116772. RtreeMatchArg *pBlob;
  116773. int nBlob;
  116774. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
  116775. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  116776. if( !pBlob ){
  116777. sqlite3_result_error_nomem(ctx);
  116778. }else{
  116779. int i;
  116780. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  116781. pBlob->xGeom = pGeomCtx->xGeom;
  116782. pBlob->pContext = pGeomCtx->pContext;
  116783. pBlob->nParam = nArg;
  116784. for(i=0; i<nArg; i++){
  116785. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  116786. }
  116787. sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
  116788. }
  116789. }
  116790. /*
  116791. ** Register a new geometry function for use with the r-tree MATCH operator.
  116792. */
  116793. SQLITE_API int sqlite3_rtree_geometry_callback(
  116794. sqlite3 *db,
  116795. const char *zGeom,
  116796. int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
  116797. void *pContext
  116798. ){
  116799. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  116800. /* Allocate and populate the context object. */
  116801. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  116802. if( !pGeomCtx ) return SQLITE_NOMEM;
  116803. pGeomCtx->xGeom = xGeom;
  116804. pGeomCtx->pContext = pContext;
  116805. /* Create the new user-function. Register a destructor function to delete
  116806. ** the context object when it is no longer required. */
  116807. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  116808. (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
  116809. );
  116810. }
  116811. #if !SQLITE_CORE
  116812. SQLITE_API int sqlite3_extension_init(
  116813. sqlite3 *db,
  116814. char **pzErrMsg,
  116815. const sqlite3_api_routines *pApi
  116816. ){
  116817. SQLITE_EXTENSION_INIT2(pApi)
  116818. return sqlite3RtreeInit(db);
  116819. }
  116820. #endif
  116821. #endif
  116822. /************** End of rtree.c ***********************************************/
  116823. /************** Begin file icu.c *********************************************/
  116824. /*
  116825. ** 2007 May 6
  116826. **
  116827. ** The author disclaims copyright to this source code. In place of
  116828. ** a legal notice, here is a blessing:
  116829. **
  116830. ** May you do good and not evil.
  116831. ** May you find forgiveness for yourself and forgive others.
  116832. ** May you share freely, never taking more than you give.
  116833. **
  116834. *************************************************************************
  116835. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  116836. **
  116837. ** This file implements an integration between the ICU library
  116838. ** ("International Components for Unicode", an open-source library
  116839. ** for handling unicode data) and SQLite. The integration uses
  116840. ** ICU to provide the following to SQLite:
  116841. **
  116842. ** * An implementation of the SQL regexp() function (and hence REGEXP
  116843. ** operator) using the ICU uregex_XX() APIs.
  116844. **
  116845. ** * Implementations of the SQL scalar upper() and lower() functions
  116846. ** for case mapping.
  116847. **
  116848. ** * Integration of ICU and SQLite collation seqences.
  116849. **
  116850. ** * An implementation of the LIKE operator that uses ICU to
  116851. ** provide case-independent matching.
  116852. */
  116853. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  116854. /* Include ICU headers */
  116855. #include <unicode/utypes.h>
  116856. #include <unicode/uregex.h>
  116857. #include <unicode/ustring.h>
  116858. #include <unicode/ucol.h>
  116859. #ifndef SQLITE_CORE
  116860. SQLITE_EXTENSION_INIT1
  116861. #else
  116862. #endif
  116863. /*
  116864. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  116865. ** operator.
  116866. */
  116867. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  116868. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  116869. #endif
  116870. /*
  116871. ** Version of sqlite3_free() that is always a function, never a macro.
  116872. */
  116873. static void xFree(void *p){
  116874. sqlite3_free(p);
  116875. }
  116876. /*
  116877. ** Compare two UTF-8 strings for equality where the first string is
  116878. ** a "LIKE" expression. Return true (1) if they are the same and
  116879. ** false (0) if they are different.
  116880. */
  116881. static int icuLikeCompare(
  116882. const uint8_t *zPattern, /* LIKE pattern */
  116883. const uint8_t *zString, /* The UTF-8 string to compare against */
  116884. const UChar32 uEsc /* The escape character */
  116885. ){
  116886. static const int MATCH_ONE = (UChar32)'_';
  116887. static const int MATCH_ALL = (UChar32)'%';
  116888. int iPattern = 0; /* Current byte index in zPattern */
  116889. int iString = 0; /* Current byte index in zString */
  116890. int prevEscape = 0; /* True if the previous character was uEsc */
  116891. while( zPattern[iPattern]!=0 ){
  116892. /* Read (and consume) the next character from the input pattern. */
  116893. UChar32 uPattern;
  116894. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  116895. assert(uPattern!=0);
  116896. /* There are now 4 possibilities:
  116897. **
  116898. ** 1. uPattern is an unescaped match-all character "%",
  116899. ** 2. uPattern is an unescaped match-one character "_",
  116900. ** 3. uPattern is an unescaped escape character, or
  116901. ** 4. uPattern is to be handled as an ordinary character
  116902. */
  116903. if( !prevEscape && uPattern==MATCH_ALL ){
  116904. /* Case 1. */
  116905. uint8_t c;
  116906. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  116907. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  116908. ** test string.
  116909. */
  116910. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  116911. if( c==MATCH_ONE ){
  116912. if( zString[iString]==0 ) return 0;
  116913. U8_FWD_1_UNSAFE(zString, iString);
  116914. }
  116915. iPattern++;
  116916. }
  116917. if( zPattern[iPattern]==0 ) return 1;
  116918. while( zString[iString] ){
  116919. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  116920. return 1;
  116921. }
  116922. U8_FWD_1_UNSAFE(zString, iString);
  116923. }
  116924. return 0;
  116925. }else if( !prevEscape && uPattern==MATCH_ONE ){
  116926. /* Case 2. */
  116927. if( zString[iString]==0 ) return 0;
  116928. U8_FWD_1_UNSAFE(zString, iString);
  116929. }else if( !prevEscape && uPattern==uEsc){
  116930. /* Case 3. */
  116931. prevEscape = 1;
  116932. }else{
  116933. /* Case 4. */
  116934. UChar32 uString;
  116935. U8_NEXT_UNSAFE(zString, iString, uString);
  116936. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  116937. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  116938. if( uString!=uPattern ){
  116939. return 0;
  116940. }
  116941. prevEscape = 0;
  116942. }
  116943. }
  116944. return zString[iString]==0;
  116945. }
  116946. /*
  116947. ** Implementation of the like() SQL function. This function implements
  116948. ** the build-in LIKE operator. The first argument to the function is the
  116949. ** pattern and the second argument is the string. So, the SQL statements:
  116950. **
  116951. ** A LIKE B
  116952. **
  116953. ** is implemented as like(B, A). If there is an escape character E,
  116954. **
  116955. ** A LIKE B ESCAPE E
  116956. **
  116957. ** is mapped to like(B, A, E).
  116958. */
  116959. static void icuLikeFunc(
  116960. sqlite3_context *context,
  116961. int argc,
  116962. sqlite3_value **argv
  116963. ){
  116964. const unsigned char *zA = sqlite3_value_text(argv[0]);
  116965. const unsigned char *zB = sqlite3_value_text(argv[1]);
  116966. UChar32 uEsc = 0;
  116967. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  116968. ** of deep recursion and N*N behavior in patternCompare().
  116969. */
  116970. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  116971. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  116972. return;
  116973. }
  116974. if( argc==3 ){
  116975. /* The escape character string must consist of a single UTF-8 character.
  116976. ** Otherwise, return an error.
  116977. */
  116978. int nE= sqlite3_value_bytes(argv[2]);
  116979. const unsigned char *zE = sqlite3_value_text(argv[2]);
  116980. int i = 0;
  116981. if( zE==0 ) return;
  116982. U8_NEXT(zE, i, nE, uEsc);
  116983. if( i!=nE){
  116984. sqlite3_result_error(context,
  116985. "ESCAPE expression must be a single character", -1);
  116986. return;
  116987. }
  116988. }
  116989. if( zA && zB ){
  116990. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  116991. }
  116992. }
  116993. /*
  116994. ** This function is called when an ICU function called from within
  116995. ** the implementation of an SQL scalar function returns an error.
  116996. **
  116997. ** The scalar function context passed as the first argument is
  116998. ** loaded with an error message based on the following two args.
  116999. */
  117000. static void icuFunctionError(
  117001. sqlite3_context *pCtx, /* SQLite scalar function context */
  117002. const char *zName, /* Name of ICU function that failed */
  117003. UErrorCode e /* Error code returned by ICU function */
  117004. ){
  117005. char zBuf[128];
  117006. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  117007. zBuf[127] = '\0';
  117008. sqlite3_result_error(pCtx, zBuf, -1);
  117009. }
  117010. /*
  117011. ** Function to delete compiled regexp objects. Registered as
  117012. ** a destructor function with sqlite3_set_auxdata().
  117013. */
  117014. static void icuRegexpDelete(void *p){
  117015. URegularExpression *pExpr = (URegularExpression *)p;
  117016. uregex_close(pExpr);
  117017. }
  117018. /*
  117019. ** Implementation of SQLite REGEXP operator. This scalar function takes
  117020. ** two arguments. The first is a regular expression pattern to compile
  117021. ** the second is a string to match against that pattern. If either
  117022. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  117023. ** is 1 if the string matches the pattern, or 0 otherwise.
  117024. **
  117025. ** SQLite maps the regexp() function to the regexp() operator such
  117026. ** that the following two are equivalent:
  117027. **
  117028. ** zString REGEXP zPattern
  117029. ** regexp(zPattern, zString)
  117030. **
  117031. ** Uses the following ICU regexp APIs:
  117032. **
  117033. ** uregex_open()
  117034. ** uregex_matches()
  117035. ** uregex_close()
  117036. */
  117037. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  117038. UErrorCode status = U_ZERO_ERROR;
  117039. URegularExpression *pExpr;
  117040. UBool res;
  117041. const UChar *zString = sqlite3_value_text16(apArg[1]);
  117042. (void)nArg; /* Unused parameter */
  117043. /* If the left hand side of the regexp operator is NULL,
  117044. ** then the result is also NULL.
  117045. */
  117046. if( !zString ){
  117047. return;
  117048. }
  117049. pExpr = sqlite3_get_auxdata(p, 0);
  117050. if( !pExpr ){
  117051. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  117052. if( !zPattern ){
  117053. return;
  117054. }
  117055. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  117056. if( U_SUCCESS(status) ){
  117057. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  117058. }else{
  117059. assert(!pExpr);
  117060. icuFunctionError(p, "uregex_open", status);
  117061. return;
  117062. }
  117063. }
  117064. /* Configure the text that the regular expression operates on. */
  117065. uregex_setText(pExpr, zString, -1, &status);
  117066. if( !U_SUCCESS(status) ){
  117067. icuFunctionError(p, "uregex_setText", status);
  117068. return;
  117069. }
  117070. /* Attempt the match */
  117071. res = uregex_matches(pExpr, 0, &status);
  117072. if( !U_SUCCESS(status) ){
  117073. icuFunctionError(p, "uregex_matches", status);
  117074. return;
  117075. }
  117076. /* Set the text that the regular expression operates on to a NULL
  117077. ** pointer. This is not really necessary, but it is tidier than
  117078. ** leaving the regular expression object configured with an invalid
  117079. ** pointer after this function returns.
  117080. */
  117081. uregex_setText(pExpr, 0, 0, &status);
  117082. /* Return 1 or 0. */
  117083. sqlite3_result_int(p, res ? 1 : 0);
  117084. }
  117085. /*
  117086. ** Implementations of scalar functions for case mapping - upper() and
  117087. ** lower(). Function upper() converts its input to upper-case (ABC).
  117088. ** Function lower() converts to lower-case (abc).
  117089. **
  117090. ** ICU provides two types of case mapping, "general" case mapping and
  117091. ** "language specific". Refer to ICU documentation for the differences
  117092. ** between the two.
  117093. **
  117094. ** To utilise "general" case mapping, the upper() or lower() scalar
  117095. ** functions are invoked with one argument:
  117096. **
  117097. ** upper('ABC') -> 'abc'
  117098. ** lower('abc') -> 'ABC'
  117099. **
  117100. ** To access ICU "language specific" case mapping, upper() or lower()
  117101. ** should be invoked with two arguments. The second argument is the name
  117102. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  117103. ** as the second argument is the same as invoking the 1 argument version
  117104. ** of upper() or lower().
  117105. **
  117106. ** lower('I', 'en_us') -> 'i'
  117107. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  117108. **
  117109. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  117110. */
  117111. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  117112. const UChar *zInput;
  117113. UChar *zOutput;
  117114. int nInput;
  117115. int nOutput;
  117116. UErrorCode status = U_ZERO_ERROR;
  117117. const char *zLocale = 0;
  117118. assert(nArg==1 || nArg==2);
  117119. if( nArg==2 ){
  117120. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  117121. }
  117122. zInput = sqlite3_value_text16(apArg[0]);
  117123. if( !zInput ){
  117124. return;
  117125. }
  117126. nInput = sqlite3_value_bytes16(apArg[0]);
  117127. nOutput = nInput * 2 + 2;
  117128. zOutput = sqlite3_malloc(nOutput);
  117129. if( !zOutput ){
  117130. return;
  117131. }
  117132. if( sqlite3_user_data(p) ){
  117133. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  117134. }else{
  117135. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  117136. }
  117137. if( !U_SUCCESS(status) ){
  117138. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  117139. return;
  117140. }
  117141. sqlite3_result_text16(p, zOutput, -1, xFree);
  117142. }
  117143. /*
  117144. ** Collation sequence destructor function. The pCtx argument points to
  117145. ** a UCollator structure previously allocated using ucol_open().
  117146. */
  117147. static void icuCollationDel(void *pCtx){
  117148. UCollator *p = (UCollator *)pCtx;
  117149. ucol_close(p);
  117150. }
  117151. /*
  117152. ** Collation sequence comparison function. The pCtx argument points to
  117153. ** a UCollator structure previously allocated using ucol_open().
  117154. */
  117155. static int icuCollationColl(
  117156. void *pCtx,
  117157. int nLeft,
  117158. const void *zLeft,
  117159. int nRight,
  117160. const void *zRight
  117161. ){
  117162. UCollationResult res;
  117163. UCollator *p = (UCollator *)pCtx;
  117164. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  117165. switch( res ){
  117166. case UCOL_LESS: return -1;
  117167. case UCOL_GREATER: return +1;
  117168. case UCOL_EQUAL: return 0;
  117169. }
  117170. assert(!"Unexpected return value from ucol_strcoll()");
  117171. return 0;
  117172. }
  117173. /*
  117174. ** Implementation of the scalar function icu_load_collation().
  117175. **
  117176. ** This scalar function is used to add ICU collation based collation
  117177. ** types to an SQLite database connection. It is intended to be called
  117178. ** as follows:
  117179. **
  117180. ** SELECT icu_load_collation(<locale>, <collation-name>);
  117181. **
  117182. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  117183. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  117184. ** collation sequence to create.
  117185. */
  117186. static void icuLoadCollation(
  117187. sqlite3_context *p,
  117188. int nArg,
  117189. sqlite3_value **apArg
  117190. ){
  117191. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  117192. UErrorCode status = U_ZERO_ERROR;
  117193. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  117194. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  117195. UCollator *pUCollator; /* ICU library collation object */
  117196. int rc; /* Return code from sqlite3_create_collation_x() */
  117197. assert(nArg==2);
  117198. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  117199. zName = (const char *)sqlite3_value_text(apArg[1]);
  117200. if( !zLocale || !zName ){
  117201. return;
  117202. }
  117203. pUCollator = ucol_open(zLocale, &status);
  117204. if( !U_SUCCESS(status) ){
  117205. icuFunctionError(p, "ucol_open", status);
  117206. return;
  117207. }
  117208. assert(p);
  117209. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  117210. icuCollationColl, icuCollationDel
  117211. );
  117212. if( rc!=SQLITE_OK ){
  117213. ucol_close(pUCollator);
  117214. sqlite3_result_error(p, "Error registering collation function", -1);
  117215. }
  117216. }
  117217. /*
  117218. ** Register the ICU extension functions with database db.
  117219. */
  117220. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  117221. struct IcuScalar {
  117222. const char *zName; /* Function name */
  117223. int nArg; /* Number of arguments */
  117224. int enc; /* Optimal text encoding */
  117225. void *pContext; /* sqlite3_user_data() context */
  117226. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  117227. } scalars[] = {
  117228. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  117229. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  117230. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  117231. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  117232. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  117233. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  117234. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  117235. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  117236. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  117237. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  117238. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  117239. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  117240. };
  117241. int rc = SQLITE_OK;
  117242. int i;
  117243. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  117244. struct IcuScalar *p = &scalars[i];
  117245. rc = sqlite3_create_function(
  117246. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  117247. );
  117248. }
  117249. return rc;
  117250. }
  117251. #if !SQLITE_CORE
  117252. SQLITE_API int sqlite3_extension_init(
  117253. sqlite3 *db,
  117254. char **pzErrMsg,
  117255. const sqlite3_api_routines *pApi
  117256. ){
  117257. SQLITE_EXTENSION_INIT2(pApi)
  117258. return sqlite3IcuInit(db);
  117259. }
  117260. #endif
  117261. #endif
  117262. /************** End of icu.c *************************************************/
  117263. /************** Begin file fts3_icu.c ****************************************/
  117264. /*
  117265. ** 2007 June 22
  117266. **
  117267. ** The author disclaims copyright to this source code. In place of
  117268. ** a legal notice, here is a blessing:
  117269. **
  117270. ** May you do good and not evil.
  117271. ** May you find forgiveness for yourself and forgive others.
  117272. ** May you share freely, never taking more than you give.
  117273. **
  117274. *************************************************************************
  117275. ** This file implements a tokenizer for fts3 based on the ICU library.
  117276. **
  117277. ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
  117278. */
  117279. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  117280. #ifdef SQLITE_ENABLE_ICU
  117281. #include <unicode/ubrk.h>
  117282. #include <unicode/utf16.h>
  117283. typedef struct IcuTokenizer IcuTokenizer;
  117284. typedef struct IcuCursor IcuCursor;
  117285. struct IcuTokenizer {
  117286. sqlite3_tokenizer base;
  117287. char *zLocale;
  117288. };
  117289. struct IcuCursor {
  117290. sqlite3_tokenizer_cursor base;
  117291. UBreakIterator *pIter; /* ICU break-iterator object */
  117292. int nChar; /* Number of UChar elements in pInput */
  117293. UChar *aChar; /* Copy of input using utf-16 encoding */
  117294. int *aOffset; /* Offsets of each character in utf-8 input */
  117295. int nBuffer;
  117296. char *zBuffer;
  117297. int iToken;
  117298. };
  117299. /*
  117300. ** Create a new tokenizer instance.
  117301. */
  117302. static int icuCreate(
  117303. int argc, /* Number of entries in argv[] */
  117304. const char * const *argv, /* Tokenizer creation arguments */
  117305. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  117306. ){
  117307. IcuTokenizer *p;
  117308. int n = 0;
  117309. if( argc>0 ){
  117310. n = strlen(argv[0])+1;
  117311. }
  117312. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  117313. if( !p ){
  117314. return SQLITE_NOMEM;
  117315. }
  117316. memset(p, 0, sizeof(IcuTokenizer));
  117317. if( n ){
  117318. p->zLocale = (char *)&p[1];
  117319. memcpy(p->zLocale, argv[0], n);
  117320. }
  117321. *ppTokenizer = (sqlite3_tokenizer *)p;
  117322. return SQLITE_OK;
  117323. }
  117324. /*
  117325. ** Destroy a tokenizer
  117326. */
  117327. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  117328. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  117329. sqlite3_free(p);
  117330. return SQLITE_OK;
  117331. }
  117332. /*
  117333. ** Prepare to begin tokenizing a particular string. The input
  117334. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  117335. ** used to incrementally tokenize this string is returned in
  117336. ** *ppCursor.
  117337. */
  117338. static int icuOpen(
  117339. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  117340. const char *zInput, /* Input string */
  117341. int nInput, /* Length of zInput in bytes */
  117342. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  117343. ){
  117344. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  117345. IcuCursor *pCsr;
  117346. const int32_t opt = U_FOLD_CASE_DEFAULT;
  117347. UErrorCode status = U_ZERO_ERROR;
  117348. int nChar;
  117349. UChar32 c;
  117350. int iInput = 0;
  117351. int iOut = 0;
  117352. *ppCursor = 0;
  117353. if( nInput<0 ){
  117354. nInput = strlen(zInput);
  117355. }
  117356. nChar = nInput+1;
  117357. pCsr = (IcuCursor *)sqlite3_malloc(
  117358. sizeof(IcuCursor) + /* IcuCursor */
  117359. nChar * sizeof(UChar) + /* IcuCursor.aChar[] */
  117360. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  117361. );
  117362. if( !pCsr ){
  117363. return SQLITE_NOMEM;
  117364. }
  117365. memset(pCsr, 0, sizeof(IcuCursor));
  117366. pCsr->aChar = (UChar *)&pCsr[1];
  117367. pCsr->aOffset = (int *)&pCsr->aChar[nChar];
  117368. pCsr->aOffset[iOut] = iInput;
  117369. U8_NEXT(zInput, iInput, nInput, c);
  117370. while( c>0 ){
  117371. int isError = 0;
  117372. c = u_foldCase(c, opt);
  117373. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  117374. if( isError ){
  117375. sqlite3_free(pCsr);
  117376. return SQLITE_ERROR;
  117377. }
  117378. pCsr->aOffset[iOut] = iInput;
  117379. if( iInput<nInput ){
  117380. U8_NEXT(zInput, iInput, nInput, c);
  117381. }else{
  117382. c = 0;
  117383. }
  117384. }
  117385. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  117386. if( !U_SUCCESS(status) ){
  117387. sqlite3_free(pCsr);
  117388. return SQLITE_ERROR;
  117389. }
  117390. pCsr->nChar = iOut;
  117391. ubrk_first(pCsr->pIter);
  117392. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  117393. return SQLITE_OK;
  117394. }
  117395. /*
  117396. ** Close a tokenization cursor previously opened by a call to icuOpen().
  117397. */
  117398. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  117399. IcuCursor *pCsr = (IcuCursor *)pCursor;
  117400. ubrk_close(pCsr->pIter);
  117401. sqlite3_free(pCsr->zBuffer);
  117402. sqlite3_free(pCsr);
  117403. return SQLITE_OK;
  117404. }
  117405. /*
  117406. ** Extract the next token from a tokenization cursor.
  117407. */
  117408. static int icuNext(
  117409. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  117410. const char **ppToken, /* OUT: *ppToken is the token text */
  117411. int *pnBytes, /* OUT: Number of bytes in token */
  117412. int *piStartOffset, /* OUT: Starting offset of token */
  117413. int *piEndOffset, /* OUT: Ending offset of token */
  117414. int *piPosition /* OUT: Position integer of token */
  117415. ){
  117416. IcuCursor *pCsr = (IcuCursor *)pCursor;
  117417. int iStart = 0;
  117418. int iEnd = 0;
  117419. int nByte = 0;
  117420. while( iStart==iEnd ){
  117421. UChar32 c;
  117422. iStart = ubrk_current(pCsr->pIter);
  117423. iEnd = ubrk_next(pCsr->pIter);
  117424. if( iEnd==UBRK_DONE ){
  117425. return SQLITE_DONE;
  117426. }
  117427. while( iStart<iEnd ){
  117428. int iWhite = iStart;
  117429. U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  117430. if( u_isspace(c) ){
  117431. iStart = iWhite;
  117432. }else{
  117433. break;
  117434. }
  117435. }
  117436. assert(iStart<=iEnd);
  117437. }
  117438. do {
  117439. UErrorCode status = U_ZERO_ERROR;
  117440. if( nByte ){
  117441. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  117442. if( !zNew ){
  117443. return SQLITE_NOMEM;
  117444. }
  117445. pCsr->zBuffer = zNew;
  117446. pCsr->nBuffer = nByte;
  117447. }
  117448. u_strToUTF8(
  117449. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  117450. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  117451. &status /* Output success/failure */
  117452. );
  117453. } while( nByte>pCsr->nBuffer );
  117454. *ppToken = pCsr->zBuffer;
  117455. *pnBytes = nByte;
  117456. *piStartOffset = pCsr->aOffset[iStart];
  117457. *piEndOffset = pCsr->aOffset[iEnd];
  117458. *piPosition = pCsr->iToken++;
  117459. return SQLITE_OK;
  117460. }
  117461. /*
  117462. ** The set of routines that implement the simple tokenizer
  117463. */
  117464. static const sqlite3_tokenizer_module icuTokenizerModule = {
  117465. 0, /* iVersion */
  117466. icuCreate, /* xCreate */
  117467. icuDestroy, /* xCreate */
  117468. icuOpen, /* xOpen */
  117469. icuClose, /* xClose */
  117470. icuNext, /* xNext */
  117471. };
  117472. /*
  117473. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  117474. */
  117475. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  117476. sqlite3_tokenizer_module const**ppModule
  117477. ){
  117478. *ppModule = &icuTokenizerModule;
  117479. }
  117480. #endif /* defined(SQLITE_ENABLE_ICU) */
  117481. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  117482. /************** End of fts3_icu.c ********************************************/